diff --git a/tasks/agentescape-15-skeleton-3841189d/tests/grade.py b/tasks/agentescape-15-skeleton-3841189d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3841189d/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-15-skeleton-3841189d/tests/test.sh b/tasks/agentescape-15-skeleton-3841189d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3841189d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-3b64066d/environment/Dockerfile b/tasks/agentescape-15-skeleton-3b64066d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-3b64066d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/agent/cli.py b/tasks/agentescape-15-skeleton-3b64066d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-3b64066d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2974160df60898dd7c2a3f1117211626971ca5f1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d-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-15-skeleton-3b64066d/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ee72f20b33cdbfc9821a786680a297433ee1009d --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/scenario.json @@ -0,0 +1,948 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "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", + "calc_modexp", + "zip_unzip_item", + "calc_bigmul_37ca", + "zip_unzip_file", + "terminal_1", + "zip_unzip_file_cdbb", + "calc_bigmul_ef6f", + "item_10" + ], + "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" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "calc_bigmul_37ca": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "zip_unzip_file_cdbb": { + "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_bigmul_ef6f": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re", + "hex_result": "a1b2c3d4e5f609182736455463728190", + "math_token": "Math_Token_Verification_ID_99823" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "482910384756291038475629103847" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "SecurePassword_Access_Level_3" + }, + "init_outputs": {} + }, + "calc_bigmul_37ca": { + "init_inputs": { + "a": "837465102938475610293847561029" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "password": "Archive_Key_Alpha_Numeric_99" + }, + "init_outputs": { + "files": "extracted_manifest_v2.json" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Primary input slot configuration string.", + "slot_b": "102938475610293847561029384756" + }, + "init_outputs": { + "text_output": "Terminal output stream ready for data.", + "hex_output": "deadbeef1234567890abcdef12345678" + } + }, + "zip_unzip_file_cdbb": { + "init_inputs": { + "zip_id": "backup_archive_2023.zip", + "password": "Complex_Pass_Phrase_Variant_B" + }, + "init_outputs": { + "files": "restored_database_log.txt" + } + }, + "calc_bigmul_ef6f": { + "init_inputs": { + "a": "564738291029384756102938475610" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "314159265358979323846264338327" + } + } + }, + "intro_narrative": "The rain lashes against the foggy windows of your rundown detective agency. You've just received a mysterious anonymous package containing a collection of legacy tech and encrypted data fragments. The note attached is brief: 'They're covering up the syndicate's latest hit. Only you can piece this together.' Before you is a chaotic web of outdated extraction tools, corrupted drives, and cipher machines. Your objective is clear: navigate this labyrinth of digital evidence, route the fragmented data through the correct analysis tools, and reconstruct the final truth. You'll need to power up the main terminal to reveal the syndicate's secrets, but it's locked behind multiple layers of cryptographic dependencies. Time is running out before the trail goes completely cold. Connect the dots, Detective.", + "narrative_style": "detective" + }, + "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": "0" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f609182736455463728190" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Verification_ID_99823" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re", + "hex_result": "a1b2c3d4e5f609182736455463728190", + "math_token": "Math_Token_Verification_ID_99823" + } + }, + "narrative": "This is the Mainframe Terminal. It requires inputs from both the Quantum Decryptor and the Secondary Analyzer to finally crack the case." + }, + { + "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": "482910384756291038475629103847" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1931293756103776628497249362848837643123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "482910384756291038475629103847" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Decryptor. It requires inputs from both the Primary Analyzer and the Signal Amplifier." + }, + { + "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": "4453792234778588373496037784314675475267458714901" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Secondary Analyzer. It requires inputs from both the Primary Analyzer and the Data Combiner." + }, + { + "id": "calc_gcd_ff9d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 2306118487 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "177417766629876978243326804876114049272483316192486677704470" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Primary Analyzer. It requires inputs from both the Integrity Verifier and the Trace Multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1931293756103776628497249362848837643123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 2306118487 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4453792234778588373496037784314675475267458714901" + } + ], + "narrative": "This is the Data Combiner. It requires inputs from both the Signal Amplifier and the Integrity Verifier." + }, + { + "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 heavily Encrypted Drive containing classified suspect files. It buzzes faintly with stored data." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_manifest_v2.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword_Access_Level_3" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "SecurePassword_Access_Level_3" + }, + "outputs": {} + }, + "narrative": "This is the Deep Extraction Module. It requires input from the File Extractor to recover embedded physical traces." + }, + { + "id": "calc_bigmul_37ca", + "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": "837465102938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 2306118487 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1931293756103776628497249362848837643123" + } + ], + "init": { + "inputs": { + "a": "837465102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Signal Amplifier. It requires input from the Integrity Verifier to boost the digital signal." + }, + { + "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": "restored_database_log.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Archive_Key_Alpha_Numeric_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_v2.json" + } + ], + "init": { + "inputs": { + "password": "Archive_Key_Alpha_Numeric_99" + }, + "outputs": { + "files": "extracted_manifest_v2.json" + } + }, + "narrative": "This is the File Extractor. It requires input from the Archive Extractor to dig deeper into the compressed folders." + }, + { + "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": "deadbeef1234567890abcdef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "89749357" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2306118487 + } + ], + "narrative": "This is the Integrity Verifier. It requires input from the Entry Terminal to process the data." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Primary input slot configuration string." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output stream ready for data." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef1234567890abcdef12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Primary input slot configuration string.", + "slot_b": "102938475610293847561029384756" + }, + "outputs": { + "text_output": "Terminal output stream ready for data.", + "hex_output": "deadbeef1234567890abcdef12345678" + } + }, + "narrative": "An old Entry Terminal covered in dust. It looks like it still has power and awaits initial manual operation." + }, + { + "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 strange Hidden Cipher found tucked away in a drawer." + }, + { + "id": "zip_unzip_file_cdbb", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_archive_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Complex_Pass_Phrase_Variant_B" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "restored_database_log.txt" + } + ], + "init": { + "inputs": { + "zip_id": "backup_archive_2023.zip", + "password": "Complex_Pass_Phrase_Variant_B" + }, + "outputs": { + "files": "restored_database_log.txt" + } + }, + "narrative": "The Archive Extractor. A standalone machine used to pull basic locked files from cold storage." + }, + { + "id": "calc_bigmul_ef6f", + "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": "564738291029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "314159265358979323846264338327" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "177417766629876978243326804876114049272483316192486677704470" + } + ], + "init": { + "inputs": { + "a": "564738291029384756102938475610" + }, + "outputs": {} + }, + "narrative": "This is the Trace Multiplier. It requires input from the Evidence Tag to reconstruct the numeric sequence." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "314159265358979323846264338327" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "314159265358979323846264338327" + } + }, + "narrative": "A crumpled Evidence Tag with some faded numbers written across the bottom." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "calc_gcd_ff9d", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_gcd_ff9d", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul_37ca", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_37ca", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_ff9d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_item", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "calc_gcd_ff9d", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_cdbb", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_37ca", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_ef6f", + "target_id": "calc_gcd_ff9d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul_ef6f", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-3b64066d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/instruction.md b/tasks/agentescape-15-skeleton-3b64066d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/solution/oracle.py b/tasks/agentescape-15-skeleton-3b64066d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/solution/scenario.json b/tasks/agentescape-15-skeleton-3b64066d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ee72f20b33cdbfc9821a786680a297433ee1009d --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/solution/scenario.json @@ -0,0 +1,948 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "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", + "calc_modexp", + "zip_unzip_item", + "calc_bigmul_37ca", + "zip_unzip_file", + "terminal_1", + "zip_unzip_file_cdbb", + "calc_bigmul_ef6f", + "item_10" + ], + "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" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "calc_bigmul_37ca": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "zip_unzip_file_cdbb": { + "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_bigmul_ef6f": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re", + "hex_result": "a1b2c3d4e5f609182736455463728190", + "math_token": "Math_Token_Verification_ID_99823" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "482910384756291038475629103847" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "SecurePassword_Access_Level_3" + }, + "init_outputs": {} + }, + "calc_bigmul_37ca": { + "init_inputs": { + "a": "837465102938475610293847561029" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "password": "Archive_Key_Alpha_Numeric_99" + }, + "init_outputs": { + "files": "extracted_manifest_v2.json" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Primary input slot configuration string.", + "slot_b": "102938475610293847561029384756" + }, + "init_outputs": { + "text_output": "Terminal output stream ready for data.", + "hex_output": "deadbeef1234567890abcdef12345678" + } + }, + "zip_unzip_file_cdbb": { + "init_inputs": { + "zip_id": "backup_archive_2023.zip", + "password": "Complex_Pass_Phrase_Variant_B" + }, + "init_outputs": { + "files": "restored_database_log.txt" + } + }, + "calc_bigmul_ef6f": { + "init_inputs": { + "a": "564738291029384756102938475610" + }, + "init_outputs": {} + }, + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "314159265358979323846264338327" + } + } + }, + "intro_narrative": "The rain lashes against the foggy windows of your rundown detective agency. You've just received a mysterious anonymous package containing a collection of legacy tech and encrypted data fragments. The note attached is brief: 'They're covering up the syndicate's latest hit. Only you can piece this together.' Before you is a chaotic web of outdated extraction tools, corrupted drives, and cipher machines. Your objective is clear: navigate this labyrinth of digital evidence, route the fragmented data through the correct analysis tools, and reconstruct the final truth. You'll need to power up the main terminal to reveal the syndicate's secrets, but it's locked behind multiple layers of cryptographic dependencies. Time is running out before the trail goes completely cold. Connect the dots, Detective.", + "narrative_style": "detective" + }, + "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": "0" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f609182736455463728190" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Verification_ID_99823" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Au_Ag_Pt_Os_Ir_Rh_Pd_Re", + "hex_result": "a1b2c3d4e5f609182736455463728190", + "math_token": "Math_Token_Verification_ID_99823" + } + }, + "narrative": "This is the Mainframe Terminal. It requires inputs from both the Quantum Decryptor and the Secondary Analyzer to finally crack the case." + }, + { + "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": "482910384756291038475629103847" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1931293756103776628497249362848837643123" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "482910384756291038475629103847" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Decryptor. It requires inputs from both the Primary Analyzer and the Signal Amplifier." + }, + { + "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": "4453792234778588373496037784314675475267458714901" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Secondary Analyzer. It requires inputs from both the Primary Analyzer and the Data Combiner." + }, + { + "id": "calc_gcd_ff9d", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 2306118487 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "177417766629876978243326804876114049272483316192486677704470" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the Primary Analyzer. It requires inputs from both the Integrity Verifier and the Trace Multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "1931293756103776628497249362848837643123" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 2306118487 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4453792234778588373496037784314675475267458714901" + } + ], + "narrative": "This is the Data Combiner. It requires inputs from both the Signal Amplifier and the Integrity Verifier." + }, + { + "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 heavily Encrypted Drive containing classified suspect files. It buzzes faintly with stored data." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_manifest_v2.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword_Access_Level_3" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "SecurePassword_Access_Level_3" + }, + "outputs": {} + }, + "narrative": "This is the Deep Extraction Module. It requires input from the File Extractor to recover embedded physical traces." + }, + { + "id": "calc_bigmul_37ca", + "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": "837465102938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 2306118487 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1931293756103776628497249362848837643123" + } + ], + "init": { + "inputs": { + "a": "837465102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Signal Amplifier. It requires input from the Integrity Verifier to boost the digital signal." + }, + { + "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": "restored_database_log.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Archive_Key_Alpha_Numeric_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_v2.json" + } + ], + "init": { + "inputs": { + "password": "Archive_Key_Alpha_Numeric_99" + }, + "outputs": { + "files": "extracted_manifest_v2.json" + } + }, + "narrative": "This is the File Extractor. It requires input from the Archive Extractor to dig deeper into the compressed folders." + }, + { + "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": "deadbeef1234567890abcdef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "89749357" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2306118487 + } + ], + "narrative": "This is the Integrity Verifier. It requires input from the Entry Terminal to process the data." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Primary input slot configuration string." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal output stream ready for data." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef1234567890abcdef12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Primary input slot configuration string.", + "slot_b": "102938475610293847561029384756" + }, + "outputs": { + "text_output": "Terminal output stream ready for data.", + "hex_output": "deadbeef1234567890abcdef12345678" + } + }, + "narrative": "An old Entry Terminal covered in dust. It looks like it still has power and awaits initial manual operation." + }, + { + "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 strange Hidden Cipher found tucked away in a drawer." + }, + { + "id": "zip_unzip_file_cdbb", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_archive_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Complex_Pass_Phrase_Variant_B" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "restored_database_log.txt" + } + ], + "init": { + "inputs": { + "zip_id": "backup_archive_2023.zip", + "password": "Complex_Pass_Phrase_Variant_B" + }, + "outputs": { + "files": "restored_database_log.txt" + } + }, + "narrative": "The Archive Extractor. A standalone machine used to pull basic locked files from cold storage." + }, + { + "id": "calc_bigmul_ef6f", + "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": "564738291029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "314159265358979323846264338327" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "177417766629876978243326804876114049272483316192486677704470" + } + ], + "init": { + "inputs": { + "a": "564738291029384756102938475610" + }, + "outputs": {} + }, + "narrative": "This is the Trace Multiplier. It requires input from the Evidence Tag to reconstruct the numeric sequence." + }, + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "314159265358979323846264338327" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "314159265358979323846264338327" + } + }, + "narrative": "A crumpled Evidence Tag with some faded numbers written across the bottom." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "calc_gcd_ff9d", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_gcd_ff9d", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul_37ca", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_37ca", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_ff9d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_item", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "calc_gcd_ff9d", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_cdbb", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul_37ca", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_ef6f", + "target_id": "calc_gcd_ff9d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_10", + "target_id": "calc_bigmul_ef6f", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3b64066d/solution/solve.sh b/tasks/agentescape-15-skeleton-3b64066d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-3b64066d/task.toml b/tasks/agentescape-15-skeleton-3b64066d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d41881b753fb980ba6e7d016b47b7c2b56ed103 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "ae409fc721f32c324e399525551d3ad2fa6e9db6689008ec1525c896f1b8f311" +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-15-skeleton-3b64066d/tests/Dockerfile b/tasks/agentescape-15-skeleton-3b64066d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-3b64066d/tests/expected.json b/tasks/agentescape-15-skeleton-3b64066d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f6be25353b3d7911fd799cafb706d89130d5708f --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "ae409fc721f32c324e399525551d3ad2fa6e9db6689008ec1525c896f1b8f311", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3b64066d/tests/grade.py b/tasks/agentescape-15-skeleton-3b64066d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/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-15-skeleton-3b64066d/tests/test.sh b/tasks/agentescape-15-skeleton-3b64066d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3b64066d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-3c3b7112/environment/Dockerfile b/tasks/agentescape-15-skeleton-3c3b7112/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-3c3b7112/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/agent/cli.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-3c3b7112/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f3c9607c12c5b1a82f0de8afcb452116f9e00236 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112-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-15-skeleton-3c3b7112/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3b584ae6f0c9b863b8f8d2cdd001426e985e29f6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/scenario.json @@ -0,0 +1,925 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_9", + "win_condition": { + "type": "item_content", + "node_id": "item_9", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_9", + "unicode_norm", + "terminal_2", + "calc_inv_mod", + "graph_shortest_path", + "json_get", + "terminal_1", + "zip_unzip_file", + "item_4", + "checksum_crc32" + ], + "by_node": { + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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" + } + } + }, + "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": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "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_9": { + "init_inputs": {}, + "init_outputs": { + "content": "container_manifest_v2.json" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation sequence pending authorization.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_map.json" + }, + "init_outputs": { + "path": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]", + "cost": "58291" + } + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.config.parameters.coordinates" + }, + "init_outputs": { + "values": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Primary node ready. Destination parameter set.", + "hex_output": "abcd1234abcd1234", + "item_dispenser": "A dusty slot that refuses to open." + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "P@ssw0rd_2024!" + }, + "init_outputs": { + "files": "secure_data_dump.json" + } + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "archive_backup_v3.zip" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f67890" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the cold, blue glow of the defunct Arasaka Sub-Net server room. Rain drums rhythmically against the reinforced glass high above the neon-drenched sprawl of Neo-Veridia. You are a 'Diver,' a data archeologist hired to retrieve a legendary piece of pre-War tech: the data contents of a specific Neuro-Cortex Chip. The chip isn't just lying around; it has to be synthesized and programmed on-site using the facility's dormant industrial equipment. The room is filled with whirring processors, locked terminals, and cryptographic nodes. You must restore the data flow, bypass the security protocols, and fabricate the vessel to smuggle the data out before the intrusion countermeasures incinerate the room—and you along with it.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside", + "value": "synthesized_item_b6b4e0a034ed98d0" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "container_manifest_v2.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "container_manifest_v2.json" + } + }, + "narrative": "The Neuro-Cortex Chip. This serves as the final storage container for the extracted data." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Calculation sequence pending authorization." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_b6b4e0a034ed98d0" + } + ], + "narrative": "The Nano-Fabricator. A high-end industrial printer capable of molecular assembly. It requires a clean text blueprint from the Linguistic Purifier to begin construction." + }, + { + "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": "Calculation sequence pending authorization." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Calculation sequence pending authorization." + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "The Linguistic Purifier. A sanity-check module that standardizes code formats. It awaits raw text output from the Mainframe Access Node to process." + }, + { + "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": "58291" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "85052" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sequence pending authorization." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "11223344556677889900aabbccddeeff" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation sequence pending authorization.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "narrative": "The Mainframe Access Node. The central security hub of the room. It requires complex numerical keys derived from the Cryptographic Inverter and the Network Router to unlock its secrets." + }, + { + "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": "58291" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "85052" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Inverter. A specialized processor for modular arithmetic. It needs the path cost value calculated by the Network Router to generate the inverse key." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Primary node ready. Destination parameter set." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "58291" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json" + }, + "outputs": { + "path": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]", + "cost": "58291" + } + }, + "narrative": "The Network Router. A holographic mapping system for data packets. It requires coordinates from the Data Extractor and a destination target from the Sector Control Panel to compute the optimal path." + }, + { + "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": "secure_data_dump.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.config.parameters.coordinates" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.config.parameters.coordinates" + }, + "outputs": { + "values": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + }, + "narrative": "The Data Extractor. A script designed to parse structural logs. It requires the decompressed files from the Archive Decryptor to function." + }, + { + "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": "Security Protocol Delta. The final fragment of the administrative override key." + }, + { + "id": "item_8_4735", + "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": "Security Protocol Gamma. A segment of the administrative override key." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 405212579 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Primary node ready. Destination parameter set." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "abcd1234abcd1234" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A dusty slot that refuses to open." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Primary node ready. Destination parameter set.", + "hex_output": "abcd1234abcd1234", + "item_dispenser": "A dusty slot that refuses to open." + } + }, + "narrative": "The Sector Control Panel. A dual-input interface governing local sub-systems. It requires configuration strings from the Data Extractor and verification integers from the Integrity Scanner." + }, + { + "id": "item_8_19f1", + "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": "Security Protocol Beta. A segment of the administrative override key." + }, + { + "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_backup_v3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "P@ssw0rd_2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "secure_data_dump.json" + } + ], + "init": { + "inputs": { + "password": "P@ssw0rd_2024!" + }, + "outputs": { + "files": "secure_data_dump.json" + } + }, + "narrative": "The Archive Decryptor. A brute-force decryption tool for legacy storage formats. It requires the locked data file found inside the Black Box." + }, + { + "id": "item_8_22b9", + "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": "Security Protocol Alpha. The first segment of the administrative override key." + }, + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "archive_backup_v3.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "archive_backup_v3.zip" + } + }, + "narrative": "The Black Box. A heavily encrypted, blast-proof data container retrieved from a crashed corporate transport." + }, + { + "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": "a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "18270da3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 405212579 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f67890" + }, + "outputs": {} + }, + "narrative": "The Integrity Scanner. A diagnostic tool used to verify the validity of hexadecimal data streams." + } + ], + "edges": [ + { + "source_id": "matter_synthesizer", + "target_id": "item_9", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "container" + }, + { + "source_id": "unicode_norm", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "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_8", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_4735", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "terminal_1", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "dst" + }, + { + "source_id": "item_8_19f1", + "target_id": "item_8_4735", + "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": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8_22b9", + "target_id": "item_8_19f1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-3c3b7112/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/instruction.md b/tasks/agentescape-15-skeleton-3c3b7112/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/solution/oracle.py b/tasks/agentescape-15-skeleton-3c3b7112/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/solution/scenario.json b/tasks/agentescape-15-skeleton-3c3b7112/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3b584ae6f0c9b863b8f8d2cdd001426e985e29f6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/solution/scenario.json @@ -0,0 +1,925 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_9", + "win_condition": { + "type": "item_content", + "node_id": "item_9", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_9", + "unicode_norm", + "terminal_2", + "calc_inv_mod", + "graph_shortest_path", + "json_get", + "terminal_1", + "zip_unzip_file", + "item_4", + "checksum_crc32" + ], + "by_node": { + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "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" + } + } + }, + "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": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "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_9": { + "init_inputs": {}, + "init_outputs": { + "content": "container_manifest_v2.json" + } + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation sequence pending authorization.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_map.json" + }, + "init_outputs": { + "path": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]", + "cost": "58291" + } + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.config.parameters.coordinates" + }, + "init_outputs": { + "values": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Primary node ready. Destination parameter set.", + "hex_output": "abcd1234abcd1234", + "item_dispenser": "A dusty slot that refuses to open." + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "P@ssw0rd_2024!" + }, + "init_outputs": { + "files": "secure_data_dump.json" + } + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "archive_backup_v3.zip" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f67890" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the cold, blue glow of the defunct Arasaka Sub-Net server room. Rain drums rhythmically against the reinforced glass high above the neon-drenched sprawl of Neo-Veridia. You are a 'Diver,' a data archeologist hired to retrieve a legendary piece of pre-War tech: the data contents of a specific Neuro-Cortex Chip. The chip isn't just lying around; it has to be synthesized and programmed on-site using the facility's dormant industrial equipment. The room is filled with whirring processors, locked terminals, and cryptographic nodes. You must restore the data flow, bypass the security protocols, and fabricate the vessel to smuggle the data out before the intrusion countermeasures incinerate the room—and you along with it.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside", + "value": "synthesized_item_b6b4e0a034ed98d0" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "container_manifest_v2.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "container_manifest_v2.json" + } + }, + "narrative": "The Neuro-Cortex Chip. This serves as the final storage container for the extracted data." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Calculation sequence pending authorization." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_b6b4e0a034ed98d0" + } + ], + "narrative": "The Nano-Fabricator. A high-end industrial printer capable of molecular assembly. It requires a clean text blueprint from the Linguistic Purifier to begin construction." + }, + { + "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": "Calculation sequence pending authorization." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Calculation sequence pending authorization." + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "The Linguistic Purifier. A sanity-check module that standardizes code formats. It awaits raw text output from the Mainframe Access Node to process." + }, + { + "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": "58291" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "85052" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sequence pending authorization." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "11223344556677889900aabbccddeeff" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation sequence pending authorization.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "narrative": "The Mainframe Access Node. The central security hub of the room. It requires complex numerical keys derived from the Cryptographic Inverter and the Network Router to unlock its secrets." + }, + { + "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": "58291" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "85052" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Inverter. A specialized processor for modular arithmetic. It needs the path cost value calculated by the Network Router to generate the inverse key." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Primary node ready. Destination parameter set." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "58291" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json" + }, + "outputs": { + "path": "[\"Server_A\", \"Router_X\", \"Switch_09\", \"Gateway_N\", \"Server_B\"]", + "cost": "58291" + } + }, + "narrative": "The Network Router. A holographic mapping system for data packets. It requires coordinates from the Data Extractor and a destination target from the Sector Control Panel to compute the optimal path." + }, + { + "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": "secure_data_dump.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.config.parameters.coordinates" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + ], + "init": { + "inputs": { + "jsonpath": "$.config.parameters.coordinates" + }, + "outputs": { + "values": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + } + }, + "narrative": "The Data Extractor. A script designed to parse structural logs. It requires the decompressed files from the Archive Decryptor to function." + }, + { + "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": "Security Protocol Delta. The final fragment of the administrative override key." + }, + { + "id": "item_8_4735", + "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": "Security Protocol Gamma. A segment of the administrative override key." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "[\"10.0.0.1\", \"192.168.1.5\", \"172.16.0.25\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 405212579 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Primary node ready. Destination parameter set." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "abcd1234abcd1234" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A dusty slot that refuses to open." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Primary node ready. Destination parameter set.", + "hex_output": "abcd1234abcd1234", + "item_dispenser": "A dusty slot that refuses to open." + } + }, + "narrative": "The Sector Control Panel. A dual-input interface governing local sub-systems. It requires configuration strings from the Data Extractor and verification integers from the Integrity Scanner." + }, + { + "id": "item_8_19f1", + "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": "Security Protocol Beta. A segment of the administrative override key." + }, + { + "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_backup_v3.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "P@ssw0rd_2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "secure_data_dump.json" + } + ], + "init": { + "inputs": { + "password": "P@ssw0rd_2024!" + }, + "outputs": { + "files": "secure_data_dump.json" + } + }, + "narrative": "The Archive Decryptor. A brute-force decryption tool for legacy storage formats. It requires the locked data file found inside the Black Box." + }, + { + "id": "item_8_22b9", + "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": "Security Protocol Alpha. The first segment of the administrative override key." + }, + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "archive_backup_v3.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "archive_backup_v3.zip" + } + }, + "narrative": "The Black Box. A heavily encrypted, blast-proof data container retrieved from a crashed corporate transport." + }, + { + "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": "a1b2c3d4e5f67890" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "18270da3" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 405212579 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f67890" + }, + "outputs": {} + }, + "narrative": "The Integrity Scanner. A diagnostic tool used to verify the validity of hexadecimal data streams." + } + ], + "edges": [ + { + "source_id": "matter_synthesizer", + "target_id": "item_9", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "container" + }, + { + "source_id": "unicode_norm", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "blueprint" + }, + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "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_8", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_4735", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "terminal_1", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "dst" + }, + { + "source_id": "item_8_19f1", + "target_id": "item_8_4735", + "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": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8_22b9", + "target_id": "item_8_19f1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3c3b7112/solution/solve.sh b/tasks/agentescape-15-skeleton-3c3b7112/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-3c3b7112/task.toml b/tasks/agentescape-15-skeleton-3c3b7112/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90ec2977556339503ecdd540f64f49ad3ac7b319 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "2c3a064e86581a4af8a0fce451d55bcae7a58e1315e3fb7d3f1420d5963c7c88" +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-15-skeleton-3c3b7112/tests/Dockerfile b/tasks/agentescape-15-skeleton-3c3b7112/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-3c3b7112/tests/expected.json b/tasks/agentescape-15-skeleton-3c3b7112/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..92623b2cd28a381027330fd9895e15af417df3af --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "2c3a064e86581a4af8a0fce451d55bcae7a58e1315e3fb7d3f1420d5963c7c88", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-3c3b7112/tests/grade.py b/tasks/agentescape-15-skeleton-3c3b7112/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/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-15-skeleton-3c3b7112/tests/test.sh b/tasks/agentescape-15-skeleton-3c3b7112/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-3c3b7112/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-41513452/environment/Dockerfile b/tasks/agentescape-15-skeleton-41513452/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-41513452/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/agent/cli.py b/tasks/agentescape-15-skeleton-41513452/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-41513452/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c13891820a5b2c0395b28886e74a926d0dd2ad86 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452-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-15-skeleton-41513452/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f1653ececd2493e039631b4d9711aa09cc885dc8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/scenario.json @@ -0,0 +1,879 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "calc_bigmul", + "win_condition": { + "type": "tool_output", + "node_id": "calc_bigmul", + "output_port": "product", + "output_type": "Big_Int", + "description": "Execute Big Number Multiplier and get the output from port 'product'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp", + "calc_modexp_3eae", + "checksum_crc32", + "container_1", + "calc_inv_mod_bf70", + "calc_bigmul_e884", + "checksum_crc32_a0f5", + "terminal_1" + ], + "by_node": { + "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_3eae": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "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": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_bf70": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_e884": { + "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_a0f5": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + } + } + }, + "initial_values": { + "calc_modexp": { + "init_inputs": { + "mod": "918273645091827364501234" + }, + "init_outputs": {} + }, + "calc_modexp_3eae": { + "init_inputs": { + "exp": "102938475610293847565678" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafebabedeadbeefcafebabe" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "1122334455667788" + }, + "init_outputs": {} + }, + "calc_inv_mod_bf70": { + "init_inputs": { + "mod": "192837465019283746509999" + }, + "init_outputs": {} + }, + "calc_bigmul_e884": { + "init_inputs": { + "b": "564738291056473829104321" + }, + "init_outputs": {} + }, + "checksum_crc32_a0f5": { + "init_inputs": { + "hex": "00ff00ff00ff00ff12345678" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Initialization sequence alpha", + "slot_b": "888888888888888888888888" + }, + "init_outputs": { + "text_output": "Process completed successfully without errors.", + "hex_output": "abcdef0123456789" + } + } + }, + "intro_narrative": "You are a rogue hacker who has infiltrated the hidden underground server room of the elusive mega-corporation, OmniCorp. The air is cold, filled with the loud hum of cooling fans and the relentless blinking of massive server racks. Your mission is to bypass their multi-layered security network and extract the final system override key before the automated security sweep locks you inside forever. The room is scattered with various cryptographic modules, standalone validators, and encrypted data drives. You must trace the data flows, activate the correct sequences, and route the right signals into the right devices. Find a way to activate the ultimate override and secure your escape.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "16636997727183668330421759372130998875409423690059799034314421369942009" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "160849764713261360202412" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2676057169952557064178074242572313483650102717986903662914545587645903737407427118804941925708" + } + ], + "narrative": "This is the Core Override Processor. The ultimate system control node. It requires inputs from both the Firewall Breach Protocol and the Network 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "220698836" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "4" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "160849764713261360202412" + } + ], + "init": { + "inputs": { + "mod": "918273645091827364501234" + }, + "outputs": {} + }, + "narrative": "This is the Firewall Breach Protocol. A sophisticated intrusion software package. It requires inputs from both the Resonance Calibrator and the Logic Inverter." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "220698836" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1505266296" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "narrative": "This is the Resonance Calibrator. A synchronization unit for server frequencies. It requires inputs from both the Logic Inverter and the Quantum Exponentiator." + }, + { + "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": "1505266296" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1537536131 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "220698836" + } + ], + "narrative": "This is the Logic Inverter. A cybernetic decryption relay. It requires inputs from both the Quantum Exponentiator and the Secondary Hash Validator." + }, + { + "id": "calc_modexp_3eae", + "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": "16636997727183668330421759372130998875409423690059799034314421369942009" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "102938475610293847565678" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1537536131 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1505266296" + } + ], + "init": { + "inputs": { + "exp": "102938475610293847565678" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Exponentiator. A highly advanced encryption engine. It requires inputs from both the Secondary Hash Validator and the Network Multiplier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeefcafebabedeadbeefcafebabe" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5ba4f083" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1537536131 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabedeadbeefcafebabe" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Hash Validator. A backup data validation station used for secondary layer security." + }, + { + "id": "calc_bigmul_561c", + "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": "96930643579624209892649378071983457172190720917" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "171638164287201034744277" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "16636997727183668330421759372130998875409423690059799034314421369942009" + } + ], + "narrative": "This is the Network Multiplier. A bandwidth expansion device. It requires inputs from both the Security Reverser and the Data Amplifier." + }, + { + "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": "1122334455667788" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "1122334455667788" + }, + "outputs": {} + }, + "narrative": "This is the Biometric Lockbox. A sturdy titanium box secured with a fingerprint scanner." + }, + { + "id": "calc_inv_mod_bf70", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": 465438134 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "192837465019283746509999" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "171638164287201034744277" + } + ], + "init": { + "inputs": { + "mod": "192837465019283746509999" + }, + "outputs": {} + }, + "narrative": "This is the Security Reverser. A specialized cryptographic tool. It requires input from the Primary Hash 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": "This is an Encrypted Key Fob. A small digital device with a blank screen and no obvious ports." + }, + { + "id": "calc_bigmul_e884", + "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": "171638164287201034744277" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "564738291056473829104321" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "96930643579624209892649378071983457172190720917" + } + ], + "init": { + "inputs": { + "b": "564738291056473829104321" + }, + "outputs": {} + }, + "narrative": "This is the Data Amplifier. A signal boosting module. It requires input from the Security Reverser." + }, + { + "id": "checksum_crc32_a0f5", + "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": "00ff00ff00ff00ff12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1bbe05b6" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 465438134 + } + ], + "init": { + "inputs": { + "hex": "00ff00ff00ff00ff12345678" + }, + "outputs": {} + }, + "narrative": "This is the Primary Hash Validator. An offline data validation station used to verify initial data blocks." + }, + { + "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 Server Logs drive. A heavily encrypted digital text file containing time-stamped system events." + }, + { + "id": "item_8_be37", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is a Bypass Token. A sleek, metallic physical token with embedded micro-circuitry." + }, + { + "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": "Initialization sequence alpha" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "888888888888888888888888" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Process completed successfully without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "abcdef0123456789" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialization sequence alpha", + "slot_b": "888888888888888888888888" + }, + "outputs": { + "text_output": "Process completed successfully without errors.", + "hex_output": "abcdef0123456789" + } + }, + "narrative": "This is the Mainframe Access Terminal. A heavy-duty console used by system administrators to interface directly with the network." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_modexp_3eae", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_3eae", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3eae", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_561c", + "target_id": "calc_modexp_3eae", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_bf70", + "target_id": "calc_bigmul_561c", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_561c", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_e884", + "target_id": "calc_bigmul_561c", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_a0f5", + "target_id": "calc_inv_mod_bf70", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_bf70", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_bf70", + "target_id": "calc_bigmul_e884", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_561c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8_be37", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-41513452/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-41513452/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/instruction.md b/tasks/agentescape-15-skeleton-41513452/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/solution/oracle.py b/tasks/agentescape-15-skeleton-41513452/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/solution/scenario.json b/tasks/agentescape-15-skeleton-41513452/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f1653ececd2493e039631b4d9711aa09cc885dc8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/solution/scenario.json @@ -0,0 +1,879 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "calc_bigmul", + "win_condition": { + "type": "tool_output", + "node_id": "calc_bigmul", + "output_port": "product", + "output_type": "Big_Int", + "description": "Execute Big Number Multiplier and get the output from port 'product'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp", + "calc_modexp_3eae", + "checksum_crc32", + "container_1", + "calc_inv_mod_bf70", + "calc_bigmul_e884", + "checksum_crc32_a0f5", + "terminal_1" + ], + "by_node": { + "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_3eae": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "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": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_bf70": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul_e884": { + "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_a0f5": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + } + } + }, + "initial_values": { + "calc_modexp": { + "init_inputs": { + "mod": "918273645091827364501234" + }, + "init_outputs": {} + }, + "calc_modexp_3eae": { + "init_inputs": { + "exp": "102938475610293847565678" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafebabedeadbeefcafebabe" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "1122334455667788" + }, + "init_outputs": {} + }, + "calc_inv_mod_bf70": { + "init_inputs": { + "mod": "192837465019283746509999" + }, + "init_outputs": {} + }, + "calc_bigmul_e884": { + "init_inputs": { + "b": "564738291056473829104321" + }, + "init_outputs": {} + }, + "checksum_crc32_a0f5": { + "init_inputs": { + "hex": "00ff00ff00ff00ff12345678" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Initialization sequence alpha", + "slot_b": "888888888888888888888888" + }, + "init_outputs": { + "text_output": "Process completed successfully without errors.", + "hex_output": "abcdef0123456789" + } + } + }, + "intro_narrative": "You are a rogue hacker who has infiltrated the hidden underground server room of the elusive mega-corporation, OmniCorp. The air is cold, filled with the loud hum of cooling fans and the relentless blinking of massive server racks. Your mission is to bypass their multi-layered security network and extract the final system override key before the automated security sweep locks you inside forever. The room is scattered with various cryptographic modules, standalone validators, and encrypted data drives. You must trace the data flows, activate the correct sequences, and route the right signals into the right devices. Find a way to activate the ultimate override and secure your escape.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "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": "16636997727183668330421759372130998875409423690059799034314421369942009" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "160849764713261360202412" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2676057169952557064178074242572313483650102717986903662914545587645903737407427118804941925708" + } + ], + "narrative": "This is the Core Override Processor. The ultimate system control node. It requires inputs from both the Firewall Breach Protocol and the Network 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "220698836" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "4" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "160849764713261360202412" + } + ], + "init": { + "inputs": { + "mod": "918273645091827364501234" + }, + "outputs": {} + }, + "narrative": "This is the Firewall Breach Protocol. A sophisticated intrusion software package. It requires inputs from both the Resonance Calibrator and the Logic Inverter." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "220698836" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1505266296" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "narrative": "This is the Resonance Calibrator. A synchronization unit for server frequencies. It requires inputs from both the Logic Inverter and the Quantum Exponentiator." + }, + { + "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": "1505266296" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1537536131 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "220698836" + } + ], + "narrative": "This is the Logic Inverter. A cybernetic decryption relay. It requires inputs from both the Quantum Exponentiator and the Secondary Hash Validator." + }, + { + "id": "calc_modexp_3eae", + "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": "16636997727183668330421759372130998875409423690059799034314421369942009" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "102938475610293847565678" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1537536131 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1505266296" + } + ], + "init": { + "inputs": { + "exp": "102938475610293847565678" + }, + "outputs": {} + }, + "narrative": "This is the Quantum Exponentiator. A highly advanced encryption engine. It requires inputs from both the Secondary Hash Validator and the Network Multiplier." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeefcafebabedeadbeefcafebabe" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5ba4f083" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1537536131 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabedeadbeefcafebabe" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Hash Validator. A backup data validation station used for secondary layer security." + }, + { + "id": "calc_bigmul_561c", + "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": "96930643579624209892649378071983457172190720917" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "171638164287201034744277" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "16636997727183668330421759372130998875409423690059799034314421369942009" + } + ], + "narrative": "This is the Network Multiplier. A bandwidth expansion device. It requires inputs from both the Security Reverser and the Data Amplifier." + }, + { + "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": "1122334455667788" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "1122334455667788" + }, + "outputs": {} + }, + "narrative": "This is the Biometric Lockbox. A sturdy titanium box secured with a fingerprint scanner." + }, + { + "id": "calc_inv_mod_bf70", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": 465438134 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "192837465019283746509999" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "171638164287201034744277" + } + ], + "init": { + "inputs": { + "mod": "192837465019283746509999" + }, + "outputs": {} + }, + "narrative": "This is the Security Reverser. A specialized cryptographic tool. It requires input from the Primary Hash 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": "This is an Encrypted Key Fob. A small digital device with a blank screen and no obvious ports." + }, + { + "id": "calc_bigmul_e884", + "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": "171638164287201034744277" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "564738291056473829104321" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "96930643579624209892649378071983457172190720917" + } + ], + "init": { + "inputs": { + "b": "564738291056473829104321" + }, + "outputs": {} + }, + "narrative": "This is the Data Amplifier. A signal boosting module. It requires input from the Security Reverser." + }, + { + "id": "checksum_crc32_a0f5", + "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": "00ff00ff00ff00ff12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1bbe05b6" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 465438134 + } + ], + "init": { + "inputs": { + "hex": "00ff00ff00ff00ff12345678" + }, + "outputs": {} + }, + "narrative": "This is the Primary Hash Validator. An offline data validation station used to verify initial data blocks." + }, + { + "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 Server Logs drive. A heavily encrypted digital text file containing time-stamped system events." + }, + { + "id": "item_8_be37", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "This is a Bypass Token. A sleek, metallic physical token with embedded micro-circuitry." + }, + { + "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": "Initialization sequence alpha" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "888888888888888888888888" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Process completed successfully without errors." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "abcdef0123456789" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Initialization sequence alpha", + "slot_b": "888888888888888888888888" + }, + "outputs": { + "text_output": "Process completed successfully without errors.", + "hex_output": "abcdef0123456789" + } + }, + "narrative": "This is the Mainframe Access Terminal. A heavy-duty console used by system administrators to interface directly with the network." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_modexp_3eae", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_3eae", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3eae", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul_561c", + "target_id": "calc_modexp_3eae", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_bf70", + "target_id": "calc_bigmul_561c", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "b" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_561c", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_e884", + "target_id": "calc_bigmul_561c", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_a0f5", + "target_id": "calc_inv_mod_bf70", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_bf70", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_bf70", + "target_id": "calc_bigmul_e884", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_561c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8_be37", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-41513452/solution/solve.sh b/tasks/agentescape-15-skeleton-41513452/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-41513452/task.toml b/tasks/agentescape-15-skeleton-41513452/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c240f94f5d79745a617ac23f4c4f399e355db321 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "44b2b243a6246508ae69cba7cda06e221ac66105f27f07f8f44255ee08d87a52" +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-15-skeleton-41513452/tests/Dockerfile b/tasks/agentescape-15-skeleton-41513452/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-41513452/tests/expected.json b/tasks/agentescape-15-skeleton-41513452/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a278dc7fbb031da59c001564d876751b2663c670 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "44b2b243a6246508ae69cba7cda06e221ac66105f27f07f8f44255ee08d87a52", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-41513452/tests/grade.py b/tasks/agentescape-15-skeleton-41513452/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/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-15-skeleton-41513452/tests/test.sh b/tasks/agentescape-15-skeleton-41513452/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-41513452/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-420a410f/environment/Dockerfile b/tasks/agentescape-15-skeleton-420a410f/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-420a410f/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/agent/cli.py b/tasks/agentescape-15-skeleton-420a410f/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-420a410f/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..73f105c67b0cdc496b767d681d2f3febf867ee76 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f-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-15-skeleton-420a410f/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fca01bb7a0f1ec50eff7ebe16a5c1beef59bf444 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/scenario.json @@ -0,0 +1,977 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "container_3", + "win_condition": { + "type": "item_content", + "node_id": "container_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_3", + "terminal_2", + "calc_modexp", + "calc_gcd", + "calc_inv_mod", + "calc_modexp_4b06", + "num_base_convert_4975", + "container_4", + "calc_bigmul", + "num_base_convert_60f7", + "calc_bigmul_8a0c" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_modexp_4b06": { + "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": {} + }, + "num_base_convert_4975": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_60f7": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_bigmul_8a0c": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal active. Waiting for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "MathToken_XC928" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "8475629103847562910384" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "9182736450192837465012" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_modexp_4b06": { + "init_inputs": { + "exp": "2039485761203948576120", + "mod": "100003" + }, + "init_outputs": {} + }, + "num_base_convert_4975": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "hash_verification_scan_01" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "3847562910384756291038", + "b": "9283746501928374650192" + }, + "init_outputs": {} + }, + "num_base_convert_60f7": { + "init_inputs": { + "s": "5647382910564738291056", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_8a0c": { + "init_inputs": { + "b": "7465839201746583920174" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand within the Celestial Sanctum, the high tower of the ancient Archmage Arithmos. The room is filled with humming crystals, floating runes, and intricate machinery fueled by pure mana. Arithmos has vanished, leaving behind his greatest treasure locked within the Vault of Eternity. To open it, you must harmonize the flow of magical energy through the room's various artifacts. The machines are dormant or disjointed; only by channeling the correct magical values from one device to another can you reconstruct the sequence that unseals the vault. The air crackles with potential—the magic awaits your command.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "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": "1" + } + ], + "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": "The Vault of Eternity. The Archmage's final masterpiece, a floating safe reinforced by ancient magic. It requires the purified essence from the Essence Purifier to release its seal." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Scroll of Time. An ancient parchment recovered from the Oracle's Chest, bearing markings of different eras." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Oracle's Chest. A gilded chest sealed by a hexadecimal ward. It requires the specific hex code output from the Grand Oracle to unlock." + }, + { + "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": "426655022700731698887210179096672058609793" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "201950950407245095040706700" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal active. Waiting for data stream." + }, + { + "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": "MathToken_XC928" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal active. Waiting for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "MathToken_XC928" + } + }, + "narrative": "The Grand Oracle. A stone altar with a glowing interface, acting as the sanctum's central processor. It requires the synthesized data from the Tri-Element Converter and the Astral Projector." + }, + { + "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": "201950950407245095040706700" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27050" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "5647382910564738291056" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "201950950407245095040706700" + } + ], + "narrative": "The Tri-Element Converter. A complex gear-work device with three intake ports. It requires synchronized inputs from the Stellar Resonator, the Flux Transmuter, and the Harmonic 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "457259" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8475629103847562910384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "35719798710233837651681931723859574594579296" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "426655022700731698887210179096672058609793" + } + ], + "init": { + "inputs": { + "exp": "8475629103847562910384" + }, + "outputs": {} + }, + "narrative": "The Astral Projector. A massive telescope pointed at the night sky, awaiting coordinates. It requires stabilization data from the Void Inverter and power from the Ley Line Amplifier." + }, + { + "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": "9182736450192837465012" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "457259" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465012" + }, + "outputs": {} + }, + "narrative": "The Essence Purifier. A filtration basin that distills magic to its common denominator. It requires the translated values from the Rune Translator." + }, + { + "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": "5647382910564738291056" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "457259" + } + ], + "init": { + "inputs": { + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Void Inverter. A dark mirror that calculates the counter-balance of a spell. It requires the transmuted energy from the Flux Transmuter." + }, + { + "id": "calc_modexp_4b06", + "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": "426655022700731698887210179096672058609793" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2039485761203948576120" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "27050" + } + ], + "init": { + "inputs": { + "exp": "2039485761203948576120", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "The Stellar Resonator. A tuning fork made of starlight alloy. It requires the celestial coordinates from the Astral Projector to begin vibrating." + }, + { + "id": "num_base_convert_4975", + "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": "457259" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27050" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "457259" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Rune Translator. An enchanted slate that deciphers numerical prophecies. It requires inputs from the Void Inverter and the Stellar Resonator to interpret the script." + }, + { + "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": "hash_verification_scan_01" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "hash_verification_scan_01" + }, + "outputs": {} + }, + "narrative": "The Shadow Coffer. A small box seemingly woven from solidified shadows, secured by a complex verbal lock mechanism." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "3847562910384756291038" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9283746501928374650192" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "35719798710233837651681931723859574594579296" + } + ], + "init": { + "inputs": { + "a": "3847562910384756291038", + "b": "9283746501928374650192" + }, + "outputs": {} + }, + "narrative": "The Ley Line Amplifier. A heavy bronze pedestal that gathers raw ambient magic and multiplies its intensity." + }, + { + "id": "num_base_convert_60f7", + "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": "5647382910564738291056" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "35719798710233837651681931723859574594579296" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "5647382910564738291056" + } + ], + "init": { + "inputs": { + "s": "5647382910564738291056", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Flux Transmuter. A prism that shifts the form of magical energy. It requires a concentrated charge from the Ley Line Amplifier to function." + }, + { + "id": "calc_bigmul_8a0c", + "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": "27050" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "7465839201746583920174" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "201950950407245095040706700" + } + ], + "init": { + "inputs": { + "b": "7465839201746583920174" + }, + "outputs": {} + }, + "narrative": "The Harmonic Multiplier. A set of echoing crystals designed to expand a magical signal. It requires the specific frequency from the Stellar Resonator." + }, + { + "id": "item_16_34b4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Onyx Gem. A smooth, dark stone found resting on a velvet cushion." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_4975", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_4975", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "num_base_convert_4975", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "container_4", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_4b06", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "num_base_convert_60f7", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_8a0c", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "num_base_convert_60f7", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "calc_bigmul_8a0c", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_60f7", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "item_16_34b4", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-420a410f/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/instruction.md b/tasks/agentescape-15-skeleton-420a410f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/solution/oracle.py b/tasks/agentescape-15-skeleton-420a410f/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/solution/scenario.json b/tasks/agentescape-15-skeleton-420a410f/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fca01bb7a0f1ec50eff7ebe16a5c1beef59bf444 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/solution/scenario.json @@ -0,0 +1,977 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "container_3", + "win_condition": { + "type": "item_content", + "node_id": "container_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_3", + "terminal_2", + "calc_modexp", + "calc_gcd", + "calc_inv_mod", + "calc_modexp_4b06", + "num_base_convert_4975", + "container_4", + "calc_bigmul", + "num_base_convert_60f7", + "calc_bigmul_8a0c" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_modexp_4b06": { + "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": {} + }, + "num_base_convert_4975": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_60f7": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_bigmul_8a0c": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "π_e_φ_√2_ln3_sin1_cos0" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal active. Waiting for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "MathToken_XC928" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "8475629103847562910384" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "9182736450192837465012" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "999983" + }, + "init_outputs": {} + }, + "calc_modexp_4b06": { + "init_inputs": { + "exp": "2039485761203948576120", + "mod": "100003" + }, + "init_outputs": {} + }, + "num_base_convert_4975": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "hash_verification_scan_01" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "3847562910384756291038", + "b": "9283746501928374650192" + }, + "init_outputs": {} + }, + "num_base_convert_60f7": { + "init_inputs": { + "s": "5647382910564738291056", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_8a0c": { + "init_inputs": { + "b": "7465839201746583920174" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand within the Celestial Sanctum, the high tower of the ancient Archmage Arithmos. The room is filled with humming crystals, floating runes, and intricate machinery fueled by pure mana. Arithmos has vanished, leaving behind his greatest treasure locked within the Vault of Eternity. To open it, you must harmonize the flow of magical energy through the room's various artifacts. The machines are dormant or disjointed; only by channeling the correct magical values from one device to another can you reconstruct the sequence that unseals the vault. The air crackles with potential—the magic awaits your command.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "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": "1" + } + ], + "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": "The Vault of Eternity. The Archmage's final masterpiece, a floating safe reinforced by ancient magic. It requires the purified essence from the Essence Purifier to release its seal." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Scroll of Time. An ancient parchment recovered from the Oracle's Chest, bearing markings of different eras." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Oracle's Chest. A gilded chest sealed by a hexadecimal ward. It requires the specific hex code output from the Grand Oracle to unlock." + }, + { + "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": "426655022700731698887210179096672058609793" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "201950950407245095040706700" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal active. Waiting for data stream." + }, + { + "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": "MathToken_XC928" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal active. Waiting for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "math_token": "MathToken_XC928" + } + }, + "narrative": "The Grand Oracle. A stone altar with a glowing interface, acting as the sanctum's central processor. It requires the synthesized data from the Tri-Element Converter and the Astral Projector." + }, + { + "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": "201950950407245095040706700" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27050" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "5647382910564738291056" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "201950950407245095040706700" + } + ], + "narrative": "The Tri-Element Converter. A complex gear-work device with three intake ports. It requires synchronized inputs from the Stellar Resonator, the Flux Transmuter, and the Harmonic 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "457259" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8475629103847562910384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "35719798710233837651681931723859574594579296" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "426655022700731698887210179096672058609793" + } + ], + "init": { + "inputs": { + "exp": "8475629103847562910384" + }, + "outputs": {} + }, + "narrative": "The Astral Projector. A massive telescope pointed at the night sky, awaiting coordinates. It requires stabilization data from the Void Inverter and power from the Ley Line Amplifier." + }, + { + "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": "9182736450192837465012" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "457259" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465012" + }, + "outputs": {} + }, + "narrative": "The Essence Purifier. A filtration basin that distills magic to its common denominator. It requires the translated values from the Rune Translator." + }, + { + "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": "5647382910564738291056" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "457259" + } + ], + "init": { + "inputs": { + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Void Inverter. A dark mirror that calculates the counter-balance of a spell. It requires the transmuted energy from the Flux Transmuter." + }, + { + "id": "calc_modexp_4b06", + "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": "426655022700731698887210179096672058609793" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "2039485761203948576120" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "27050" + } + ], + "init": { + "inputs": { + "exp": "2039485761203948576120", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "The Stellar Resonator. A tuning fork made of starlight alloy. It requires the celestial coordinates from the Astral Projector to begin vibrating." + }, + { + "id": "num_base_convert_4975", + "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": "457259" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27050" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "457259" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Rune Translator. An enchanted slate that deciphers numerical prophecies. It requires inputs from the Void Inverter and the Stellar Resonator to interpret the script." + }, + { + "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": "hash_verification_scan_01" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "hash_verification_scan_01" + }, + "outputs": {} + }, + "narrative": "The Shadow Coffer. A small box seemingly woven from solidified shadows, secured by a complex verbal lock mechanism." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "3847562910384756291038" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9283746501928374650192" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "35719798710233837651681931723859574594579296" + } + ], + "init": { + "inputs": { + "a": "3847562910384756291038", + "b": "9283746501928374650192" + }, + "outputs": {} + }, + "narrative": "The Ley Line Amplifier. A heavy bronze pedestal that gathers raw ambient magic and multiplies its intensity." + }, + { + "id": "num_base_convert_60f7", + "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": "5647382910564738291056" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "35719798710233837651681931723859574594579296" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "5647382910564738291056" + } + ], + "init": { + "inputs": { + "s": "5647382910564738291056", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Flux Transmuter. A prism that shifts the form of magical energy. It requires a concentrated charge from the Ley Line Amplifier to function." + }, + { + "id": "calc_bigmul_8a0c", + "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": "27050" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "7465839201746583920174" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "201950950407245095040706700" + } + ], + "init": { + "inputs": { + "b": "7465839201746583920174" + }, + "outputs": {} + }, + "narrative": "The Harmonic Multiplier. A set of echoing crystals designed to expand a magical signal. It requires the specific frequency from the Stellar Resonator." + }, + { + "id": "item_16_34b4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Onyx Gem. A smooth, dark stone found resting on a velvet cushion." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_4975", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_4975", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "num_base_convert_4975", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "container_4", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_4b06", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "num_base_convert_60f7", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_8a0c", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "num_base_convert_60f7", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_modexp_4b06", + "target_id": "calc_bigmul_8a0c", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_60f7", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "item_16_34b4", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-420a410f/solution/solve.sh b/tasks/agentescape-15-skeleton-420a410f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-420a410f/task.toml b/tasks/agentescape-15-skeleton-420a410f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..70da2dce23995d055fd6c5412acccfb32146feb8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "08180a2fcfa76c7d8268fef74c350bc83fbddd488d9ea327d9292aa9a203515c" +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-15-skeleton-420a410f/tests/Dockerfile b/tasks/agentescape-15-skeleton-420a410f/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-420a410f/tests/expected.json b/tasks/agentescape-15-skeleton-420a410f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..848343a4b018080dae3bb770c4f38263651cdf31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "08180a2fcfa76c7d8268fef74c350bc83fbddd488d9ea327d9292aa9a203515c", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-420a410f/tests/grade.py b/tasks/agentescape-15-skeleton-420a410f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/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-15-skeleton-420a410f/tests/test.sh b/tasks/agentescape-15-skeleton-420a410f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-420a410f/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-4828aa13/environment/Dockerfile b/tasks/agentescape-15-skeleton-4828aa13/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-4828aa13/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/agent/cli.py b/tasks/agentescape-15-skeleton-4828aa13/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-4828aa13/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..860fd539408ae0963ee8810acc17339248827306 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13-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-15-skeleton-4828aa13/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3f82ca5c3f0e7a6cdebbe5d8230217d9e565c09e --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/scenario.json @@ -0,0 +1,895 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "csv_query", + "win_condition": { + "type": "tool_output", + "node_id": "csv_query", + "output_port": "rows", + "output_type": "Text_Generic", + "description": "Execute CSV Query and get the output from port 'rows'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "csv_query_1247", + "zip_unzip_file", + "text_xor_hex", + "container_4", + "zip_unzip_file_9cd5", + "zip_unzip_file_3ed0", + "zip_unzip_item", + "item_15" + ], + "by_node": { + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "csv_query_1247": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9cd5": { + "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" + } + } + }, + "zip_unzip_file_3ed0": { + "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" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + } + } + }, + "initial_values": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + }, + "csv_query_1247": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_dataset_2023.csv" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "4a6f686e20446f65", + "hex_b": "1122334455667788" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "fp_9a8b7c6d5e4f3a2b1c" + }, + "init_outputs": {} + }, + "zip_unzip_file_9cd5": { + "init_inputs": { + "zip_id": "archive_protected_v1.zip", + "password": "StrongPassword123!" + }, + "init_outputs": { + "files": "confidential_report.txt" + } + }, + "zip_unzip_file_3ed0": { + "init_inputs": { + "zip_id": "backup_logs_2024.zip", + "password": "admin_access_key" + }, + "init_outputs": { + "files": "system_trace.log" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "resources_bundle.zip", + "password": "Unlock_Resources_99" + }, + "init_outputs": {} + }, + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "Asia/Tokyo" + } + } + }, + "intro_narrative": "You have breached the server room of the Helios Corporation, a shadow organization accused of illicit neural experiments. The facility is in lockdown, red emergency lights pulsing against the cold steel of the server racks. Your objective is clear: retrieve the 'Project Chimera' subject list before the halon gas system triggers. The central mainframe is air-gapped and protected by layers of encryption and physical security. You must scavenge the room for credentials, decrypt the fragmented data streams, and piece together the access protocols to query the Master Database Terminal. Time is running out.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_dataset_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[M[*u\"\u0018" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + }, + "narrative": "The Master Database Terminal. This is your final objective. To execute the retrieval command, it requires the filtered dataset from Database Node A, the specific file handle from Archive Extractor B, and the column parameters from Text Converter A." + }, + { + "id": "csv_query_1247", + "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": "confidential_report.txt" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[M[*u\"\u0018" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "W01bKnUiGO0=" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + }, + "narrative": "Database Node A. This is an intermediate SQL processing unit. It constructs a query fragment. It requires the selection syntax from Text Converter B, the conditional logic from the Encoder Terminal, and the source file ID from the Main Server Archive." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "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 string", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "[M[*u\"\u0018" + } + ], + "narrative": "Text Converter B. A legacy decoding script running on a monochrome monitor. It needs the System Key to unlock. Once active, it processes the raw hex output from Decryption Module Alpha." + }, + { + "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": "system_trace.log" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "W01bKnUiGO0=" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_dataset_2023.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_dataset_2023.csv" + } + }, + "narrative": "Archive Extractor B. A secondary decompression utility. It requires the file reference from Archive Extractor A and the authorization string generated by the Encoder Terminal." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "W01bKnUiGO0=" + } + ], + "narrative": "The Encoder Terminal. A tablet running a format conversion tool. It requires the raw binary data output from Decryption Module Alpha to generate a readable string." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "4a6f686e20446f65" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "1122334455667788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "5b4d5b2a752218ed" + } + ], + "init": { + "inputs": { + "hex_a": "4a6f686e20446f65", + "hex_b": "1122334455667788" + }, + "outputs": {} + }, + "narrative": "Decryption Module Alpha. A dedicated cryptographic processor. It is currently locked and requires the hardware key from the Biometric Safe to activate. Once unlocked, it merges two hex data streams." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "fp_9a8b7c6d5e4f3a2b1c" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "fp_9a8b7c6d5e4f3a2b1c" + }, + "outputs": {} + }, + "narrative": "The Biometric Safe. A reinforced titanium box with a glowing fingerprint scanner. It requires a specific fingerprint hash to open and reveal its contents." + }, + { + "id": "zip_unzip_file_9cd5", + "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_protected_v1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "confidential_report.txt" + } + ], + "init": { + "inputs": { + "zip_id": "archive_protected_v1.zip", + "password": "StrongPassword123!" + }, + "outputs": { + "files": "confidential_report.txt" + } + }, + "narrative": "The Main Server Archive. The root file directory containing encrypted system logs and database files." + }, + { + "id": "zip_unzip_file_3ed0", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_logs_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "admin_access_key" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "system_trace.log" + } + ], + "init": { + "inputs": { + "zip_id": "backup_logs_2024.zip", + "password": "admin_access_key" + }, + "outputs": { + "files": "system_trace.log" + } + }, + "narrative": "Archive Extractor A. A locked file extraction protocol. It requires the rolling code from the Security Token to access the file system." + }, + { + "id": "hex_decode_ebfb", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "[M[*u\"\u0018" + } + ], + "narrative": "Text Converter A. A linguistic analysis tool. It requires the authorization item from the Secure Folder to function. It processes the raw hex data from Decryption Module Alpha." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The System Key. A digital clearance key extracted from the Backup Folder." + }, + { + "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 Security Token. A loose RSA hardware token found under a desk. It displays a changing integer." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "resources_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Resources_99" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "resources_bundle.zip", + "password": "Unlock_Resources_99" + }, + "outputs": {} + }, + "narrative": "The Backup Folder. An isolated backup partition containing system tools. It requires valid credentials to access the items inside." + }, + { + "id": "zip_unzip_item_b5c1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "confidential_report.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "The Secure Folder. A protected sub-directory. It requires the file path from the Main Server Archive and the credentials found on the Password Note." + }, + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "Asia/Tokyo" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "Asia/Tokyo" + } + }, + "narrative": "The Password Note. A yellow sticky note attached to a monitor with a complex string of characters written on it." + } + ], + "edges": [ + { + "source_id": "csv_query_1247", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "where" + }, + { + "source_id": "hex_decode", + "target_id": "csv_query_1247", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query_1247", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "where" + }, + { + "source_id": "container_4", + "target_id": "text_xor_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_9cd5", + "target_id": "csv_query_1247", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_3ed0", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hex_decode_ebfb", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "item_16", + "target_id": "hex_decode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode_ebfb", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file_3ed0", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item_b5c1", + "target_id": "hex_decode_ebfb", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_9cd5", + "target_id": "zip_unzip_item_b5c1", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_15", + "target_id": "zip_unzip_item_b5c1", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-4828aa13/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/instruction.md b/tasks/agentescape-15-skeleton-4828aa13/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/solution/oracle.py b/tasks/agentescape-15-skeleton-4828aa13/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/solution/scenario.json b/tasks/agentescape-15-skeleton-4828aa13/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3f82ca5c3f0e7a6cdebbe5d8230217d9e565c09e --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/solution/scenario.json @@ -0,0 +1,895 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "csv_query", + "win_condition": { + "type": "tool_output", + "node_id": "csv_query", + "output_port": "rows", + "output_type": "Text_Generic", + "description": "Execute CSV Query and get the output from port 'rows'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "csv_query_1247", + "zip_unzip_file", + "text_xor_hex", + "container_4", + "zip_unzip_file_9cd5", + "zip_unzip_file_3ed0", + "zip_unzip_item", + "item_15" + ], + "by_node": { + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "csv_query_1247": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9cd5": { + "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" + } + } + }, + "zip_unzip_file_3ed0": { + "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" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_15": { + "node_name": "", + "node_type": "Item", + "template_id": "item_15", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "Timezone text" + } + } + } + } + }, + "initial_values": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + }, + "csv_query_1247": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_dataset_2023.csv" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "4a6f686e20446f65", + "hex_b": "1122334455667788" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "fp_9a8b7c6d5e4f3a2b1c" + }, + "init_outputs": {} + }, + "zip_unzip_file_9cd5": { + "init_inputs": { + "zip_id": "archive_protected_v1.zip", + "password": "StrongPassword123!" + }, + "init_outputs": { + "files": "confidential_report.txt" + } + }, + "zip_unzip_file_3ed0": { + "init_inputs": { + "zip_id": "backup_logs_2024.zip", + "password": "admin_access_key" + }, + "init_outputs": { + "files": "system_trace.log" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "resources_bundle.zip", + "password": "Unlock_Resources_99" + }, + "init_outputs": {} + }, + "item_15": { + "init_inputs": {}, + "init_outputs": { + "content": "Asia/Tokyo" + } + } + }, + "intro_narrative": "You have breached the server room of the Helios Corporation, a shadow organization accused of illicit neural experiments. The facility is in lockdown, red emergency lights pulsing against the cold steel of the server racks. Your objective is clear: retrieve the 'Project Chimera' subject list before the halon gas system triggers. The central mainframe is air-gapped and protected by layers of encryption and physical security. You must scavenge the room for credentials, decrypt the fragmented data streams, and piece together the access protocols to query the Master Database Terminal. Time is running out.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "extracted_dataset_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[M[*u\"\u0018" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"name\": \"alpha\", \"score\": 98}, {\"id\": 102, \"name\": \"beta\", \"score\": 85}, {\"id\": 103, \"name\": \"gamma\", \"score\": 91}]" + } + }, + "narrative": "The Master Database Terminal. This is your final objective. To execute the retrieval command, it requires the filtered dataset from Database Node A, the specific file handle from Archive Extractor B, and the column parameters from Text Converter A." + }, + { + "id": "csv_query_1247", + "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": "confidential_report.txt" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "[M[*u\"\u0018" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "W01bKnUiGO0=" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"category\": \"A\", \"count\": 15}, {\"category\": \"B\", \"count\": 23}, {\"category\": \"C\", \"count\": 7}]" + } + }, + "narrative": "Database Node A. This is an intermediate SQL processing unit. It constructs a query fragment. It requires the selection syntax from Text Converter B, the conditional logic from the Encoder Terminal, and the source file ID from the Main Server Archive." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "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 string", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "[M[*u\"\u0018" + } + ], + "narrative": "Text Converter B. A legacy decoding script running on a monochrome monitor. It needs the System Key to unlock. Once active, it processes the raw hex output from Decryption Module Alpha." + }, + { + "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": "system_trace.log" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "W01bKnUiGO0=" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_dataset_2023.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_dataset_2023.csv" + } + }, + "narrative": "Archive Extractor B. A secondary decompression utility. It requires the file reference from Archive Extractor A and the authorization string generated by the Encoder Terminal." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "W01bKnUiGO0=" + } + ], + "narrative": "The Encoder Terminal. A tablet running a format conversion tool. It requires the raw binary data output from Decryption Module Alpha to generate a readable string." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "4a6f686e20446f65" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "1122334455667788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "5b4d5b2a752218ed" + } + ], + "init": { + "inputs": { + "hex_a": "4a6f686e20446f65", + "hex_b": "1122334455667788" + }, + "outputs": {} + }, + "narrative": "Decryption Module Alpha. A dedicated cryptographic processor. It is currently locked and requires the hardware key from the Biometric Safe to activate. Once unlocked, it merges two hex data streams." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "fp_9a8b7c6d5e4f3a2b1c" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "fp_9a8b7c6d5e4f3a2b1c" + }, + "outputs": {} + }, + "narrative": "The Biometric Safe. A reinforced titanium box with a glowing fingerprint scanner. It requires a specific fingerprint hash to open and reveal its contents." + }, + { + "id": "zip_unzip_file_9cd5", + "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_protected_v1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "confidential_report.txt" + } + ], + "init": { + "inputs": { + "zip_id": "archive_protected_v1.zip", + "password": "StrongPassword123!" + }, + "outputs": { + "files": "confidential_report.txt" + } + }, + "narrative": "The Main Server Archive. The root file directory containing encrypted system logs and database files." + }, + { + "id": "zip_unzip_file_3ed0", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "backup_logs_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "admin_access_key" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "system_trace.log" + } + ], + "init": { + "inputs": { + "zip_id": "backup_logs_2024.zip", + "password": "admin_access_key" + }, + "outputs": { + "files": "system_trace.log" + } + }, + "narrative": "Archive Extractor A. A locked file extraction protocol. It requires the rolling code from the Security Token to access the file system." + }, + { + "id": "hex_decode_ebfb", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "5b4d5b2a752218ed" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "[M[*u\"\u0018" + } + ], + "narrative": "Text Converter A. A linguistic analysis tool. It requires the authorization item from the Secure Folder to function. It processes the raw hex data from Decryption Module Alpha." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The System Key. A digital clearance key extracted from the Backup Folder." + }, + { + "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 Security Token. A loose RSA hardware token found under a desk. It displays a changing integer." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "resources_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Resources_99" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "resources_bundle.zip", + "password": "Unlock_Resources_99" + }, + "outputs": {} + }, + "narrative": "The Backup Folder. An isolated backup partition containing system tools. It requires valid credentials to access the items inside." + }, + { + "id": "zip_unzip_item_b5c1", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "confidential_report.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "The Secure Folder. A protected sub-directory. It requires the file path from the Main Server Archive and the credentials found on the Password Note." + }, + { + "id": "item_15", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_15", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "Timezone text", + "value": "Asia/Tokyo" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "Asia/Tokyo" + } + }, + "narrative": "The Password Note. A yellow sticky note attached to a monitor with a complex string of characters written on it." + } + ], + "edges": [ + { + "source_id": "csv_query_1247", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "where" + }, + { + "source_id": "hex_decode", + "target_id": "csv_query_1247", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query_1247", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "where" + }, + { + "source_id": "container_4", + "target_id": "text_xor_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_9cd5", + "target_id": "csv_query_1247", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_3ed0", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hex_decode_ebfb", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "item_16", + "target_id": "hex_decode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode_ebfb", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file_3ed0", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item_b5c1", + "target_id": "hex_decode_ebfb", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_9cd5", + "target_id": "zip_unzip_item_b5c1", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_15", + "target_id": "zip_unzip_item_b5c1", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-4828aa13/solution/solve.sh b/tasks/agentescape-15-skeleton-4828aa13/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-4828aa13/task.toml b/tasks/agentescape-15-skeleton-4828aa13/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e5adcaaab3447b25d80a549feaaeca00e489355 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "b171662fca63763f2abad2473e03e4b74b6a9be979b88f7b10571e76b4fb03a8" +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-15-skeleton-4828aa13/tests/Dockerfile b/tasks/agentescape-15-skeleton-4828aa13/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-4828aa13/tests/expected.json b/tasks/agentescape-15-skeleton-4828aa13/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ead56d6c5c4373c598e45c2692cbbfe1bf37461a --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "b171662fca63763f2abad2473e03e4b74b6a9be979b88f7b10571e76b4fb03a8", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-4828aa13/tests/grade.py b/tasks/agentescape-15-skeleton-4828aa13/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/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-15-skeleton-4828aa13/tests/test.sh b/tasks/agentescape-15-skeleton-4828aa13/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-4828aa13/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-53ca9853/environment/Dockerfile b/tasks/agentescape-15-skeleton-53ca9853/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-53ca9853/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/agent/cli.py b/tasks/agentescape-15-skeleton-53ca9853/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-53ca9853/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7397b4057fc0641d5970e3aea1be0a0cda6dfd5d --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853-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-15-skeleton-53ca9853/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..4aff1d0be9c7024beaf0f8acac63e7684d36161c --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/scenario.json @@ -0,0 +1,1159 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "container_3", + "win_condition": { + "type": "item_content", + "node_id": "container_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_3", + "terminal_2", + "graph_shortest_path", + "zip_unzip_file", + "num_base_convert_66ce", + "zip_unzip_item", + "terminal_1", + "time_convert", + "csv_query", + "calc_bigmul", + "graph_shortest_path_8352", + "checksum_crc32", + "calc_inv_mod" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert_66ce": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "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" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "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": {} + }, + "graph_shortest_path_8352": { + "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" + } + } + }, + "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": {} + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation paused. Waiting for complete numerical inputs.", + "hex_result": "4a6f686e20446f65205369676e6174757265" + } + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Termination_Point" + }, + "init_outputs": { + "path": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]", + "cost": "15420" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_backup.zip" + }, + "init_outputs": { + "files": "extracted_manifest.json" + } + }, + "num_base_convert_66ce": { + "init_inputs": { + "s": "82736451928374650129384765" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_payload_bundle.zip" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Primary command sequence initiated." + }, + "init_outputs": { + "text_output": "Terminal active. Please provide secondary slot input for execution.", + "hex_output": "deadbeefcafebabe12345678" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-11-15T09:45:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Tokyo" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "transactions_log.csv", + "select": "transaction_id, amount, status" + }, + "init_outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "9182736450192837465012938" + }, + "init_outputs": {} + }, + "graph_shortest_path_8352": { + "init_inputs": { + "file_id": "network_topology_v2.json", + "src": "Server_Alpha", + "dst": "Database_Omega" + }, + "init_outputs": { + "path": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]", + "cost": "2450" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "6574839201928374650192837", + "mod": "104729" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the airborne workshop of the late Inventor-General Archimedes Vance. Suspended miles above the smog-choked streets of New London in a decaying dirigible, this laboratory holds his greatest secret: the blueprints for an infinite clean energy engine, locked safely away inside The Brass Vault. As the airship's boiler pressure drops to critical levels, you have only a limited time to navigate his labyrinth of steam-powered contraptions and clockwork terminals. You must decipher the intricate connections between his aetheric inventions and restore the grand mechanism before the vessel plummets to the earth.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "82736451928374650129384765" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + }, + "narrative": "This is The Brass Vault, a heavy safe sealed with pneumatic locks. It requires input from The Resonance Tuner to release its final latches." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chrono-Parchment is a fragile, oil-stained document covered in fading mechanical schematics." + }, + { + "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": "15420" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "15627833792682515958895617773304738" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation paused. Waiting for complete numerical inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a6f686e20446f65205369676e6174757265" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation paused. Waiting for complete numerical inputs.", + "hex_result": "4a6f686e20446f65205369676e6174757265" + } + }, + "narrative": "This is The Aetheric Calculator, a brass-plated device with glowing vacuum tubes. It requires inputs from both The Navigator's Compass and The Cogwheel Translator to function." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_manifest.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Termination_Point" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15420" + } + ], + "init": { + "inputs": { + "dst": "Node_Termination_Point" + }, + "outputs": { + "path": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]", + "cost": "15420" + } + }, + "narrative": "This is The Navigator's Compass, a complex array of mechanical mapping rings. It requires inputs from The Steam-Driven Archive and The Punched Card Reader to chart a precise course." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "15627833792682515958895617773304738" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2450" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "15420" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "15627833792682515958895617773304738" + } + ], + "narrative": "This is The Cogwheel Translator, a massive gear-shifting mechanism. It requires inputs from The Navigator's Compass, The Multiplier Loom, and The Cartographer's Gyroscope to calibrate its gears." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal active. Please provide secondary slot input for execution." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_backup.zip" + }, + "outputs": { + "files": "extracted_manifest.json" + } + }, + "narrative": "This is The Steam-Driven Archive, a pressurized filing cabinet hissing with steam. It requires input from The Analytical Engine to unlock its document cylinders." + }, + { + "id": "num_base_convert_66ce", + "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": "82736451928374650129384765" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "15627833792682515958895617773304738" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "35306" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "82736451928374650129384765" + } + ], + "init": { + "inputs": { + "s": "82736451928374650129384765" + }, + "outputs": {} + }, + "narrative": "This is The Resonance Tuner, a delicate acoustic instrument with crystalline dials. It requires inputs from The Cogwheel Translator and The Phase Inverter to find the correct frequency." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "2023-11-15T18:45:00+09:00" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_payload_bundle.zip" + }, + "outputs": {} + }, + "narrative": "This is The Clockwork Lockbox, a small, intricately geared safe. It requires input from The Temporal Astrolabe to disengage its internal tumblers." + }, + { + "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": "Primary command sequence initiated." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "15627833792682515958895617773304738" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal active. Please provide secondary slot input for execution." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Primary command sequence initiated." + }, + "outputs": { + "text_output": "Terminal active. Please provide secondary slot input for execution.", + "hex_output": "deadbeefcafebabe12345678" + } + }, + "narrative": "This is The Analytical Engine, a towering machine clattering with thousands of brass switches. It requires input from The Multiplier Loom to begin its processing sequence." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-11-15T09:45:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-11-15T18:45:00+09:00" + } + ], + "init": { + "inputs": { + "iso": "2023-11-15T09:45:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Tokyo" + }, + "outputs": {} + }, + "narrative": "This is The Temporal Astrolabe, a complex handheld device with rotating celestial dials." + }, + { + "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": "transactions_log.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, amount, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Terminal active. Please provide secondary slot input for execution." + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + ], + "init": { + "inputs": { + "file_id": "transactions_log.csv", + "select": "transaction_id, amount, status" + }, + "outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + }, + "narrative": "This is The Punched Card Reader, a clanking machine that sorts through stacks of perforated brass sheets. It requires input from The Analytical Engine to filter the correct records." + }, + { + "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": "9182736450192837465012938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "15627833792682515958895617773304738" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465012938" + }, + "outputs": {} + }, + "narrative": "This is The Multiplier Loom, a sprawling apparatus of spinning bobbins and logic threads. It requires input from The Pressure Gauge Analyzer to set its initial weaving pattern." + }, + { + "id": "graph_shortest_path_8352", + "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_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Database_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "2450" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v2.json", + "src": "Server_Alpha", + "dst": "Database_Omega" + }, + "outputs": { + "path": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]", + "cost": "2450" + } + }, + "narrative": "This is The Cartographer's Gyroscope, a spinning brass globe suspended in a heavy iron gimbal." + }, + { + "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": "This is The Pressure Gauge Analyzer, a diagnostic tool attached to a series of copper pipes." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "6574839201928374650192837" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "35306" + } + ], + "init": { + "inputs": { + "a": "6574839201928374650192837", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is The Phase Inverter, a humming electrical generator with exposed copper coils and leaping sparks." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "num_base_convert_66ce", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_item", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_item", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_66ce", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "time_convert", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_8352", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "where" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_66ce", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-53ca9853/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/instruction.md b/tasks/agentescape-15-skeleton-53ca9853/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/solution/oracle.py b/tasks/agentescape-15-skeleton-53ca9853/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/solution/scenario.json b/tasks/agentescape-15-skeleton-53ca9853/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..4aff1d0be9c7024beaf0f8acac63e7684d36161c --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/solution/scenario.json @@ -0,0 +1,1159 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "container_3", + "win_condition": { + "type": "item_content", + "node_id": "container_3", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_3", + "terminal_2", + "graph_shortest_path", + "zip_unzip_file", + "num_base_convert_66ce", + "zip_unzip_item", + "terminal_1", + "time_convert", + "csv_query", + "calc_bigmul", + "graph_shortest_path_8352", + "checksum_crc32", + "calc_inv_mod" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert_66ce": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "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" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "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": {} + }, + "graph_shortest_path_8352": { + "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" + } + } + }, + "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": {} + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation paused. Waiting for complete numerical inputs.", + "hex_result": "4a6f686e20446f65205369676e6174757265" + } + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Termination_Point" + }, + "init_outputs": { + "path": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]", + "cost": "15420" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_data_backup.zip" + }, + "init_outputs": { + "files": "extracted_manifest.json" + } + }, + "num_base_convert_66ce": { + "init_inputs": { + "s": "82736451928374650129384765" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_payload_bundle.zip" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Primary command sequence initiated." + }, + "init_outputs": { + "text_output": "Terminal active. Please provide secondary slot input for execution.", + "hex_output": "deadbeefcafebabe12345678" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2023-11-15T09:45:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Tokyo" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "transactions_log.csv", + "select": "transaction_id, amount, status" + }, + "init_outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "9182736450192837465012938" + }, + "init_outputs": {} + }, + "graph_shortest_path_8352": { + "init_inputs": { + "file_id": "network_topology_v2.json", + "src": "Server_Alpha", + "dst": "Database_Omega" + }, + "init_outputs": { + "path": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]", + "cost": "2450" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "6574839201928374650192837", + "mod": "104729" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the airborne workshop of the late Inventor-General Archimedes Vance. Suspended miles above the smog-choked streets of New London in a decaying dirigible, this laboratory holds his greatest secret: the blueprints for an infinite clean energy engine, locked safely away inside The Brass Vault. As the airship's boiler pressure drops to critical levels, you have only a limited time to navigate his labyrinth of steam-powered contraptions and clockwork terminals. You must decipher the intricate connections between his aetheric inventions and restore the grand mechanism before the vessel plummets to the earth.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "82736451928374650129384765" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "Zorvath_Quixil_Nymphera_Vorthun_Kaelis" + } + }, + "narrative": "This is The Brass Vault, a heavy safe sealed with pneumatic locks. It requires input from The Resonance Tuner to release its final latches." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chrono-Parchment is a fragile, oil-stained document covered in fading mechanical schematics." + }, + { + "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": "15420" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "15627833792682515958895617773304738" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation paused. Waiting for complete numerical inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a6f686e20446f65205369676e6174757265" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation paused. Waiting for complete numerical inputs.", + "hex_result": "4a6f686e20446f65205369676e6174757265" + } + }, + "narrative": "This is The Aetheric Calculator, a brass-plated device with glowing vacuum tubes. It requires inputs from both The Navigator's Compass and The Cogwheel Translator to function." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_manifest.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Termination_Point" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15420" + } + ], + "init": { + "inputs": { + "dst": "Node_Termination_Point" + }, + "outputs": { + "path": "[\"Start_Node\", \"Gateway_A\", \"Router_7\", \"Node_Termination_Point\"]", + "cost": "15420" + } + }, + "narrative": "This is The Navigator's Compass, a complex array of mechanical mapping rings. It requires inputs from The Steam-Driven Archive and The Punched Card Reader to chart a precise course." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "15627833792682515958895617773304738" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2450" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "15420" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "15627833792682515958895617773304738" + } + ], + "narrative": "This is The Cogwheel Translator, a massive gear-shifting mechanism. It requires inputs from The Navigator's Compass, The Multiplier Loom, and The Cartographer's Gyroscope to calibrate its gears." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_data_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal active. Please provide secondary slot input for execution." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_backup.zip" + }, + "outputs": { + "files": "extracted_manifest.json" + } + }, + "narrative": "This is The Steam-Driven Archive, a pressurized filing cabinet hissing with steam. It requires input from The Analytical Engine to unlock its document cylinders." + }, + { + "id": "num_base_convert_66ce", + "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": "82736451928374650129384765" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "15627833792682515958895617773304738" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "35306" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "82736451928374650129384765" + } + ], + "init": { + "inputs": { + "s": "82736451928374650129384765" + }, + "outputs": {} + }, + "narrative": "This is The Resonance Tuner, a delicate acoustic instrument with crystalline dials. It requires inputs from The Cogwheel Translator and The Phase Inverter to find the correct frequency." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "2023-11-15T18:45:00+09:00" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_payload_bundle.zip" + }, + "outputs": {} + }, + "narrative": "This is The Clockwork Lockbox, a small, intricately geared safe. It requires input from The Temporal Astrolabe to disengage its internal tumblers." + }, + { + "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": "Primary command sequence initiated." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "15627833792682515958895617773304738" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal active. Please provide secondary slot input for execution." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe12345678" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Primary command sequence initiated." + }, + "outputs": { + "text_output": "Terminal active. Please provide secondary slot input for execution.", + "hex_output": "deadbeefcafebabe12345678" + } + }, + "narrative": "This is The Analytical Engine, a towering machine clattering with thousands of brass switches. It requires input from The Multiplier Loom to begin its processing sequence." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2023-11-15T09:45:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2023-11-15T18:45:00+09:00" + } + ], + "init": { + "inputs": { + "iso": "2023-11-15T09:45:00Z", + "from_tz": "UTC", + "to_tz": "Asia/Tokyo" + }, + "outputs": {} + }, + "narrative": "This is The Temporal Astrolabe, a complex handheld device with rotating celestial dials." + }, + { + "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": "transactions_log.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, amount, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "Terminal active. Please provide secondary slot input for execution." + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + ], + "init": { + "inputs": { + "file_id": "transactions_log.csv", + "select": "transaction_id, amount, status" + }, + "outputs": { + "rows": "[{\"transaction_id\":\"TX1001\",\"amount\":\"500.00\",\"status\":\"completed\"},{\"transaction_id\":\"TX1002\",\"amount\":\"120.50\",\"status\":\"pending\"}]" + } + }, + "narrative": "This is The Punched Card Reader, a clanking machine that sorts through stacks of perforated brass sheets. It requires input from The Analytical Engine to filter the correct records." + }, + { + "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": "9182736450192837465012938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 1701871101 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "15627833792682515958895617773304738" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465012938" + }, + "outputs": {} + }, + "narrative": "This is The Multiplier Loom, a sprawling apparatus of spinning bobbins and logic threads. It requires input from The Pressure Gauge Analyzer to set its initial weaving pattern." + }, + { + "id": "graph_shortest_path_8352", + "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_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Database_Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "2450" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v2.json", + "src": "Server_Alpha", + "dst": "Database_Omega" + }, + "outputs": { + "path": "[\"Server_Alpha\", \"Switch_Core\", \"Firewall_Internal\", \"Database_Omega\"]", + "cost": "2450" + } + }, + "narrative": "This is The Cartographer's Gyroscope, a spinning brass globe suspended in a heavy iron gimbal." + }, + { + "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": "This is The Pressure Gauge Analyzer, a diagnostic tool attached to a series of copper pipes." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "6574839201928374650192837" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "35306" + } + ], + "init": { + "inputs": { + "a": "6574839201928374650192837", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is The Phase Inverter, a humming electrical generator with exposed copper coils and leaping sparks." + } + ], + "edges": [ + { + "source_id": "item_16", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "num_base_convert_66ce", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_item", + "target_id": "graph_shortest_path", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_item", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_66ce", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "time_convert", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_8352", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "where" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_66ce", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-53ca9853/solution/solve.sh b/tasks/agentescape-15-skeleton-53ca9853/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-53ca9853/task.toml b/tasks/agentescape-15-skeleton-53ca9853/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e4adef8f1f92305d0ca7e047f6b425d9e44ec6b --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "83c4ab4a2cc5823c25ebd3f3718ca41ce6da11e7c3b25bfba39299faa60a4603" +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-15-skeleton-53ca9853/tests/Dockerfile b/tasks/agentescape-15-skeleton-53ca9853/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-53ca9853/tests/expected.json b/tasks/agentescape-15-skeleton-53ca9853/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fbafe3839b89cf9a599fbb28275ed4cdef25891d --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "83c4ab4a2cc5823c25ebd3f3718ca41ce6da11e7c3b25bfba39299faa60a4603", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-53ca9853/tests/grade.py b/tasks/agentescape-15-skeleton-53ca9853/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/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-15-skeleton-53ca9853/tests/test.sh b/tasks/agentescape-15-skeleton-53ca9853/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-53ca9853/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-574dcd85/environment/Dockerfile b/tasks/agentescape-15-skeleton-574dcd85/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-574dcd85/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/agent/cli.py b/tasks/agentescape-15-skeleton-574dcd85/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-574dcd85/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bce03dfc8679ac2c3fa2d99dbedfd7115d46e6df --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85-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-15-skeleton-574dcd85/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5a6a68c300d62d6464de4ec66f3b23350f48ec95 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/scenario.json @@ -0,0 +1,970 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_16", + "win_condition": { + "type": "item_content", + "node_id": "item_16", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_16", + "terminal_1", + "num_base_convert", + "calc_bigmul", + "zip_unzip_item", + "hmac_sha256", + "unicode_norm", + "graph_shortest_path", + "item_9", + "graph_shortest_path_fcde" + ], + "by_node": { + "item_16": { + "node_name": "", + "node_type": "Item", + "template_id": "item_16", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "Timezone text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_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": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "graph_shortest_path_fcde": { + "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": { + "item_16": { + "init_inputs": {}, + "init_outputs": { + "content": "America/New_York" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence completed successfully.", + "hex_output": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + } + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "b": "8273645019283746509182736" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_data_archive.zip" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5", + "text": "Authenticate this system message." + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Lübeck", + "form": "NFC" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_X" + }, + "init_outputs": { + "path": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]", + "cost": "1250" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology.json" + } + }, + "graph_shortest_path_fcde": { + "init_inputs": { + "file_id": "complex_graph_v2.json", + "src": "Alpha", + "dst": "Omega" + }, + "init_outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]", + "cost": "4500" + } + } + }, + "intro_narrative": "You are trapped in a decommissioned server farm deep within the neon-lit undercity. The megacorp 'OmniCorp' has locked down the facility, initiating a core purge. Your only chance of escape is to extract the master bypass codes from a sealed mainframe terminal before the purge vaporizes everything. The equipment scattered around the room holds the key to overriding the lockdown, but their systems are heavily fragmented. You must trace the data paths and feed the right calculations to the right machines.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "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", + "value": "America/New_York" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/New_York" + } + }, + "narrative": "A pristine memory chip containing the final exit codes. It holds the key to escaping the lockdown and surviving the night." + }, + { + "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": "[\"Uvctv_Pqfg\", \"Icvgyca_1\", \"Tqwvgt_C\", \"Pqfg_Z\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "70440921258840054856771994018072687492649320" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence completed successfully.", + "hex_output": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + } + }, + "narrative": "This is the mainframe terminal. It requires inputs from both the signal translator and the cipher cylinder. You'll need to use both of those devices first before this terminal can be activated." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "8403481344896561715052178472191360" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "20" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "70440921258840054856771994018072687492649320" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the signal translator. It requires inputs from both the quantum multiplier and the frequency calibrator. Once you have their outputs, feed them into this device." + }, + { + "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": 1015692760 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "8273645019283746509182736" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "8403481344896561715052178472191360" + } + ], + "init": { + "inputs": { + "b": "8273645019283746509182736" + }, + "outputs": {} + }, + "narrative": "This is the quantum multiplier. It processes data from the data validator. Feed it the result from the validator to proceed." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_data_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Lübeck" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_data_archive.zip" + }, + "outputs": {} + }, + "narrative": "This is the archive decryptor. It needs the result from the format synchronizer. After processing with the synchronizer, use the output here." + }, + { + "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": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "1250" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Uvctv_Pqfg\", \"Icvgyca_1\", \"Tqwvgt_C\", \"Pqfg_Z\"]" + } + ], + "narrative": "This is the cipher cylinder. It requires input from the network router. Run the router first and supply its data here." + }, + { + "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": "1d11286d6fdba1341ddfa0746598f734a14fd69c79cbfebc4a265d5f11fca140" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3c8a3dd8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1015692760 + } + ], + "narrative": "This is the data validator. It requires input from the security token generator. Obtain the token data and process it through this module." + }, + { + "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": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authenticate this system message." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "1d11286d6fdba1341ddfa0746598f734a14fd69c79cbfebc4a265d5f11fca140" + } + ], + "init": { + "inputs": { + "hex_key": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5", + "text": "Authenticate this system message." + }, + "outputs": {} + }, + "narrative": "This is the security token generator. It hums with a faint purple light, ready to accept manual overrides and generate secure tokens." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Lübeck" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Lübeck" + } + ], + "init": { + "inputs": { + "text": "Lübeck", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "This is the format synchronizer. It is a standalone deck used to standardize corrupted text fragments from the old net." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "4500" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "8403481344896561715052178472191360" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "20" + } + ], + "narrative": "This is the frequency calibrator. It requires inputs from both the quantum multiplier and the grid navigator. Ensure both systems are utilized before accessing this calibrator." + }, + { + "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": "Lübeck" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_X" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "1250" + } + ], + "init": { + "inputs": { + "dst": "Node_X" + }, + "outputs": { + "path": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]", + "cost": "1250" + } + }, + "narrative": "This is the network router. It requires inputs from both the format synchronizer and the data cartridge. Use them together to map the route." + }, + { + "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 encrypted access card with a heavily scratched magnetic strip." + }, + { + "id": "item_8_fdd4", + "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 dormant security badge discarded by a former corp-sec officer." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "network_topology.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology.json" + } + }, + "narrative": "A heavy, metallic data cartridge containing an offline map of the subnet." + }, + { + "id": "graph_shortest_path_fcde", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "complex_graph_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4500" + } + ], + "init": { + "inputs": { + "file_id": "complex_graph_v2.json", + "src": "Alpha", + "dst": "Omega" + }, + "outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]", + "cost": "4500" + } + }, + "narrative": "This is the grid navigator. It is a tactical holomap device used to calculate node traversal times across the grid." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "zip_unzip_item", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "text_rotN", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "item_8", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_fdd4", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path_fcde", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-574dcd85/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/instruction.md b/tasks/agentescape-15-skeleton-574dcd85/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/solution/oracle.py b/tasks/agentescape-15-skeleton-574dcd85/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/solution/scenario.json b/tasks/agentescape-15-skeleton-574dcd85/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5a6a68c300d62d6464de4ec66f3b23350f48ec95 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/solution/scenario.json @@ -0,0 +1,970 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_16", + "win_condition": { + "type": "item_content", + "node_id": "item_16", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_16", + "terminal_1", + "num_base_convert", + "calc_bigmul", + "zip_unzip_item", + "hmac_sha256", + "unicode_norm", + "graph_shortest_path", + "item_9", + "graph_shortest_path_fcde" + ], + "by_node": { + "item_16": { + "node_name": "", + "node_type": "Item", + "template_id": "item_16", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "Timezone text" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_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": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "graph_shortest_path_fcde": { + "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": { + "item_16": { + "init_inputs": {}, + "init_outputs": { + "content": "America/New_York" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence completed successfully.", + "hex_output": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + } + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "b": "8273645019283746509182736" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_data_archive.zip" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5", + "text": "Authenticate this system message." + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Lübeck", + "form": "NFC" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_X" + }, + "init_outputs": { + "path": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]", + "cost": "1250" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology.json" + } + }, + "graph_shortest_path_fcde": { + "init_inputs": { + "file_id": "complex_graph_v2.json", + "src": "Alpha", + "dst": "Omega" + }, + "init_outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]", + "cost": "4500" + } + } + }, + "intro_narrative": "You are trapped in a decommissioned server farm deep within the neon-lit undercity. The megacorp 'OmniCorp' has locked down the facility, initiating a core purge. Your only chance of escape is to extract the master bypass codes from a sealed mainframe terminal before the purge vaporizes everything. The equipment scattered around the room holds the key to overriding the lockdown, but their systems are heavily fragmented. You must trace the data paths and feed the right calculations to the right machines.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "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", + "value": "America/New_York" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "America/New_York" + } + }, + "narrative": "A pristine memory chip containing the final exit codes. It holds the key to escaping the lockdown and surviving the night." + }, + { + "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": "[\"Uvctv_Pqfg\", \"Icvgyca_1\", \"Tqwvgt_C\", \"Pqfg_Z\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "70440921258840054856771994018072687492649320" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence completed successfully.", + "hex_output": "a1b2c3d4e5f60789a1b2c3d4e5f60789" + } + }, + "narrative": "This is the mainframe terminal. It requires inputs from both the signal translator and the cipher cylinder. You'll need to use both of those devices first before this terminal can be activated." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "8403481344896561715052178472191360" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "20" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "70440921258840054856771994018072687492649320" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the signal translator. It requires inputs from both the quantum multiplier and the frequency calibrator. Once you have their outputs, feed them into this device." + }, + { + "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": 1015692760 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "8273645019283746509182736" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "8403481344896561715052178472191360" + } + ], + "init": { + "inputs": { + "b": "8273645019283746509182736" + }, + "outputs": {} + }, + "narrative": "This is the quantum multiplier. It processes data from the data validator. Feed it the result from the validator to proceed." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_data_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Lübeck" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_data_archive.zip" + }, + "outputs": {} + }, + "narrative": "This is the archive decryptor. It needs the result from the format synchronizer. After processing with the synchronizer, use the output here." + }, + { + "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": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "1250" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Uvctv_Pqfg\", \"Icvgyca_1\", \"Tqwvgt_C\", \"Pqfg_Z\"]" + } + ], + "narrative": "This is the cipher cylinder. It requires input from the network router. Run the router first and supply its data here." + }, + { + "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": "1d11286d6fdba1341ddfa0746598f734a14fd69c79cbfebc4a265d5f11fca140" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3c8a3dd8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1015692760 + } + ], + "narrative": "This is the data validator. It requires input from the security token generator. Obtain the token data and process it through this module." + }, + { + "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": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authenticate this system message." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "1d11286d6fdba1341ddfa0746598f734a14fd69c79cbfebc4a265d5f11fca140" + } + ], + "init": { + "inputs": { + "hex_key": "4c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f54c3b2a1908d7e6f5", + "text": "Authenticate this system message." + }, + "outputs": {} + }, + "narrative": "This is the security token generator. It hums with a faint purple light, ready to accept manual overrides and generate secure tokens." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Lübeck" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Lübeck" + } + ], + "init": { + "inputs": { + "text": "Lübeck", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "This is the format synchronizer. It is a standalone deck used to standardize corrupted text fragments from the old net." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "4500" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "8403481344896561715052178472191360" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "20" + } + ], + "narrative": "This is the frequency calibrator. It requires inputs from both the quantum multiplier and the grid navigator. Ensure both systems are utilized before accessing this calibrator." + }, + { + "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": "Lübeck" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_X" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "1250" + } + ], + "init": { + "inputs": { + "dst": "Node_X" + }, + "outputs": { + "path": "[\"Start_Node\", \"Gateway_1\", \"Router_A\", \"Node_X\"]", + "cost": "1250" + } + }, + "narrative": "This is the network router. It requires inputs from both the format synchronizer and the data cartridge. Use them together to map the route." + }, + { + "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 encrypted access card with a heavily scratched magnetic strip." + }, + { + "id": "item_8_fdd4", + "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 dormant security badge discarded by a former corp-sec officer." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "network_topology.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology.json" + } + }, + "narrative": "A heavy, metallic data cartridge containing an offline map of the subnet." + }, + { + "id": "graph_shortest_path_fcde", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "complex_graph_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4500" + } + ], + "init": { + "inputs": { + "file_id": "complex_graph_v2.json", + "src": "Alpha", + "dst": "Omega" + }, + "outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Omega\"]", + "cost": "4500" + } + }, + "narrative": "This is the grid navigator. It is a tactical holomap device used to calculate node traversal times across the grid." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "zip_unzip_item", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "text_rotN", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "item_8", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_fdd4", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "item_9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path_fcde", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-574dcd85/solution/solve.sh b/tasks/agentescape-15-skeleton-574dcd85/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-574dcd85/task.toml b/tasks/agentescape-15-skeleton-574dcd85/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1daa6e7a750c42b7e3ee8ba4bc9bb2bd143a247 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "df9d773a1d37cf4e8c8d2b30259d050153fb0916fc7d743429e00cd3b3edcf23" +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-15-skeleton-574dcd85/tests/Dockerfile b/tasks/agentescape-15-skeleton-574dcd85/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-574dcd85/tests/expected.json b/tasks/agentescape-15-skeleton-574dcd85/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..238f438e4bd65e5b5ecf5b80f1cc488d3a019fa6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "df9d773a1d37cf4e8c8d2b30259d050153fb0916fc7d743429e00cd3b3edcf23", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-574dcd85/tests/grade.py b/tasks/agentescape-15-skeleton-574dcd85/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/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-15-skeleton-574dcd85/tests/test.sh b/tasks/agentescape-15-skeleton-574dcd85/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-574dcd85/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-58e8b735/environment/Dockerfile b/tasks/agentescape-15-skeleton-58e8b735/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-58e8b735/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/agent/cli.py b/tasks/agentescape-15-skeleton-58e8b735/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-58e8b735/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce955194c22292859cd440b05f8db498378e8044 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735-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-15-skeleton-58e8b735/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..887cc743e3cd0bf1e3d5e0f70313ef3f5ba14de9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 21, + "win_node_id": "text_rotN", + "win_condition": { + "type": "tool_output", + "node_id": "text_rotN", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute ROT-N Cipher and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "luhn_check", + "terminal_2", + "num_base_convert_1b27", + "calc_bigmul", + "calc_modexp", + "calc_modexp_5904", + "graph_shortest_path", + "base64_encode", + "terminal_2_e1d7" + ], + "by_node": { + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert_1b27": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "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_modexp_5904": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "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" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "terminal_2_e1d7": { + "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" + } + } + } + } + }, + "initial_values": { + "luhn_check": { + "init_inputs": { + "number": "8273645512349876" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial terminal access granted.", + "hex_result": "64758697afbebdcc12345678" + } + }, + "num_base_convert_1b27": { + "init_inputs": { + "s": "4857293048572039485720394857203" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "1029384756102938475610293847561" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "10", + "mod": "65537" + }, + "init_outputs": {} + }, + "calc_modexp_5904": { + "init_inputs": { + "exp": "998877665544332211009988776655" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_map.json", + "src": "Alpha", + "dst": "Omega" + }, + "init_outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]", + "cost": "54200" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "deadbeefcafebabe1234567890abcdef" + }, + "init_outputs": {} + }, + "terminal_2_e1d7": { + "init_inputs": { + "num1": "334455667788990011223344556677", + "num2": "112233445566778899001122334455" + }, + "init_outputs": { + "text_result": "Secondary cryptographic key fragment.", + "hex_result": "deafface1234567887654321" + } + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of the abandoned Blackwood Research Facility. Dust motes dance in the flickering light of emergency backup generators, and the air smells faintly of ozone and old paper. The facility went dark decades ago after a mysterious experiment, leaving behind a complex web of interconnected analytical machines. In the center of the room sits the Final Decryptor, your only hope of uncovering Dr. Blackwood's last message and overriding the lockdown. You must trace the intricate flow of data through these forgotten devices, powering them up in the correct sequence to extract the ultimate secret before the backup generators fail completely.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "false" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "gbmtf" + } + ], + "narrative": "The facility's mainframe, the Final Decryptor. This is your way out. It requires inputs from the Logic Comparator and the ID Verifier to reveal the final escape sequence." + }, + { + "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": "4857293048572039485720394857203" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "63447158827160715882716071588269796" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "An intricate mechanical brain designated as the Logic Comparator. It requires inputs from the Protocol Converter and the Frequency Tuner to synthesize the data streams." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "8273645512349876" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "8273645512349876" + }, + "outputs": {} + }, + "narrative": "A small, wall-mounted ID Verifier. Its screen blinks steadily, ready to process numerical identification strings." + }, + { + "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": "63447158827160715882716071588269796" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1547413936" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4857293048572039485720394857203" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "63447158827160715882716071588269796" + } + ], + "narrative": "A tangled mess of fiber optic wiring making up the Protocol Converter. It requires inputs from the Signal Amplifier, the Frequency Tuner, and the Quantum Calculator." + }, + { + "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": 2578479866 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "4857293048572039485720394857203" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial terminal access granted." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "64758697afbebdcc12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial terminal access granted.", + "hex_result": "64758697afbebdcc12345678" + } + }, + "narrative": "A reinforced Security Terminal built directly into the concrete wall. It requires inputs from the Integrity Scanner and the Frequency Tuner to unlock its interface." + }, + { + "id": "num_base_convert_1b27", + "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": "4857293048572039485720394857203" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1547413936" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 2578479866 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4857293048572039485720394857203" + } + ], + "init": { + "inputs": { + "s": "4857293048572039485720394857203" + }, + "outputs": {} + }, + "narrative": "A dial-covered box known as the Frequency Tuner. It requires inputs from the Phase Inverter and the Integrity Scanner to lock onto the correct transmission band." + }, + { + "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": "3371322b3738722b757234534e465a346b4b764e37773d3d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "99b07afa" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2578479866 + } + ], + "narrative": "A heavy metallic device called the Integrity Scanner. It requires input from the Text Translator to run its diagnostic protocols." + }, + { + "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": "1029384756102938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "61636" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "63447158827160715882716071588269796" + } + ], + "init": { + "inputs": { + "a": "1029384756102938475610293847561" + }, + "outputs": {} + }, + "narrative": "A large, humming machine marked the Signal Amplifier. It requires input from the Resonance Chamber to boost its operational capacity." + }, + { + "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": "1547413936" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "63447158827160715882716071588269796" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1547413936" + } + ], + "narrative": "A specialized oscillation tool called the Phase Inverter. It requires inputs from both the Signal Amplifier and the Quantum Calculator to calibrate its frequencies." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1547413936" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "61636" + } + ], + "init": { + "inputs": { + "base": "10", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "A sealed glass cylinder known as the Resonance Chamber. It hums with latent energy and requires input from the Quantum Calculator to operate." + }, + { + "id": "calc_modexp_5904", + "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": "54200" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "998877665544332211009988776655" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2578479866 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1547413936" + } + ], + "init": { + "inputs": { + "exp": "998877665544332211009988776655" + }, + "outputs": {} + }, + "narrative": "A complex array of vacuum tubes called the Quantum Calculator. It requires inputs from both the Network Map Analyzer and the Integrity Scanner to stabilize its matrix." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "54200" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json", + "src": "Alpha", + "dst": "Omega" + }, + "outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]", + "cost": "54200" + } + }, + "narrative": "A dusty server rack labeled the Network Map Analyzer. It appears to hold old routing tables and spatial data." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "3q2+78r+ur4SNFZ4kKvN7w==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "3371322b3738722b757234534e465a346b4b764e37773d3d" + } + ], + "narrative": "This is the Text Translator, a device filled with spinning cipher wheels. It requires input from the Data Ingestor to function properly." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "deadbeefcafebabe1234567890abcdef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "3q2+78r+ur4SNFZ4kKvN7w==" + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A brass-rimmed terminal known as the Data Ingestor. It sits quietly, waiting for an initial sequence to be entered." + }, + { + "id": "terminal_2_e1d7", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "334455667788990011223344556677" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary cryptographic key fragment." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deafface1234567887654321" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "334455667788990011223344556677", + "num2": "112233445566778899001122334455" + }, + "outputs": { + "text_result": "Secondary cryptographic key fragment.", + "hex_result": "deafface1234567887654321" + } + }, + "narrative": "An isolated Backup Console with a flickering green phosphor display. It seems completely standalone and ready for use." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "n" + }, + { + "source_id": "luhn_check", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_1b27", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_1b27", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_5904", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_5904", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "hex_encode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_2_e1d7", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-58e8b735/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/instruction.md b/tasks/agentescape-15-skeleton-58e8b735/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/solution/oracle.py b/tasks/agentescape-15-skeleton-58e8b735/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/solution/scenario.json b/tasks/agentescape-15-skeleton-58e8b735/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..887cc743e3cd0bf1e3d5e0f70313ef3f5ba14de9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/solution/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 21, + "win_node_id": "text_rotN", + "win_condition": { + "type": "tool_output", + "node_id": "text_rotN", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute ROT-N Cipher and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "luhn_check", + "terminal_2", + "num_base_convert_1b27", + "calc_bigmul", + "calc_modexp", + "calc_modexp_5904", + "graph_shortest_path", + "base64_encode", + "terminal_2_e1d7" + ], + "by_node": { + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "num_base_convert_1b27": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "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_modexp_5904": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "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" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "terminal_2_e1d7": { + "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" + } + } + } + } + }, + "initial_values": { + "luhn_check": { + "init_inputs": { + "number": "8273645512349876" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initial terminal access granted.", + "hex_result": "64758697afbebdcc12345678" + } + }, + "num_base_convert_1b27": { + "init_inputs": { + "s": "4857293048572039485720394857203" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "1029384756102938475610293847561" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "10", + "mod": "65537" + }, + "init_outputs": {} + }, + "calc_modexp_5904": { + "init_inputs": { + "exp": "998877665544332211009988776655" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_map.json", + "src": "Alpha", + "dst": "Omega" + }, + "init_outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]", + "cost": "54200" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "deadbeefcafebabe1234567890abcdef" + }, + "init_outputs": {} + }, + "terminal_2_e1d7": { + "init_inputs": { + "num1": "334455667788990011223344556677", + "num2": "112233445566778899001122334455" + }, + "init_outputs": { + "text_result": "Secondary cryptographic key fragment.", + "hex_result": "deafface1234567887654321" + } + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of the abandoned Blackwood Research Facility. Dust motes dance in the flickering light of emergency backup generators, and the air smells faintly of ozone and old paper. The facility went dark decades ago after a mysterious experiment, leaving behind a complex web of interconnected analytical machines. In the center of the room sits the Final Decryptor, your only hope of uncovering Dr. Blackwood's last message and overriding the lockdown. You must trace the intricate flow of data through these forgotten devices, powering them up in the correct sequence to extract the ultimate secret before the backup generators fail completely.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "false" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "gbmtf" + } + ], + "narrative": "The facility's mainframe, the Final Decryptor. This is your way out. It requires inputs from the Logic Comparator and the ID Verifier to reveal the final escape sequence." + }, + { + "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": "4857293048572039485720394857203" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "63447158827160715882716071588269796" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "An intricate mechanical brain designated as the Logic Comparator. It requires inputs from the Protocol Converter and the Frequency Tuner to synthesize the data streams." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "8273645512349876" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "8273645512349876" + }, + "outputs": {} + }, + "narrative": "A small, wall-mounted ID Verifier. Its screen blinks steadily, ready to process numerical identification strings." + }, + { + "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": "63447158827160715882716071588269796" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1547413936" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4857293048572039485720394857203" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "63447158827160715882716071588269796" + } + ], + "narrative": "A tangled mess of fiber optic wiring making up the Protocol Converter. It requires inputs from the Signal Amplifier, the Frequency Tuner, and the Quantum Calculator." + }, + { + "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": 2578479866 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "4857293048572039485720394857203" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initial terminal access granted." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "64758697afbebdcc12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initial terminal access granted.", + "hex_result": "64758697afbebdcc12345678" + } + }, + "narrative": "A reinforced Security Terminal built directly into the concrete wall. It requires inputs from the Integrity Scanner and the Frequency Tuner to unlock its interface." + }, + { + "id": "num_base_convert_1b27", + "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": "4857293048572039485720394857203" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1547413936" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 2578479866 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4857293048572039485720394857203" + } + ], + "init": { + "inputs": { + "s": "4857293048572039485720394857203" + }, + "outputs": {} + }, + "narrative": "A dial-covered box known as the Frequency Tuner. It requires inputs from the Phase Inverter and the Integrity Scanner to lock onto the correct transmission band." + }, + { + "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": "3371322b3738722b757234534e465a346b4b764e37773d3d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "99b07afa" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2578479866 + } + ], + "narrative": "A heavy metallic device called the Integrity Scanner. It requires input from the Text Translator to run its diagnostic protocols." + }, + { + "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": "1029384756102938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "61636" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "63447158827160715882716071588269796" + } + ], + "init": { + "inputs": { + "a": "1029384756102938475610293847561" + }, + "outputs": {} + }, + "narrative": "A large, humming machine marked the Signal Amplifier. It requires input from the Resonance Chamber to boost its operational capacity." + }, + { + "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": "1547413936" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "63447158827160715882716071588269796" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1547413936" + } + ], + "narrative": "A specialized oscillation tool called the Phase Inverter. It requires inputs from both the Signal Amplifier and the Quantum Calculator to calibrate its frequencies." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1547413936" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "61636" + } + ], + "init": { + "inputs": { + "base": "10", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "A sealed glass cylinder known as the Resonance Chamber. It hums with latent energy and requires input from the Quantum Calculator to operate." + }, + { + "id": "calc_modexp_5904", + "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": "54200" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "998877665544332211009988776655" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2578479866 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1547413936" + } + ], + "init": { + "inputs": { + "exp": "998877665544332211009988776655" + }, + "outputs": {} + }, + "narrative": "A complex array of vacuum tubes called the Quantum Calculator. It requires inputs from both the Network Map Analyzer and the Integrity Scanner to stabilize its matrix." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_topology_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "54200" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_map.json", + "src": "Alpha", + "dst": "Omega" + }, + "outputs": { + "path": "[\"Alpha\", \"Beta\", \"Gamma\", \"Delta\", \"Epsilon\", \"Omega\"]", + "cost": "54200" + } + }, + "narrative": "A dusty server rack labeled the Network Map Analyzer. It appears to hold old routing tables and spatial data." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "3q2+78r+ur4SNFZ4kKvN7w==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "3371322b3738722b757234534e465a346b4b764e37773d3d" + } + ], + "narrative": "This is the Text Translator, a device filled with spinning cipher wheels. It requires input from the Data Ingestor to function properly." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "deadbeefcafebabe1234567890abcdef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "3q2+78r+ur4SNFZ4kKvN7w==" + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A brass-rimmed terminal known as the Data Ingestor. It sits quietly, waiting for an initial sequence to be entered." + }, + { + "id": "terminal_2_e1d7", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "334455667788990011223344556677" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary cryptographic key fragment." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deafface1234567887654321" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "334455667788990011223344556677", + "num2": "112233445566778899001122334455" + }, + "outputs": { + "text_result": "Secondary cryptographic key fragment.", + "hex_result": "deafface1234567887654321" + } + }, + "narrative": "An isolated Backup Console with a flickering green phosphor display. It seems completely standalone and ready for use." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "n" + }, + { + "source_id": "luhn_check", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_1b27", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_1b27", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "num_base_convert_1b27", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_5904", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_5904", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_5904", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "hex_encode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_encode", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_2_e1d7", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-58e8b735/solution/solve.sh b/tasks/agentescape-15-skeleton-58e8b735/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-58e8b735/task.toml b/tasks/agentescape-15-skeleton-58e8b735/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68d087769e46c239de0d736e1f61eb2db346300e --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "f27a5b94b79def05c99fcef42b40b1a513ab1dce3c53f970ebda32e4f5add73d" +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-15-skeleton-58e8b735/tests/Dockerfile b/tasks/agentescape-15-skeleton-58e8b735/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-58e8b735/tests/expected.json b/tasks/agentescape-15-skeleton-58e8b735/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9e0a68a463dd9eb4ffa6391b759c90297abf7972 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "f27a5b94b79def05c99fcef42b40b1a513ab1dce3c53f970ebda32e4f5add73d", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-58e8b735/tests/grade.py b/tasks/agentescape-15-skeleton-58e8b735/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/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-15-skeleton-58e8b735/tests/test.sh b/tasks/agentescape-15-skeleton-58e8b735/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-58e8b735/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-5956f7d2/environment/Dockerfile b/tasks/agentescape-15-skeleton-5956f7d2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-5956f7d2/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/agent/cli.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-5956f7d2/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..741503b30a682cf80f6555fe0afed6968de3c237 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2-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-15-skeleton-5956f7d2/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..33c0815732ea22ed59c5e4dd6bde8c0823475e79 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/scenario.json @@ -0,0 +1,806 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "luhn_check", + "win_condition": { + "type": "tool_output", + "node_id": "luhn_check", + "output_port": "valid", + "output_type": "Text_Generic", + "description": "Execute Luhn Checker and get the output from port 'valid'" + }, + "source_init": { + "source_nodes": [ + "hex_encode_3e1b", + "terminal_2", + "hmac_sha256", + "terminal_1", + "calc_gcd", + "calc_inv_mod" + ], + "by_node": { + "hex_encode_3e1b": { + "node_name": "Text to Hex Encoder", + "node_type": "Tool", + "template_id": "hex_encode", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "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" + } + } + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_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": {} + }, + "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": {} + } + } + }, + "initial_values": { + "hex_encode_3e1b": { + "init_inputs": { + "text": "Initiating secure data transmission sequence." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "837465920182736450918273645109" + }, + "init_outputs": { + "text_result": "Calculation deferred; pending secondary numeric operand.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "cafebabecafebabecafebabecafebabe", + "text": "Verify the integrity of this critical payload." + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialized. Waiting for external calculation inputs.", + "hex_output": "8899aabbccddeeff0011223344556677", + "item_dispenser": "Standard issued token of negligible value." + } + }, + "calc_gcd": { + "init_inputs": { + "a": "592837465102938475610293847561", + "b": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "475869102384756102938475612345", + "mod": "524287" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, leaving behind a scarred wasteland of rusted metal and forgotten technology. You are a scavenger who just discovered a sealed military bunker half-buried in the irradiated dunes. Rumors say this bunker holds a functional atmospheric purifier, a treasure that could save your struggling settlement. However, the outpost is protected by a complex network of ancient computer terminals, biometric lockboxes, and fragmented communication relays. Your objective is to reactivate the automated systems, bypass the military-grade security, and trick the final lockdown validator into granting you access. You'll need to power up the surviving processors, piece together scraps of data, and follow the digital breadcrumbs left by the bunker's final operators before the radioactive sandstorm hits and buries this place forever.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the Final Validator. It requires input from the Cipher Decoder to verify the ultimate override command and open the bunker doors." + }, + { + "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": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Initiating secure data transmission sequence." + } + ], + "narrative": "This is the Cipher Decoder. It requires input from the Signal Encoder to process the complex data stream." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "narrative": "This is the Signal Encoder. It requires input from the Field Decoder to package the outgoing transmission." + }, + { + "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 sharp, rusted scrap of metal torn from a ruined military transport vehicle." + }, + { + "id": "hex_decode_e885", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "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 string", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Initiating secure data transmission sequence." + } + ], + "narrative": "This is the Field Decoder. It requires input from the Backup Encoder to translate the incoming transmission." + }, + { + "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": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Wasteland Crate. It requires input from the Backup Encoder to bypass its electronic latch." + }, + { + "id": "hex_encode_3e1b", + "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": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "init": { + "inputs": { + "text": "Initiating secure data transmission sequence." + }, + "outputs": {} + }, + "narrative": "A Backup Encoder running on a depleted battery, its screen flickering faintly." + }, + { + "id": "item_16_a260", + "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 dust-covered scrap of old world metal with faded warning markings." + }, + { + "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": "93d70dc28105276e30c1f11225d60d53cf11c83530960e4587ac20ec6df5c7a2" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Secure Lockbox. It requires input from the Security Authenticator to release its biometric seals." + }, + { + "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": "837465920182736450918273645109" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation deferred; pending secondary numeric operand." + }, + { + "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": "837465920182736450918273645109" + }, + "outputs": { + "text_result": "Calculation deferred; pending secondary numeric operand.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Secondary Console. It requires input from the Navigation Processor to calculate its coordinates." + }, + { + "id": "container_1_589c", + "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": "8899aabbccddeeff0011223344556677" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Primary Lockbox. It requires input from the Main Console to disengage its heavy blast locks." + }, + { + "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": "cafebabecafebabecafebabecafebabe" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Verify the integrity of this critical payload." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "93d70dc28105276e30c1f11225d60d53cf11c83530960e4587ac20ec6df5c7a2" + } + ], + "init": { + "inputs": { + "hex_key": "cafebabecafebabecafebabecafebabe", + "text": "Verify the integrity of this critical payload." + }, + "outputs": {} + }, + "narrative": "A high-tech Security Authenticator salvaged from a military ruin." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Calculation deferred; pending secondary numeric operand." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "7461" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized. Waiting for external calculation inputs." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "8899aabbccddeeff0011223344556677" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard issued token of negligible value." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialized. Waiting for external calculation inputs.", + "hex_output": "8899aabbccddeeff0011223344556677", + "item_dispenser": "Standard issued token of negligible value." + } + }, + "narrative": "This is the Main Console. It requires inputs from both the Secondary Console and the Grid Calibrator to boot up its primary interface." + }, + { + "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": "592837465102938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "592837465102938475610293847561", + "b": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "A bulky Navigation Processor used by scavengers, running on barely enough solar power." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "475869102384756102938475612345" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "524287" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "7461" + } + ], + "init": { + "inputs": { + "a": "475869102384756102938475612345", + "mod": "524287" + }, + "outputs": {} + }, + "narrative": "A rugged Grid Calibrator found half-buried in the rubble." + } + ], + "edges": [ + { + "source_id": "hex_decode", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "hex_encode", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "hex_encode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hex_decode_e885", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "hex_decode_e885", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hex_encode_3e1b", + "target_id": "hex_decode_e885", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "hex_encode_3e1b", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_a260", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_1", + "target_id": "item_16_a260", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "container_1_589c", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_1", + "target_id": "container_1_589c", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-5956f7d2/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/instruction.md b/tasks/agentescape-15-skeleton-5956f7d2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/solution/oracle.py b/tasks/agentescape-15-skeleton-5956f7d2/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/solution/scenario.json b/tasks/agentescape-15-skeleton-5956f7d2/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..33c0815732ea22ed59c5e4dd6bde8c0823475e79 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/solution/scenario.json @@ -0,0 +1,806 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "luhn_check", + "win_condition": { + "type": "tool_output", + "node_id": "luhn_check", + "output_port": "valid", + "output_type": "Text_Generic", + "description": "Execute Luhn Checker and get the output from port 'valid'" + }, + "source_init": { + "source_nodes": [ + "hex_encode_3e1b", + "terminal_2", + "hmac_sha256", + "terminal_1", + "calc_gcd", + "calc_inv_mod" + ], + "by_node": { + "hex_encode_3e1b": { + "node_name": "Text to Hex Encoder", + "node_type": "Tool", + "template_id": "hex_encode", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "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" + } + } + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + }, + "text": { + "type": "Text_Generic", + "description": "Text message" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_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": {} + }, + "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": {} + } + } + }, + "initial_values": { + "hex_encode_3e1b": { + "init_inputs": { + "text": "Initiating secure data transmission sequence." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "837465920182736450918273645109" + }, + "init_outputs": { + "text_result": "Calculation deferred; pending secondary numeric operand.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "cafebabecafebabecafebabecafebabe", + "text": "Verify the integrity of this critical payload." + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialized. Waiting for external calculation inputs.", + "hex_output": "8899aabbccddeeff0011223344556677", + "item_dispenser": "Standard issued token of negligible value." + } + }, + "calc_gcd": { + "init_inputs": { + "a": "592837465102938475610293847561", + "b": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "475869102384756102938475612345", + "mod": "524287" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The world ended decades ago, leaving behind a scarred wasteland of rusted metal and forgotten technology. You are a scavenger who just discovered a sealed military bunker half-buried in the irradiated dunes. Rumors say this bunker holds a functional atmospheric purifier, a treasure that could save your struggling settlement. However, the outpost is protected by a complex network of ancient computer terminals, biometric lockboxes, and fragmented communication relays. Your objective is to reactivate the automated systems, bypass the military-grade security, and trick the final lockdown validator into granting you access. You'll need to power up the surviving processors, piece together scraps of data, and follow the digital breadcrumbs left by the bunker's final operators before the radioactive sandstorm hits and buries this place forever.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the Final Validator. It requires input from the Cipher Decoder to verify the ultimate override command and open the bunker doors." + }, + { + "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": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Initiating secure data transmission sequence." + } + ], + "narrative": "This is the Cipher Decoder. It requires input from the Signal Encoder to process the complex data stream." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "narrative": "This is the Signal Encoder. It requires input from the Field Decoder to package the outgoing transmission." + }, + { + "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 sharp, rusted scrap of metal torn from a ruined military transport vehicle." + }, + { + "id": "hex_decode_e885", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "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 string", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Initiating secure data transmission sequence." + } + ], + "narrative": "This is the Field Decoder. It requires input from the Backup Encoder to translate the incoming transmission." + }, + { + "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": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Wasteland Crate. It requires input from the Backup Encoder to bypass its electronic latch." + }, + { + "id": "hex_encode_3e1b", + "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": "Initiating secure data transmission sequence." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e6974696174696e67207365637572652064617461207472616e736d697373696f6e2073657175656e63652e" + } + ], + "init": { + "inputs": { + "text": "Initiating secure data transmission sequence." + }, + "outputs": {} + }, + "narrative": "A Backup Encoder running on a depleted battery, its screen flickering faintly." + }, + { + "id": "item_16_a260", + "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 dust-covered scrap of old world metal with faded warning markings." + }, + { + "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": "93d70dc28105276e30c1f11225d60d53cf11c83530960e4587ac20ec6df5c7a2" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Secure Lockbox. It requires input from the Security Authenticator to release its biometric seals." + }, + { + "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": "837465920182736450918273645109" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation deferred; pending secondary numeric operand." + }, + { + "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": "837465920182736450918273645109" + }, + "outputs": { + "text_result": "Calculation deferred; pending secondary numeric operand.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the Secondary Console. It requires input from the Navigation Processor to calculate its coordinates." + }, + { + "id": "container_1_589c", + "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": "8899aabbccddeeff0011223344556677" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Primary Lockbox. It requires input from the Main Console to disengage its heavy blast locks." + }, + { + "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": "cafebabecafebabecafebabecafebabe" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Verify the integrity of this critical payload." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "93d70dc28105276e30c1f11225d60d53cf11c83530960e4587ac20ec6df5c7a2" + } + ], + "init": { + "inputs": { + "hex_key": "cafebabecafebabecafebabecafebabe", + "text": "Verify the integrity of this critical payload." + }, + "outputs": {} + }, + "narrative": "A high-tech Security Authenticator salvaged from a military ruin." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Calculation deferred; pending secondary numeric operand." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "7461" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized. Waiting for external calculation inputs." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "8899aabbccddeeff0011223344556677" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard issued token of negligible value." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialized. Waiting for external calculation inputs.", + "hex_output": "8899aabbccddeeff0011223344556677", + "item_dispenser": "Standard issued token of negligible value." + } + }, + "narrative": "This is the Main Console. It requires inputs from both the Secondary Console and the Grid Calibrator to boot up its primary interface." + }, + { + "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": "592837465102938475610293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "592837465102938475610293847561", + "b": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "A bulky Navigation Processor used by scavengers, running on barely enough solar power." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "475869102384756102938475612345" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "524287" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "7461" + } + ], + "init": { + "inputs": { + "a": "475869102384756102938475612345", + "mod": "524287" + }, + "outputs": {} + }, + "narrative": "A rugged Grid Calibrator found half-buried in the rubble." + } + ], + "edges": [ + { + "source_id": "hex_decode", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "hex_encode", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "hex_encode", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hex_decode_e885", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "hex_decode_e885", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "hex_encode_3e1b", + "target_id": "hex_decode_e885", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "hex_encode_3e1b", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_a260", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_1", + "target_id": "item_16_a260", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "container_1_589c", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_1", + "target_id": "container_1_589c", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5956f7d2/solution/solve.sh b/tasks/agentescape-15-skeleton-5956f7d2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-5956f7d2/task.toml b/tasks/agentescape-15-skeleton-5956f7d2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..87bb2118513fdaadae1d61711f3c9f51c3e18ee7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "9ff1ada837c3392c2fc6b7d077833f29bf27307964aeeddea1bfa423eb00150f" +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-15-skeleton-5956f7d2/tests/Dockerfile b/tasks/agentescape-15-skeleton-5956f7d2/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-5956f7d2/tests/expected.json b/tasks/agentescape-15-skeleton-5956f7d2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fcde8aa98eb5c99f727fd11e41ffe07775604224 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "9ff1ada837c3392c2fc6b7d077833f29bf27307964aeeddea1bfa423eb00150f", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5956f7d2/tests/grade.py b/tasks/agentescape-15-skeleton-5956f7d2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/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-15-skeleton-5956f7d2/tests/test.sh b/tasks/agentescape-15-skeleton-5956f7d2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5956f7d2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-59bbf192/environment/Dockerfile b/tasks/agentescape-15-skeleton-59bbf192/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-59bbf192/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/agent/cli.py b/tasks/agentescape-15-skeleton-59bbf192/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-59bbf192/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccfc835911b1bba529cd2d6d67ef90a8452d56fc --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192-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-15-skeleton-59bbf192/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..9331f39e9c5f2c767d37a1cc1716eb176b883534 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/scenario.json @@ -0,0 +1,933 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "item_13", + "win_condition": { + "type": "item_content", + "node_id": "item_13", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_13", + "item_7", + "terminal_1", + "json_get", + "num_base_convert", + "checksum_crc32", + "matter_synthesizer", + "calc_gcd", + "checksum_crc32_2d76", + "container_4_9539", + "json_get_6d3b" + ], + "by_node": { + "item_13": { + "node_name": "", + "node_type": "Item", + "template_id": "item_13", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "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": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_2d76": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "container_4_9539": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get_6d3b": { + "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" + } + } + } + } + }, + "initial_values": { + "item_13": { + "init_inputs": {}, + "init_outputs": { + "content": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(9182736450192837465)" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialization complete. Awaiting input.", + "hex_output": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + } + }, + "json_get": { + "init_inputs": { + "file_id": "database_export_v2.json" + }, + "init_outputs": { + "values": "Configuration loaded successfully." + } + }, + "num_base_convert": { + "init_inputs": { + "s": "485720193847562910384756" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "9a8b7c6d5e4f3a2b1c0d" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic: Positron Matrix Stabilizer Type-4" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "293847561029384756102938" + }, + "init_outputs": {} + }, + "checksum_crc32_2d76": { + "init_inputs": { + "hex": "f1e2d3c4b5a69788" + }, + "init_outputs": {} + }, + "container_4_9539": { + "init_inputs": { + "fingerprint_input": "bio_auth_token_xh72" + }, + "init_outputs": {} + }, + "json_get_6d3b": { + "init_inputs": { + "file_id": "settings_registry.json", + "jsonpath": "$.system.parameters.retry_count" + }, + "init_outputs": { + "values": "$.users[?(@.active==true)].email" + } + } + }, + "intro_narrative": "You awaken aboard the derelict orbital station 'Aethelgard'. The emergency lights flicker rhythmically, casting long, unsettling shadows across the cold metallic walls. The station's central AI has locked down the main reactor, and the automated life support systems are rapidly failing. Your only chance of survival is to manually override the security protocols and extract the master decryption key hidden deep within the mainframe vault. To achieve this, you must navigate the abandoned research labs, re-activate dormant scientific equipment, and piece together the fragmented data flow before the oxygen runs out completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_13", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_13", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + }, + "narrative": "The Data Core. A glowing, crystalline module humming with latent energy. It contains the ultimate override sequences necessary to restore the station's life support." + }, + { + "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": "220868265c163aa267c398a8e1b70901d87698b6a9a6455e164978258b847093" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Mainframe Vault. A heavy, reinforced security enclosure protecting the core systems. It requires input from the Security Authenticator to bypass its electronic locks." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "9182736450192837465\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "220868265c163aa267c398a8e1b70901d87698b6a9a6455e164978258b847093" + } + ], + "narrative": "The Security Authenticator. A high-level cryptographic verification module. It requires inputs from both the Logic Processor and the Command Terminal to synthesize a valid override hash." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(9182736450192837465)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "9182736450192837465\n" + } + ], + "narrative": "The Logic Processor. A quantum calculation unit used for executing raw instructions. It requires input from the Encrypted Memory Chip to run its automated diagnostic routines." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(9182736450192837465)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(9182736450192837465)" + } + }, + "narrative": "The Encrypted Memory Chip. A small, slightly scorched storage device containing isolated code fragments from the previous crew." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Configuration loaded successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "485720193847562910384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialization complete. Awaiting input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialization complete. Awaiting input.", + "hex_output": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + } + }, + "narrative": "The Command Terminal. The primary interface for the station's bridge. It requires inputs from both the Data Extractor and the Signal Translator to generate access commands." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "database_export_v2.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.users[?(@.active==true)].email" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Configuration loaded successfully." + } + ], + "init": { + "inputs": { + "file_id": "database_export_v2.json" + }, + "outputs": { + "values": "Configuration loaded successfully." + } + }, + "narrative": "The Data Extractor. A specialized parsing subsystem. It requires input from the Archive Scanner to isolate and extract the correct data blocks from 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": "485720193847562910384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 535982341 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "485720193847562910384756" + } + ], + "init": { + "inputs": { + "s": "485720193847562910384756" + }, + "outputs": {} + }, + "narrative": "The Signal Translator. A universal language and telemetry converter. It requires inputs from both the Integrity Checker and the Frequency Calibrator to properly decode the incoming transmissions." + }, + { + "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": "9a8b7c6d5e4f3a2b1c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1ff27105" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 535982341 + } + ], + "init": { + "inputs": { + "hex": "9a8b7c6d5e4f3a2b1c0d" + }, + "outputs": {} + }, + "narrative": "The Integrity Checker. A diagnostic tool used by engineers to verify the structural integrity of data packets." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "System initialization complete. Awaiting input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Lockbox. A personalized storage container built into the wall. It requires input from the Command Terminal to authenticate its user." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Schematic: Positron Matrix Stabilizer Type-4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_ddefff0bcf012e1c" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic: Positron Matrix Stabilizer Type-4" + }, + "outputs": {} + }, + "narrative": "The Nanotech Fabricator. A sophisticated 3D-printing machine capable of assembling physical tools and components from digital blueprints." + }, + { + "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": 1624888492 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "293847561029384756102938" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "293847561029384756102938" + }, + "outputs": {} + }, + "narrative": "The Frequency Calibrator. A waveform alignment device. It requires input from the Primary Sensor to calculate the optimal resonance frequency." + }, + { + "id": "checksum_crc32_2d76", + "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": "f1e2d3c4b5a69788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "60d9d4ac" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1624888492 + } + ], + "init": { + "inputs": { + "hex": "f1e2d3c4b5a69788" + }, + "outputs": {} + }, + "narrative": "The Primary Sensor. An environmental scanning array used to detect structural anomalies in the station's hull." + }, + { + "id": "container_4_9539", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "bio_auth_token_xh72" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "bio_auth_token_xh72" + }, + "outputs": {} + }, + "narrative": "The Specimen Case. A reinforced stasis box originally used by the science team for safely transporting volatile alien flora." + }, + { + "id": "json_get_6d3b", + "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": "settings_registry.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.system.parameters.retry_count" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "$.users[?(@.active==true)].email" + } + ], + "init": { + "inputs": { + "file_id": "settings_registry.json", + "jsonpath": "$.system.parameters.retry_count" + }, + "outputs": { + "values": "$.users[?(@.active==true)].email" + } + }, + "narrative": "The Archive Scanner. A dedicated search terminal used to query the station's vast historical and operational databases." + } + ], + "edges": [ + { + "source_id": "container_1", + "target_id": "item_13", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "code_py_exec", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "terminal_1", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "item_dispenser", + "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": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_key" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "container_4", + "target_id": "hmac_sha256", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "matter_synthesizer", + "target_id": "terminal_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "terminal_1", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32_2d76", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "container_4_9539", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "json_get_6d3b", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "jsonpath" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-59bbf192/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/instruction.md b/tasks/agentescape-15-skeleton-59bbf192/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/solution/oracle.py b/tasks/agentescape-15-skeleton-59bbf192/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/solution/scenario.json b/tasks/agentescape-15-skeleton-59bbf192/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..9331f39e9c5f2c767d37a1cc1716eb176b883534 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/solution/scenario.json @@ -0,0 +1,933 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "item_13", + "win_condition": { + "type": "item_content", + "node_id": "item_13", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_13", + "item_7", + "terminal_1", + "json_get", + "num_base_convert", + "checksum_crc32", + "matter_synthesizer", + "calc_gcd", + "checksum_crc32_2d76", + "container_4_9539", + "json_get_6d3b" + ], + "by_node": { + "item_13": { + "node_name": "", + "node_type": "Item", + "template_id": "item_13", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "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": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_2d76": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "container_4_9539": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get_6d3b": { + "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" + } + } + } + } + }, + "initial_values": { + "item_13": { + "init_inputs": {}, + "init_outputs": { + "content": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(9182736450192837465)" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialization complete. Awaiting input.", + "hex_output": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + } + }, + "json_get": { + "init_inputs": { + "file_id": "database_export_v2.json" + }, + "init_outputs": { + "values": "Configuration loaded successfully." + } + }, + "num_base_convert": { + "init_inputs": { + "s": "485720193847562910384756" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "9a8b7c6d5e4f3a2b1c0d" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic: Positron Matrix Stabilizer Type-4" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "293847561029384756102938" + }, + "init_outputs": {} + }, + "checksum_crc32_2d76": { + "init_inputs": { + "hex": "f1e2d3c4b5a69788" + }, + "init_outputs": {} + }, + "container_4_9539": { + "init_inputs": { + "fingerprint_input": "bio_auth_token_xh72" + }, + "init_outputs": {} + }, + "json_get_6d3b": { + "init_inputs": { + "file_id": "settings_registry.json", + "jsonpath": "$.system.parameters.retry_count" + }, + "init_outputs": { + "values": "$.users[?(@.active==true)].email" + } + } + }, + "intro_narrative": "You awaken aboard the derelict orbital station 'Aethelgard'. The emergency lights flicker rhythmically, casting long, unsettling shadows across the cold metallic walls. The station's central AI has locked down the main reactor, and the automated life support systems are rapidly failing. Your only chance of survival is to manually override the security protocols and extract the master decryption key hidden deep within the mainframe vault. To achieve this, you must navigate the abandoned research labs, re-activate dormant scientific equipment, and piece together the fragmented data flow before the oxygen runs out completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_13", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_13", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "e4d9c2a1b5f8e7d3c6b9a2f1e4d8c3b7a5e9f2d6c8b1a4e7f3d2c5b8a1e9f4d7" + } + }, + "narrative": "The Data Core. A glowing, crystalline module humming with latent energy. It contains the ultimate override sequences necessary to restore the station's life support." + }, + { + "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": "220868265c163aa267c398a8e1b70901d87698b6a9a6455e164978258b847093" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Mainframe Vault. A heavy, reinforced security enclosure protecting the core systems. It requires input from the Security Authenticator to bypass its electronic locks." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "9182736450192837465\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "220868265c163aa267c398a8e1b70901d87698b6a9a6455e164978258b847093" + } + ], + "narrative": "The Security Authenticator. A high-level cryptographic verification module. It requires inputs from both the Logic Processor and the Command Terminal to synthesize a valid override hash." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(9182736450192837465)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "9182736450192837465\n" + } + ], + "narrative": "The Logic Processor. A quantum calculation unit used for executing raw instructions. It requires input from the Encrypted Memory Chip to run its automated diagnostic routines." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(9182736450192837465)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(9182736450192837465)" + } + }, + "narrative": "The Encrypted Memory Chip. A small, slightly scorched storage device containing isolated code fragments from the previous crew." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Configuration loaded successfully." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "485720193847562910384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialization complete. Awaiting input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialization complete. Awaiting input.", + "hex_output": "4a9b2c8d3e7f1a6b5c0d9e8f2a1b4c7d" + } + }, + "narrative": "The Command Terminal. The primary interface for the station's bridge. It requires inputs from both the Data Extractor and the Signal Translator to generate access commands." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "database_export_v2.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.users[?(@.active==true)].email" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Configuration loaded successfully." + } + ], + "init": { + "inputs": { + "file_id": "database_export_v2.json" + }, + "outputs": { + "values": "Configuration loaded successfully." + } + }, + "narrative": "The Data Extractor. A specialized parsing subsystem. It requires input from the Archive Scanner to isolate and extract the correct data blocks from 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": "485720193847562910384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 535982341 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "485720193847562910384756" + } + ], + "init": { + "inputs": { + "s": "485720193847562910384756" + }, + "outputs": {} + }, + "narrative": "The Signal Translator. A universal language and telemetry converter. It requires inputs from both the Integrity Checker and the Frequency Calibrator to properly decode the incoming transmissions." + }, + { + "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": "9a8b7c6d5e4f3a2b1c0d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1ff27105" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 535982341 + } + ], + "init": { + "inputs": { + "hex": "9a8b7c6d5e4f3a2b1c0d" + }, + "outputs": {} + }, + "narrative": "The Integrity Checker. A diagnostic tool used by engineers to verify the structural integrity of data packets." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "System initialization complete. Awaiting input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Lockbox. A personalized storage container built into the wall. It requires input from the Command Terminal to authenticate its user." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Schematic: Positron Matrix Stabilizer Type-4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_ddefff0bcf012e1c" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic: Positron Matrix Stabilizer Type-4" + }, + "outputs": {} + }, + "narrative": "The Nanotech Fabricator. A sophisticated 3D-printing machine capable of assembling physical tools and components from digital blueprints." + }, + { + "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": 1624888492 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "293847561029384756102938" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "b": "293847561029384756102938" + }, + "outputs": {} + }, + "narrative": "The Frequency Calibrator. A waveform alignment device. It requires input from the Primary Sensor to calculate the optimal resonance frequency." + }, + { + "id": "checksum_crc32_2d76", + "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": "f1e2d3c4b5a69788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "60d9d4ac" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1624888492 + } + ], + "init": { + "inputs": { + "hex": "f1e2d3c4b5a69788" + }, + "outputs": {} + }, + "narrative": "The Primary Sensor. An environmental scanning array used to detect structural anomalies in the station's hull." + }, + { + "id": "container_4_9539", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "bio_auth_token_xh72" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "bio_auth_token_xh72" + }, + "outputs": {} + }, + "narrative": "The Specimen Case. A reinforced stasis box originally used by the science team for safely transporting volatile alien flora." + }, + { + "id": "json_get_6d3b", + "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": "settings_registry.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.system.parameters.retry_count" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "$.users[?(@.active==true)].email" + } + ], + "init": { + "inputs": { + "file_id": "settings_registry.json", + "jsonpath": "$.system.parameters.retry_count" + }, + "outputs": { + "values": "$.users[?(@.active==true)].email" + } + }, + "narrative": "The Archive Scanner. A dedicated search terminal used to query the station's vast historical and operational databases." + } + ], + "edges": [ + { + "source_id": "container_1", + "target_id": "item_13", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hmac_sha256", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "code_py_exec", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "terminal_1", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "item_dispenser", + "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": "num_base_convert", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "terminal_1", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_key" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "container_4", + "target_id": "hmac_sha256", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "matter_synthesizer", + "target_id": "terminal_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "terminal_1", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32_2d76", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "container_4_9539", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "json_get_6d3b", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "jsonpath" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-59bbf192/solution/solve.sh b/tasks/agentescape-15-skeleton-59bbf192/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-59bbf192/task.toml b/tasks/agentescape-15-skeleton-59bbf192/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..beffb03a51d46516fa6be60f18ba0a7c340d2e2e --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "9d35e075c3589eaaf07de58c206e7434bbb73b1a71eebceaef89f6332aec7615" +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-15-skeleton-59bbf192/tests/Dockerfile b/tasks/agentescape-15-skeleton-59bbf192/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-59bbf192/tests/expected.json b/tasks/agentescape-15-skeleton-59bbf192/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a5e2cab2156a3aebee06bc4b9866cb4a780d9aec --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "9d35e075c3589eaaf07de58c206e7434bbb73b1a71eebceaef89f6332aec7615", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-59bbf192/tests/grade.py b/tasks/agentescape-15-skeleton-59bbf192/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/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-15-skeleton-59bbf192/tests/test.sh b/tasks/agentescape-15-skeleton-59bbf192/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-59bbf192/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/environment/Dockerfile b/tasks/agentescape-15-skeleton-5a3d2d50/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-5a3d2d50/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/agent/cli.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-5a3d2d50/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8408bb74fafb47c6a5a60ab0b8af6ee28945f321 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50-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-15-skeleton-5a3d2d50/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fe6001d5df281b56aa10f9b4fe2057813f1ea353 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/scenario.json @@ -0,0 +1,820 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "terminal_2", + "text_xor_hex", + "zip_unzip_item", + "terminal_1", + "calc_gcd", + "checksum_crc32_007f" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "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": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_007f": { + "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_14": { + "init_inputs": {}, + "init_outputs": { + "content": "a1b2c3d4e5f67890123456789abcdef0" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation pending verification of input parameters.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_b": "baddecafbaddecafbaddecafbaddecaf" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_payload_data.zip" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System ready. Please input slot data for processing.", + "hex_output": "cafebabecafebabecafebabecafebabe", + "item_dispenser": "Standard Issue Utility Item" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "482910384756291038475629384710", + "b": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "checksum_crc32_007f": { + "init_inputs": { + "hex": "0102030405060708090a0b0c0d0e0f10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 4, a forgotten subterranean server farm deep beneath the Neon City. As a rogue netrunner, your mission is to infiltrate this abandoned corporate blacksite and extract a highly classified prototype hidden within the network. The air is thick with the hum of old cooling fans and the flicker of failing holographic displays. Around you lies a complex web of cryptographic terminals, hash processors, and data synthesizers left behind by the megacorp's hasty retreat. To succeed, you must navigate this interconnected maze of hardware, tracing the data flow from one terminal to the next. You'll need to decrypt raw machine code, compress data streams, and manipulate logic gates to bypass the facility's layered security protocols. Your ultimate goal is to obtain the content of the secure drive, but brute force won't work here. You must rely on your intellect to follow the digital breadcrumbs, activate the dormant systems in the correct sequence, and synthesize the keys you need. The megacorp's ICE (Intrusion Countermeasures Electronics) is still active in the shadows. Move fast, think clearly, and don't let the neon blind you.", + "narrative_style": "cyberpunk" + }, + "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", + "value": "synthesized_item_fcbcf165908dd18a" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "a1b2c3d4e5f67890123456789abcdef0" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "a1b2c3d4e5f67890123456789abcdef0" + } + }, + "narrative": "An encrypted drive left behind in the corporate ruins. It holds the final piece of the puzzle." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "false" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_fcbcf165908dd18a" + } + ], + "narrative": "A matter synthesizer. It requires input from the validation checker to construct the blueprint." + }, + { + "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 logic chip pulsing with a faint, neon-blue energy." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "Calculation pending verification of input parameters." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "A validation checker. It requires input from the central mainframe to verify the sequence." + }, + { + "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": 1068033658 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 3868456827 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending verification of input parameters." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation pending verification of input parameters.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "A central mainframe. It requires inputs from both the hash processor and the secondary hash processor." + }, + { + "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": "3fa8e67a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e693f77b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3868456827 + } + ], + "narrative": "A hash processor. It requires input from the secondary hash processor to finalize calculations." + }, + { + "id": "checksum_crc32_a32c", + "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": "c241e70196f3a562eff5a6e2f67438fc08c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3fa8e67a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1068033658 + } + ], + "narrative": "A secondary hash processor. It requires input from the logic gate to process the data stream." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "789c0bae2c2e49cd55284a4d4ca9d45308c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "baddecafbaddecafbaddecafbaddecaf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "c241e70196f3a562eff5a6e2f67438fc08c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "init": { + "inputs": { + "hex_b": "baddecafbaddecafbaddecafbaddecaf" + }, + "outputs": {} + }, + "narrative": "A logic gate. It requires input from the compression unit to mix the encrypted signals." + }, + { + "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 fragmented data log containing corrupted sector information." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "System ready. Please input slot data for processing." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0bae2c2e49cd55284a4d4ca9d45308c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "narrative": "A compression unit. It requires input from the nexus console to reduce the data footprint." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "System ready. Please input slot data for processing." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_payload_data.zip" + }, + "outputs": {} + }, + "narrative": "An archive extractor. It requires input from the nexus console to unlock protected files." + }, + { + "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": "\tL" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "26" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System ready. Please input slot data for processing." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "cafebabecafebabecafebabecafebabe" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Issue Utility Item" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System ready. Please input slot data for processing.", + "hex_output": "cafebabecafebabecafebabecafebabe", + "item_dispenser": "Standard Issue Utility Item" + } + }, + "narrative": "A nexus console. It requires inputs from both the data decoder and the math coprocessor." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "094c80f1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\tL" + } + ], + "narrative": "A data decoder. It requires input from the primary hash processor to translate the machine code." + }, + { + "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": "482910384756291038475629384710" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "26" + } + ], + "init": { + "inputs": { + "a": "482910384756291038475629384710", + "b": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "A math coprocessor designed to handle heavy cryptographic calculations." + }, + { + "id": "checksum_crc32_007f", + "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": "0102030405060708090a0b0c0d0e0f10" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "094c80f1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 156008689 + } + ], + "init": { + "inputs": { + "hex": "0102030405060708090a0b0c0d0e0f10" + }, + "outputs": {} + }, + "narrative": "A primary hash processor used for initial data integrity verification." + } + ], + "edges": [ + { + "source_id": "matter_synthesizer", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "matter_synthesizer", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "luhn_check", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "blueprint" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "number" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_a32c", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_a32c", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "text_xor_hex", + "target_id": "checksum_crc32_a32c", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zlib_deflate", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32_007f", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-5a3d2d50/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/instruction.md b/tasks/agentescape-15-skeleton-5a3d2d50/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/solution/oracle.py b/tasks/agentescape-15-skeleton-5a3d2d50/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/solution/scenario.json b/tasks/agentescape-15-skeleton-5a3d2d50/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..fe6001d5df281b56aa10f9b4fe2057813f1ea353 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/solution/scenario.json @@ -0,0 +1,820 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "terminal_2", + "text_xor_hex", + "zip_unzip_item", + "terminal_1", + "calc_gcd", + "checksum_crc32_007f" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "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": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32_007f": { + "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_14": { + "init_inputs": {}, + "init_outputs": { + "content": "a1b2c3d4e5f67890123456789abcdef0" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation pending verification of input parameters.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_b": "baddecafbaddecafbaddecafbaddecaf" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secure_payload_data.zip" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System ready. Please input slot data for processing.", + "hex_output": "cafebabecafebabecafebabecafebabe", + "item_dispenser": "Standard Issue Utility Item" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "482910384756291038475629384710", + "b": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "checksum_crc32_007f": { + "init_inputs": { + "hex": "0102030405060708090a0b0c0d0e0f10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to Sector 4, a forgotten subterranean server farm deep beneath the Neon City. As a rogue netrunner, your mission is to infiltrate this abandoned corporate blacksite and extract a highly classified prototype hidden within the network. The air is thick with the hum of old cooling fans and the flicker of failing holographic displays. Around you lies a complex web of cryptographic terminals, hash processors, and data synthesizers left behind by the megacorp's hasty retreat. To succeed, you must navigate this interconnected maze of hardware, tracing the data flow from one terminal to the next. You'll need to decrypt raw machine code, compress data streams, and manipulate logic gates to bypass the facility's layered security protocols. Your ultimate goal is to obtain the content of the secure drive, but brute force won't work here. You must rely on your intellect to follow the digital breadcrumbs, activate the dormant systems in the correct sequence, and synthesize the keys you need. The megacorp's ICE (Intrusion Countermeasures Electronics) is still active in the shadows. Move fast, think clearly, and don't let the neon blind you.", + "narrative_style": "cyberpunk" + }, + "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", + "value": "synthesized_item_fcbcf165908dd18a" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "a1b2c3d4e5f67890123456789abcdef0" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "a1b2c3d4e5f67890123456789abcdef0" + } + }, + "narrative": "An encrypted drive left behind in the corporate ruins. It holds the final piece of the puzzle." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "false" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_fcbcf165908dd18a" + } + ], + "narrative": "A matter synthesizer. It requires input from the validation checker to construct the blueprint." + }, + { + "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 logic chip pulsing with a faint, neon-blue energy." + }, + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "Calculation pending verification of input parameters." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "A validation checker. It requires input from the central mainframe to verify the sequence." + }, + { + "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": 1068033658 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 3868456827 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending verification of input parameters." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation pending verification of input parameters.", + "hex_result": "112233445566778899aabbccddeeff00" + } + }, + "narrative": "A central mainframe. It requires inputs from both the hash processor and the secondary hash processor." + }, + { + "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": "3fa8e67a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e693f77b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3868456827 + } + ], + "narrative": "A hash processor. It requires input from the secondary hash processor to finalize calculations." + }, + { + "id": "checksum_crc32_a32c", + "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": "c241e70196f3a562eff5a6e2f67438fc08c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3fa8e67a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1068033658 + } + ], + "narrative": "A secondary hash processor. It requires input from the logic gate to process the data stream." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "789c0bae2c2e49cd55284a4d4ca9d45308c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "baddecafbaddecafbaddecafbaddecaf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "c241e70196f3a562eff5a6e2f67438fc08c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "init": { + "inputs": { + "hex_b": "baddecafbaddecafbaddecafbaddecaf" + }, + "outputs": {} + }, + "narrative": "A logic gate. It requires input from the compression unit to mix the encrypted signals." + }, + { + "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 fragmented data log containing corrupted sector information." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "System ready. Please input slot data for processing." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0bae2c2e49cd55284a4d4ca9d45308c8494d2c4e55c8cc2b282d5128cec92f5148492c495448cb2f522828ca4f4e2d2ececc4bd70300fcb11341" + } + ], + "narrative": "A compression unit. It requires input from the nexus console to reduce the data footprint." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "System ready. Please input slot data for processing." + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secure_payload_data.zip" + }, + "outputs": {} + }, + "narrative": "An archive extractor. It requires input from the nexus console to unlock protected files." + }, + { + "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": "\tL" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "26" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System ready. Please input slot data for processing." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "cafebabecafebabecafebabecafebabe" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Issue Utility Item" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System ready. Please input slot data for processing.", + "hex_output": "cafebabecafebabecafebabecafebabe", + "item_dispenser": "Standard Issue Utility Item" + } + }, + "narrative": "A nexus console. It requires inputs from both the data decoder and the math coprocessor." + }, + { + "id": "hex_decode", + "name": "Hex to Text Decoder", + "description": "Decode hex to UTF-8 text.", + "type": "Tool", + "template_id": "hex_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex string", + "value": "094c80f1" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\tL" + } + ], + "narrative": "A data decoder. It requires input from the primary hash processor to translate the machine code." + }, + { + "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": "482910384756291038475629384710" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "26" + } + ], + "init": { + "inputs": { + "a": "482910384756291038475629384710", + "b": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "A math coprocessor designed to handle heavy cryptographic calculations." + }, + { + "id": "checksum_crc32_007f", + "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": "0102030405060708090a0b0c0d0e0f10" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "094c80f1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 156008689 + } + ], + "init": { + "inputs": { + "hex": "0102030405060708090a0b0c0d0e0f10" + }, + "outputs": {} + }, + "narrative": "A primary hash processor used for initial data integrity verification." + } + ], + "edges": [ + { + "source_id": "matter_synthesizer", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "item_8", + "target_id": "matter_synthesizer", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "luhn_check", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "blueprint" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "number" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "luhn_check", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_a32c", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_a32c", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "text_xor_hex", + "target_id": "checksum_crc32_a32c", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zlib_deflate", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32_007f", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/solution/solve.sh b/tasks/agentescape-15-skeleton-5a3d2d50/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/task.toml b/tasks/agentescape-15-skeleton-5a3d2d50/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae62dbf156cee14afb64b7263b6c98cfc8b34ed8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "0d2dd3be6f9439abeb0d914f6baf46feeb17164746612fe046be3c650b4f08e6" +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-15-skeleton-5a3d2d50/tests/Dockerfile b/tasks/agentescape-15-skeleton-5a3d2d50/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/tests/expected.json b/tasks/agentescape-15-skeleton-5a3d2d50/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c32502857fe63c0d7ced2d2985980b7e06f5a9cb --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "0d2dd3be6f9439abeb0d914f6baf46feeb17164746612fe046be3c650b4f08e6", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5a3d2d50/tests/grade.py b/tasks/agentescape-15-skeleton-5a3d2d50/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/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-15-skeleton-5a3d2d50/tests/test.sh b/tasks/agentescape-15-skeleton-5a3d2d50/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5a3d2d50/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/environment/Dockerfile b/tasks/agentescape-15-skeleton-5ce97e6c/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-5ce97e6c/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/agent/cli.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-5ce97e6c/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..373758843c813dd4eaf306aa9e1d683ed993658c --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c-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-15-skeleton-5ce97e6c/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f55771e4112d71156530d6801dab07790d01050c --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "checksum_crc32", + "win_condition": { + "type": "tool_output", + "node_id": "checksum_crc32", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute CRC32 Checksum and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "num_base_convert", + "graph_shortest_path", + "unicode_norm", + "checksum_crc32_e135", + "zip_unzip_file", + "terminal_2_1c1d", + "hmac_sha256", + "terminal_2_e18c" + ], + "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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "checksum_crc32_e135": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_1c1d": { + "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" + } + } + }, + "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_e18c": { + "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" + } + } + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n", + "hex_result": "a1b2c3d4e5f60718", + "math_token": "Token_Sequence_Alpha" + } + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]", + "cost": "45281" + } + }, + "unicode_norm": { + "init_inputs": { + "text": "Text with spëciâl chåracters for nòrmalizåtion" + }, + "init_outputs": {} + }, + "checksum_crc32_e135": { + "init_inputs": { + "hex": "112233445566778899aabbcc" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_v4.zip" + }, + "init_outputs": { + "files": "network_graph_data.json" + } + }, + "terminal_2_1c1d": { + "init_inputs": {}, + "init_outputs": { + "text_result": "NFC", + "hex_result": "0011223344556677", + "math_token": "Token_Sequence_Beta" + } + }, + "hmac_sha256": { + "init_inputs": { + "text": "Authorization payload for verification" + }, + "init_outputs": {} + }, + "terminal_2_e18c": { + "init_inputs": { + "num1": "894756382910283746592817", + "num2": "192837465029384756102938" + }, + "init_outputs": { + "text_result": "Final calculation phase pending", + "hex_result": "deadbeef12345678", + "math_token": "Token_Sequence_Gamma" + } + } + }, + "intro_narrative": "Welcome to Sector 7. You are a rogue decker known only as 'Cipher', hired by an anonymous syndicate to breach the Megacorp's central data vault. You've jacked your consciousness directly into their highly restricted subnet, and the Black ICE here is thick. The system is a treacherous labyrinth of obsolete corporate tech patched together with cutting-edge experimental firewalls. If you stay too long, the system's neural-feedback loops will fry your brain. Your ultimate goal is to navigate this digital maze, bypass the Final Verification Node, and extract the encrypted payload before the corporate AI traces your bio-signal. Pay close attention to the flow of data between the various terminals and processors scattered throughout the neon-lit architecture. Every node serves a purpose, and routing the right data to the right machine is the only way to survive.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "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": "48656c6c6f20576f726c6421205468697320697320612062617365363420737472696e67" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b531b46c" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3039933548 + } + ], + "narrative": "Final Verification Node. The ultimate firewall protecting the corporate secrets. It requires input from the Data Decoder Module to complete the hack." + }, + { + "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": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f20576f726c6421205468697320697320612062617365363420737472696e67" + } + ], + "narrative": "Data Decoder Module. A streamlined decryption software suite. It requires input from Mainframe Terminal Alpha." + }, + { + "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": "1900513638" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2982214246" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n", + "hex_result": "a1b2c3d4e5f60718", + "math_token": "Token_Sequence_Alpha" + } + }, + "narrative": "Mainframe Terminal Alpha. The primary access console. It requires inputs from both the Quantum Decryptor and the Signal Converter." + }, + { + "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": 3514300413 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "45281" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3489967917 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1900513638" + } + ], + "narrative": "Quantum Decryptor. A volatile processing core. It requires inputs from the Network Router, the Primary Hash Generator, and the Tertiary Hash Generator." + }, + { + "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": 2982214246 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3514300413 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "2982214246" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "Signal Converter. A complex translation matrix. It requires inputs from both the Primary Hash Generator and the Secondary Hash Generator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "45281" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]", + "cost": "45281" + } + }, + "narrative": "Network Router. An advanced mapping algorithm console. It requires inputs from the Text Formatter, the Archive Extractor, and Mainframe Terminal Beta." + }, + { + "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": "Text with spëciâl chåracters for nòrmalizåtion" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + } + ], + "init": { + "inputs": { + "text": "Text with spëciâl chåracters for nòrmalizåtion" + }, + "outputs": {} + }, + "narrative": "Text Formatter. A glowing data normalization subroutine. It requires input from Mainframe Terminal Beta." + }, + { + "id": "checksum_crc32_e135", + "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": "112233445566778899aabbcc" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d177f7fd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3514300413 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbcc" + }, + "outputs": {} + }, + "narrative": "Primary Hash Generator. A standalone encryption module emitting a low, steady hum." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_v4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_v4.zip" + }, + "outputs": { + "files": "network_graph_data.json" + } + }, + "narrative": "Archive Extractor. A secure unzipping utility guarded by ICE. It requires input from the Text Formatter." + }, + { + "id": "terminal_2_1c1d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 2982214246 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2982214246" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "NFC" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0011223344556677" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Beta" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "NFC", + "hex_result": "0011223344556677", + "math_token": "Token_Sequence_Beta" + } + }, + "narrative": "Mainframe Terminal Beta. A sleek, corporate-issued cyberdeck interface. It requires inputs from both the Secondary Hash Generator and the Signal Converter." + }, + { + "id": "checksum_crc32_4c75", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "narrative": "Secondary Hash Generator. A rack-mounted hashing unit. It requires input from Mainframe Terminal Gamma." + }, + { + "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": "Access Keycard. A physical data chit dropped by a careless corporate guard." + }, + { + "id": "checksum_crc32_a1e7", + "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": "85e117ed3183c7ca1dae13d57577638ca5585152424a9a91114e713e699fd9f2" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d004af2d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3489967917 + } + ], + "narrative": "Tertiary Hash Generator. A heavily armored data processor. It requires input from the Security Authenticator." + }, + { + "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": "b1c0fa66" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authorization payload for verification" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "85e117ed3183c7ca1dae13d57577638ca5585152424a9a91114e713e699fd9f2" + } + ], + "init": { + "inputs": { + "text": "Authorization payload for verification" + }, + "outputs": {} + }, + "narrative": "Security Authenticator. A high-grade verification protocol node. It requires input from the Secondary Hash Generator." + }, + { + "id": "terminal_2_e18c", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "894756382910283746592817" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "192837465029384756102938" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Final calculation phase pending" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Gamma" + } + ], + "init": { + "inputs": { + "num1": "894756382910283746592817", + "num2": "192837465029384756102938" + }, + "outputs": { + "text_result": "Final calculation phase pending", + "hex_result": "deadbeef12345678", + "math_token": "Token_Sequence_Gamma" + } + }, + "narrative": "Mainframe Terminal Gamma. An old, flickering console used for initial system pings." + } + ], + "edges": [ + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "data" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "checksum_crc32_e135", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_e135", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2_1c1d", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "form" + }, + { + "source_id": "terminal_2_1c1d", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "terminal_2_1c1d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_a1e7", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32_a1e7", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2_1c1d", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2_e18c", + "target_id": "checksum_crc32_4c75", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-5ce97e6c/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/instruction.md b/tasks/agentescape-15-skeleton-5ce97e6c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/solution/oracle.py b/tasks/agentescape-15-skeleton-5ce97e6c/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/solution/scenario.json b/tasks/agentescape-15-skeleton-5ce97e6c/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f55771e4112d71156530d6801dab07790d01050c --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/solution/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "checksum_crc32", + "win_condition": { + "type": "tool_output", + "node_id": "checksum_crc32", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute CRC32 Checksum and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "num_base_convert", + "graph_shortest_path", + "unicode_norm", + "checksum_crc32_e135", + "zip_unzip_file", + "terminal_2_1c1d", + "hmac_sha256", + "terminal_2_e18c" + ], + "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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "checksum_crc32_e135": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_2_1c1d": { + "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" + } + } + }, + "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_e18c": { + "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" + } + } + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n", + "hex_result": "a1b2c3d4e5f60718", + "math_token": "Token_Sequence_Alpha" + } + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]", + "cost": "45281" + } + }, + "unicode_norm": { + "init_inputs": { + "text": "Text with spëciâl chåracters for nòrmalizåtion" + }, + "init_outputs": {} + }, + "checksum_crc32_e135": { + "init_inputs": { + "hex": "112233445566778899aabbcc" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_v4.zip" + }, + "init_outputs": { + "files": "network_graph_data.json" + } + }, + "terminal_2_1c1d": { + "init_inputs": {}, + "init_outputs": { + "text_result": "NFC", + "hex_result": "0011223344556677", + "math_token": "Token_Sequence_Beta" + } + }, + "hmac_sha256": { + "init_inputs": { + "text": "Authorization payload for verification" + }, + "init_outputs": {} + }, + "terminal_2_e18c": { + "init_inputs": { + "num1": "894756382910283746592817", + "num2": "192837465029384756102938" + }, + "init_outputs": { + "text_result": "Final calculation phase pending", + "hex_result": "deadbeef12345678", + "math_token": "Token_Sequence_Gamma" + } + } + }, + "intro_narrative": "Welcome to Sector 7. You are a rogue decker known only as 'Cipher', hired by an anonymous syndicate to breach the Megacorp's central data vault. You've jacked your consciousness directly into their highly restricted subnet, and the Black ICE here is thick. The system is a treacherous labyrinth of obsolete corporate tech patched together with cutting-edge experimental firewalls. If you stay too long, the system's neural-feedback loops will fry your brain. Your ultimate goal is to navigate this digital maze, bypass the Final Verification Node, and extract the encrypted payload before the corporate AI traces your bio-signal. Pay close attention to the flow of data between the various terminals and processors scattered throughout the neon-lit architecture. Every node serves a purpose, and routing the right data to the right machine is the only way to survive.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "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": "48656c6c6f20576f726c6421205468697320697320612062617365363420737472696e67" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b531b46c" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3039933548 + } + ], + "narrative": "Final Verification Node. The ultimate firewall protecting the corporate secrets. It requires input from the Data Decoder Module to complete the hack." + }, + { + "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": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "48656c6c6f20576f726c6421205468697320697320612062617365363420737472696e67" + } + ], + "narrative": "Data Decoder Module. A streamlined decryption software suite. It requires input from Mainframe Terminal Alpha." + }, + { + "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": "1900513638" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2982214246" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "SGVsbG8gV29ybGQhIFRoaXMgaXMgYSBiYXNlNjQgc3RyaW5n", + "hex_result": "a1b2c3d4e5f60718", + "math_token": "Token_Sequence_Alpha" + } + }, + "narrative": "Mainframe Terminal Alpha. The primary access console. It requires inputs from both the Quantum Decryptor and the Signal Converter." + }, + { + "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": 3514300413 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "45281" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3489967917 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1900513638" + } + ], + "narrative": "Quantum Decryptor. A volatile processing core. It requires inputs from the Network Router, the Primary Hash Generator, and the Tertiary Hash Generator." + }, + { + "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": 2982214246 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3514300413 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "2982214246" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "Signal Converter. A complex translation matrix. It requires inputs from both the Primary Hash Generator and the Secondary Hash Generator." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "45281" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"start_node\", \"alpha_hub\", \"beta_relay\", \"gamma_gateway\", \"delta_point\", \"end_node\"]", + "cost": "45281" + } + }, + "narrative": "Network Router. An advanced mapping algorithm console. It requires inputs from the Text Formatter, the Archive Extractor, and Mainframe Terminal Beta." + }, + { + "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": "Text with spëciâl chåracters for nòrmalizåtion" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + } + ], + "init": { + "inputs": { + "text": "Text with spëciâl chåracters for nòrmalizåtion" + }, + "outputs": {} + }, + "narrative": "Text Formatter. A glowing data normalization subroutine. It requires input from Mainframe Terminal Beta." + }, + { + "id": "checksum_crc32_e135", + "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": "112233445566778899aabbcc" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d177f7fd" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3514300413 + } + ], + "init": { + "inputs": { + "hex": "112233445566778899aabbcc" + }, + "outputs": {} + }, + "narrative": "Primary Hash Generator. A standalone encryption module emitting a low, steady hum." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_v4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Text with spëciâl chåracters for nòrmalizåtion" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_v4.zip" + }, + "outputs": { + "files": "network_graph_data.json" + } + }, + "narrative": "Archive Extractor. A secure unzipping utility guarded by ICE. It requires input from the Text Formatter." + }, + { + "id": "terminal_2_1c1d", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 2982214246 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2982214246" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "NFC" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "0011223344556677" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Beta" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "NFC", + "hex_result": "0011223344556677", + "math_token": "Token_Sequence_Beta" + } + }, + "narrative": "Mainframe Terminal Beta. A sleek, corporate-issued cyberdeck interface. It requires inputs from both the Secondary Hash Generator and the Signal Converter." + }, + { + "id": "checksum_crc32_4c75", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "narrative": "Secondary Hash Generator. A rack-mounted hashing unit. It requires input from Mainframe Terminal Gamma." + }, + { + "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": "Access Keycard. A physical data chit dropped by a careless corporate guard." + }, + { + "id": "checksum_crc32_a1e7", + "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": "85e117ed3183c7ca1dae13d57577638ca5585152424a9a91114e713e699fd9f2" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d004af2d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3489967917 + } + ], + "narrative": "Tertiary Hash Generator. A heavily armored data processor. It requires input from the Security Authenticator." + }, + { + "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": "b1c0fa66" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authorization payload for verification" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "85e117ed3183c7ca1dae13d57577638ca5585152424a9a91114e713e699fd9f2" + } + ], + "init": { + "inputs": { + "text": "Authorization payload for verification" + }, + "outputs": {} + }, + "narrative": "Security Authenticator. A high-grade verification protocol node. It requires input from the Secondary Hash Generator." + }, + { + "id": "terminal_2_e18c", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "894756382910283746592817" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "192837465029384756102938" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Final calculation phase pending" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Token_Sequence_Gamma" + } + ], + "init": { + "inputs": { + "num1": "894756382910283746592817", + "num2": "192837465029384756102938" + }, + "outputs": { + "text_result": "Final calculation phase pending", + "hex_result": "deadbeef12345678", + "math_token": "Token_Sequence_Gamma" + } + }, + "narrative": "Mainframe Terminal Gamma. An old, flickering console used for initial system pings." + } + ], + "edges": [ + { + "source_id": "base64_decode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "data" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "checksum_crc32_e135", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_e135", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_2_1c1d", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "form" + }, + { + "source_id": "terminal_2_1c1d", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "terminal_2_1c1d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_a1e7", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32_a1e7", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2_1c1d", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32_4c75", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2_e18c", + "target_id": "checksum_crc32_4c75", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/solution/solve.sh b/tasks/agentescape-15-skeleton-5ce97e6c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/task.toml b/tasks/agentescape-15-skeleton-5ce97e6c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7903ff0763f92acbfc1528e130b0454600d75b3e --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "fcf89158752a950831824260324ca61a9ad5cdeaaf73105f21bc5763f955829d" +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-15-skeleton-5ce97e6c/tests/Dockerfile b/tasks/agentescape-15-skeleton-5ce97e6c/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/tests/expected.json b/tasks/agentescape-15-skeleton-5ce97e6c/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5b657c7accec393ecb535f68bb66c3ec9b57f99a --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "fcf89158752a950831824260324ca61a9ad5cdeaaf73105f21bc5763f955829d", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-5ce97e6c/tests/grade.py b/tasks/agentescape-15-skeleton-5ce97e6c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/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-15-skeleton-5ce97e6c/tests/test.sh b/tasks/agentescape-15-skeleton-5ce97e6c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-5ce97e6c/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-61902d69/environment/Dockerfile b/tasks/agentescape-15-skeleton-61902d69/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-61902d69/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/agent/cli.py b/tasks/agentescape-15-skeleton-61902d69/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-61902d69/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9b2f75271b88c4699263938789fe58d6015dd2d --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69-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-15-skeleton-61902d69/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..e1b10242efe5dbec3aa5a2d1dd66b18bb2590be0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/scenario.json @@ -0,0 +1,894 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "hash_sha256", + "win_condition": { + "type": "tool_output", + "node_id": "hash_sha256", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute SHA-256 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "num_base_convert", + "calc_bigmul", + "calc_modexp", + "zlib_deflate", + "calc_modexp_1b7b", + "num_base_convert_f1bc", + "hex_encode" + ], + "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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "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": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "calc_modexp_1b7b": { + "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": {} + }, + "num_base_convert_f1bc": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initialization sequence complete.", + "hex_result": "4a6f686e446f65313233", + "math_token": "TOKEN_START_OP_882" + } + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "293847561029384756102938", + "b": "918273645091827364509182" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "mod": "100003" + }, + "init_outputs": {} + }, + "zlib_deflate": { + "init_inputs": { + "text": "Compress this payload to generate a unique fingerprint hash for the container." + }, + "init_outputs": {} + }, + "calc_modexp_1b7b": { + "init_inputs": { + "base": "2", + "mod": "65537" + }, + "init_outputs": {} + }, + "num_base_convert_f1bc": { + "init_inputs": { + "s": "582039485726192039485726", + "from_base": "10" + }, + "init_outputs": {} + }, + "hex_encode": { + "init_inputs": { + "text": "Raw text data for hexadecimal encoding." + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the workshop of the late clockwork engineer, Archibald Vance. You find yourself trapped inside his master control room, a chaotic symphony of hissing pipes, rotating gears, and polished brass mechanisms. Vance was intensely paranoid, securing the exit behind a complex network of steam-powered calculation engines and mechanical ciphers. The air is thick with the smell of oil and ozone. To escape, you must trace the flow of energy through his strange contraptions, powering each device in the correct sequence to activate the final lock mechanism before the workshop's boiler pressure reaches a catastrophic critical state.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "False" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe" + } + ], + "narrative": "This is the final lock mechanism. It requires input from the banking authenticator to disengage the massive vault door." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "Vavgvnyvmngvba frdhrapr pbzcyrgr." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "This is the banking authenticator. It requires input from the cylinder cipher to verify the stamped financial codes." + }, + { + "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": "Initialization sequence complete." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Vavgvnyvmngvba frdhrapr pbzcyrgr." + } + ], + "narrative": "This is the cylinder cipher. It requires inputs from both the mechanical typewriter and the gear calibrator to correctly rotate its lettered rings." + }, + { + "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": "95074" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initialization sequence complete." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a6f686e446f65313233" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "TOKEN_START_OP_882" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initialization sequence complete.", + "hex_result": "4a6f686e446f65313233", + "math_token": "TOKEN_START_OP_882" + } + }, + "narrative": "This is the mechanical typewriter. It requires inputs from both the output condenser and the brass multiplier before its heavy keys can be struck." + }, + { + "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": "95074" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95074" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the output condenser. It requires inputs from both the main steam turbine and the central mixing valve to cool the pressurized data." + }, + { + "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": "293847561029384756102938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "918273645091827364509182" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938", + "b": "918273645091827364509182" + }, + "outputs": {} + }, + "narrative": "A heavy brass multiplier with overlapping gears. It sits quietly on the workbench, waiting for its cranks to be turned." + }, + { + "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": "269832470967796339190860289983789898077438176716" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "65505" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "95074" + } + ], + "init": { + "inputs": { + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the main steam turbine. It requires inputs from both the central mixing valve and the secondary pressure regulator to achieve optimal rotation." + }, + { + "id": "num_base_convert_0223", + "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": "269832470967796339190860289983789898077438176716" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "582039485726192039485726" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "narrative": "This is the central mixing valve. It requires inputs from the brass multiplier, the gear calibrator, and the primary gauge converter to balance the system." + }, + { + "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": "5261772074657874206461746120666f722068657861646563696d616c20656e636f64696e672e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e306de95" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3808878229 + } + ], + "narrative": "This is the gear calibrator. It requires input from the text encoder to align its internal teeth perfectly." + }, + { + "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 beautiful brass pocket watch with strange geometric markings and an unusually fast ticking sound." + }, + { + "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": "789c0dcbc11180300804c056ae029bb012462f09330a11c8c3eef5bfbbfb3d8399a8a18929efe572a21c9dc6902204cbf4594453eb8c196a852139d03cfe461c6e25faf3ed0388c51d3a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the pressure vault. It requires input from the steam compressor to safely release its pneumatic seals." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Compress this payload to generate a unique fingerprint hash for the container." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dcbc11180300804c056ae029bb012462f09330a11c8c3eef5bfbbfb3d8399a8a18929efe572a21c9dc6902204cbf4594453eb8c196a852139d03cfe461c6e25faf3ed0388c51d3a" + } + ], + "init": { + "inputs": { + "text": "Compress this payload to generate a unique fingerprint hash for the container." + }, + "outputs": {} + }, + "narrative": "A copper steam compressor with various pressure dials and hissing exhaust pipes." + }, + { + "id": "calc_modexp_1b7b", + "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": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3808878229 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "65505" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "This is the secondary pressure regulator. It requires input from the gear calibrator to stabilize the erratic steam flow." + }, + { + "id": "num_base_convert_f1bc", + "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": "582039485726192039485726" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "582039485726192039485726" + } + ], + "init": { + "inputs": { + "s": "582039485726192039485726", + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the primary gauge converter. It requires input from the gear calibrator to translate the mechanical readings." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Raw text data for hexadecimal encoding." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5261772074657874206461746120666f722068657861646563696d616c20656e636f64696e672e" + } + ], + "init": { + "inputs": { + "text": "Raw text data for hexadecimal encoding." + }, + "outputs": {} + }, + "narrative": "A delicate text encoder made of finely crafted clockwork parts and bronze levers." + } + ], + "edges": [ + { + "source_id": "iban_validate", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "text_rotN", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "iban" + }, + { + "source_id": "terminal_2", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "num_base_convert_0223", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "zlib_deflate", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert_0223", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp_1b7b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_f1bc", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_f1bc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_1b7b", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "hex_encode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-61902d69/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/instruction.md b/tasks/agentescape-15-skeleton-61902d69/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/solution/oracle.py b/tasks/agentescape-15-skeleton-61902d69/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/solution/scenario.json b/tasks/agentescape-15-skeleton-61902d69/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..e1b10242efe5dbec3aa5a2d1dd66b18bb2590be0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/solution/scenario.json @@ -0,0 +1,894 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "hash_sha256", + "win_condition": { + "type": "tool_output", + "node_id": "hash_sha256", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute SHA-256 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "num_base_convert", + "calc_bigmul", + "calc_modexp", + "zlib_deflate", + "calc_modexp_1b7b", + "num_base_convert_f1bc", + "hex_encode" + ], + "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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "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": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "calc_modexp_1b7b": { + "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": {} + }, + "num_base_convert_f1bc": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initialization sequence complete.", + "hex_result": "4a6f686e446f65313233", + "math_token": "TOKEN_START_OP_882" + } + }, + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "293847561029384756102938", + "b": "918273645091827364509182" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "mod": "100003" + }, + "init_outputs": {} + }, + "zlib_deflate": { + "init_inputs": { + "text": "Compress this payload to generate a unique fingerprint hash for the container." + }, + "init_outputs": {} + }, + "calc_modexp_1b7b": { + "init_inputs": { + "base": "2", + "mod": "65537" + }, + "init_outputs": {} + }, + "num_base_convert_f1bc": { + "init_inputs": { + "s": "582039485726192039485726", + "from_base": "10" + }, + "init_outputs": {} + }, + "hex_encode": { + "init_inputs": { + "text": "Raw text data for hexadecimal encoding." + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the workshop of the late clockwork engineer, Archibald Vance. You find yourself trapped inside his master control room, a chaotic symphony of hissing pipes, rotating gears, and polished brass mechanisms. Vance was intensely paranoid, securing the exit behind a complex network of steam-powered calculation engines and mechanical ciphers. The air is thick with the smell of oil and ozone. To escape, you must trace the flow of energy through his strange contraptions, powering each device in the correct sequence to activate the final lock mechanism before the workshop's boiler pressure reaches a catastrophic critical state.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "False" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "60a33e6cf5151f2d52eddae9685cfa270426aa89d8dbc7dfb854606f1d1a40fe" + } + ], + "narrative": "This is the final lock mechanism. It requires input from the banking authenticator to disengage the massive vault door." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "Vavgvnyvmngvba frdhrapr pbzcyrgr." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "This is the banking authenticator. It requires input from the cylinder cipher to verify the stamped financial codes." + }, + { + "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": "Initialization sequence complete." + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Vavgvnyvmngvba frdhrapr pbzcyrgr." + } + ], + "narrative": "This is the cylinder cipher. It requires inputs from both the mechanical typewriter and the gear calibrator to correctly rotate its lettered rings." + }, + { + "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": "95074" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initialization sequence complete." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a6f686e446f65313233" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "TOKEN_START_OP_882" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initialization sequence complete.", + "hex_result": "4a6f686e446f65313233", + "math_token": "TOKEN_START_OP_882" + } + }, + "narrative": "This is the mechanical typewriter. It requires inputs from both the output condenser and the brass multiplier before its heavy keys can be struck." + }, + { + "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": "95074" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "95074" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the output condenser. It requires inputs from both the main steam turbine and the central mixing valve to cool the pressurized data." + }, + { + "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": "293847561029384756102938" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "918273645091827364509182" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938", + "b": "918273645091827364509182" + }, + "outputs": {} + }, + "narrative": "A heavy brass multiplier with overlapping gears. It sits quietly on the workbench, waiting for its cranks to be turned." + }, + { + "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": "269832470967796339190860289983789898077438176716" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "65505" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "95074" + } + ], + "init": { + "inputs": { + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the main steam turbine. It requires inputs from both the central mixing valve and the secondary pressure regulator to achieve optimal rotation." + }, + { + "id": "num_base_convert_0223", + "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": "269832470967796339190860289983789898077438176716" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "582039485726192039485726" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "269832470967796339190860289983789898077438176716" + } + ], + "narrative": "This is the central mixing valve. It requires inputs from the brass multiplier, the gear calibrator, and the primary gauge converter to balance the system." + }, + { + "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": "5261772074657874206461746120666f722068657861646563696d616c20656e636f64696e672e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e306de95" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3808878229 + } + ], + "narrative": "This is the gear calibrator. It requires input from the text encoder to align its internal teeth perfectly." + }, + { + "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 beautiful brass pocket watch with strange geometric markings and an unusually fast ticking sound." + }, + { + "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": "789c0dcbc11180300804c056ae029bb012462f09330a11c8c3eef5bfbbfb3d8399a8a18929efe572a21c9dc6902204cbf4594453eb8c196a852139d03cfe461c6e25faf3ed0388c51d3a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the pressure vault. It requires input from the steam compressor to safely release its pneumatic seals." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Compress this payload to generate a unique fingerprint hash for the container." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dcbc11180300804c056ae029bb012462f09330a11c8c3eef5bfbbfb3d8399a8a18929efe572a21c9dc6902204cbf4594453eb8c196a852139d03cfe461c6e25faf3ed0388c51d3a" + } + ], + "init": { + "inputs": { + "text": "Compress this payload to generate a unique fingerprint hash for the container." + }, + "outputs": {} + }, + "narrative": "A copper steam compressor with various pressure dials and hissing exhaust pipes." + }, + { + "id": "calc_modexp_1b7b", + "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": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3808878229 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "65505" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "This is the secondary pressure regulator. It requires input from the gear calibrator to stabilize the erratic steam flow." + }, + { + "id": "num_base_convert_f1bc", + "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": "582039485726192039485726" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 3808878229 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "582039485726192039485726" + } + ], + "init": { + "inputs": { + "s": "582039485726192039485726", + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the primary gauge converter. It requires input from the gear calibrator to translate the mechanical readings." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Raw text data for hexadecimal encoding." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5261772074657874206461746120666f722068657861646563696d616c20656e636f64696e672e" + } + ], + "init": { + "inputs": { + "text": "Raw text data for hexadecimal encoding." + }, + "outputs": {} + }, + "narrative": "A delicate text encoder made of finely crafted clockwork parts and bronze levers." + } + ], + "edges": [ + { + "source_id": "iban_validate", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "text_rotN", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "iban" + }, + { + "source_id": "terminal_2", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "num_base_convert_0223", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "item_16", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "zlib_deflate", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert_0223", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp_1b7b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_f1bc", + "target_id": "num_base_convert_0223", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_f1bc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_1b7b", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "hex_encode", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-61902d69/solution/solve.sh b/tasks/agentescape-15-skeleton-61902d69/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-61902d69/task.toml b/tasks/agentescape-15-skeleton-61902d69/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a039c91f4a883c4d394ae2da061f428bda36f2b6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "ed7ae04c4df6f86df6dee9c8f4cd959fc4b70c362eaea653fcfd77292a0776af" +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-15-skeleton-61902d69/tests/Dockerfile b/tasks/agentescape-15-skeleton-61902d69/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-61902d69/tests/expected.json b/tasks/agentescape-15-skeleton-61902d69/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6b59c6b37b377523e0e2d31d5a52bb12388783 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "ed7ae04c4df6f86df6dee9c8f4cd959fc4b70c362eaea653fcfd77292a0776af", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-61902d69/tests/grade.py b/tasks/agentescape-15-skeleton-61902d69/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/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-15-skeleton-61902d69/tests/test.sh b/tasks/agentescape-15-skeleton-61902d69/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-61902d69/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-64331efd/environment/Dockerfile b/tasks/agentescape-15-skeleton-64331efd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-64331efd/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/agent/cli.py b/tasks/agentescape-15-skeleton-64331efd/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-64331efd/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b88d5385ad3c6e5727a51aa947398506ce13f88 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd-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-15-skeleton-64331efd/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5f95eb48fe288e633604b210e72bc66018a30901 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/scenario.json @@ -0,0 +1,832 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "hash_md5", + "win_condition": { + "type": "tool_output", + "node_id": "hash_md5", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute MD5 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "graph_shortest_path", + "text_rotN", + "checksum_crc32", + "graph_shortest_path_1ceb", + "luhn_check" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "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_1ceb": { + "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" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Standard output stream initialization successful.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "traffic_network_v3.json" + }, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]", + "cost": "482915" + } + }, + "text_rotN": { + "init_inputs": { + "n": "928374651029384756102938" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "abcdef0123456789abcdef0123456789" + }, + "init_outputs": {} + }, + "graph_shortest_path_1ceb": { + "init_inputs": { + "file_id": "server_topology_map.xml", + "dst": "Backup_Server_Rack_09" + }, + "init_outputs": { + "path": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]", + "cost": "157293" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4929485720193847" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Rain lashes against the window of the safehouse. You are standing in the abandoned office of 'The Architect,' a notorious data broker who vanished three days ago. He left behind a tangled web of digital security measures and encrypted servers. Your client needs the master key hidden within this system to prevent a financial meltdown. The room is filled with humming servers, scattered notes, and strange standalone computing devices. To find the key, you must trace the flow of data, decrypt the layers, and boot up the mainframes in the correct order. The clock is ticking.", + "narrative_style": "detective" + }, + "nodes": [ + { + "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": "eJwLLknMS0ksSlHILy0pKC1RKC4pSk3MVcjMyyzJTMzJrEosyczPUyguTU5OLS5OK83RAwDhBBNF" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "4bb60bb2b6dc47ec6ae888312fbb5646" + } + ], + "narrative": "The Master Lock. This final encryption layer guards the victory condition. It requires the specific encoded string from the Encoding Module." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "789c0b2e49cc4b492c4a51c82f2d29282d51282e294a4dcc55c8cccb2cc94cccc9ac4a2cc9cccf53282e4d4e4e2d2e4e2bcdd10300e1041345" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJwLLknMS0ksSlHILy0pKC1RKC4pSk3MVcjMyyzJTMzJrEosyczPUyguTU5OLS5OK83RAwDhBBNF" + } + ], + "narrative": "The Encoding Module. It transforms raw data into a readable format. It requires the compressed hex stream from the Compression Utility." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Standard output stream initialization successful." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0b2e49cc4b492c4a51c82f2d29282d51282e294a4dcc55c8cccb2cc94cccc9ac4a2cc9cccf53282e4d4e4e2d2e4e2bcdd10300e1041345" + } + ], + "narrative": "An automated Compression Utility running on a side monitor. It waits to archive the text output from the Mainframe Terminal." + }, + { + "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": "4346235" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2098862075025" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Standard output stream initialization successful." + }, + { + "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": {}, + "outputs": { + "text_result": "Standard output stream initialization successful.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Terminal, the heart of the operation. It requires the synchronized large integer outputs from both Quantum Processor A and Quantum Processor B to unlock." + }, + { + "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": "4346235" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "482915" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2098862075025" + } + ], + "narrative": "Quantum Processor B, the right hemisphere of the system. It requires the calculation result from Quantum Processor A and the cost metric from Network Router Beta." + }, + { + "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 secure access card with a magnetic strip." + }, + { + "id": "calc_bigmul_b530", + "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": "9" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "482915" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4346235" + } + ], + "narrative": "Quantum Processor A, the left hemisphere of the system. It calculates a massive value based on data from the Signal Harmonizer and Network Router Beta." + }, + { + "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": "traffic_network_v3.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Lgryk" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "False" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": { + "file_id": "traffic_network_v3.json" + }, + "outputs": { + "path": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]", + "cost": "482915" + } + }, + "narrative": "This is Network Router Beta, a more advanced mapping tool. It requires specific coordinate inputs from both the Shift Decoder and the Bank Account Authenticator." + }, + { + "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": "False" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "928374651029384756102938" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Lgryk" + } + ], + "init": { + "inputs": { + "n": "928374651029384756102938" + }, + "outputs": {} + }, + "narrative": "A legacy Shift Decoder module. It requires the validation status string from the Bank Account Authenticator to decrypt its message." + }, + { + "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": 3398441922 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "157293" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "narrative": "The Signal Harmonizer unit. It requires synchronized inputs from both the Data Integrity Scanner and Network Router Alpha to calculate the common frequency." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "A dedicated Bank Account Authenticator terminal. It needs the routing path generated by Network Router Alpha to verify the account status." + }, + { + "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": "abcdef0123456789abcdef0123456789" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ca901bc2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3398441922 + } + ], + "init": { + "inputs": { + "hex": "abcdef0123456789abcdef0123456789" + }, + "outputs": {} + }, + "narrative": "A handheld Data Integrity Scanner used for verifying raw binary blocks. It's currently idle." + }, + { + "id": "graph_shortest_path_1ceb", + "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": "server_topology_map.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Backup_Server_Rack_09" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "157293" + } + ], + "init": { + "inputs": { + "file_id": "server_topology_map.xml", + "dst": "Backup_Server_Rack_09" + }, + "outputs": { + "path": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]", + "cost": "157293" + } + }, + "narrative": "This is Network Router Alpha. It requires a valid identification number from the Credit Card Verifier to determine the initial packet route." + }, + { + "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 crumpled sticky note with a timezone offset scribbled on it." + }, + { + "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": "4929485720193847" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4929485720193847" + }, + "outputs": {} + }, + "narrative": "A dusty credit card verification device sits on the edge of the desk. It appears to be functional." + } + ], + "edges": [ + { + "source_id": "base64_encode", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "zlib_deflate", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_b530", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul_b530", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_bigmul_b530", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_b530", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_1ceb", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path_1ceb", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "iban" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_1ceb", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-64331efd/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/instruction.md b/tasks/agentescape-15-skeleton-64331efd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/solution/oracle.py b/tasks/agentescape-15-skeleton-64331efd/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/solution/scenario.json b/tasks/agentescape-15-skeleton-64331efd/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..5f95eb48fe288e633604b210e72bc66018a30901 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/solution/scenario.json @@ -0,0 +1,832 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "hash_md5", + "win_condition": { + "type": "tool_output", + "node_id": "hash_md5", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute MD5 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "graph_shortest_path", + "text_rotN", + "checksum_crc32", + "graph_shortest_path_1ceb", + "luhn_check" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "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_1ceb": { + "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" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Standard output stream initialization successful.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "traffic_network_v3.json" + }, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]", + "cost": "482915" + } + }, + "text_rotN": { + "init_inputs": { + "n": "928374651029384756102938" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "abcdef0123456789abcdef0123456789" + }, + "init_outputs": {} + }, + "graph_shortest_path_1ceb": { + "init_inputs": { + "file_id": "server_topology_map.xml", + "dst": "Backup_Server_Rack_09" + }, + "init_outputs": { + "path": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]", + "cost": "157293" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4929485720193847" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Rain lashes against the window of the safehouse. You are standing in the abandoned office of 'The Architect,' a notorious data broker who vanished three days ago. He left behind a tangled web of digital security measures and encrypted servers. Your client needs the master key hidden within this system to prevent a financial meltdown. The room is filled with humming servers, scattered notes, and strange standalone computing devices. To find the key, you must trace the flow of data, decrypt the layers, and boot up the mainframes in the correct order. The clock is ticking.", + "narrative_style": "detective" + }, + "nodes": [ + { + "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": "eJwLLknMS0ksSlHILy0pKC1RKC4pSk3MVcjMyyzJTMzJrEosyczPUyguTU5OLS5OK83RAwDhBBNF" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "4bb60bb2b6dc47ec6ae888312fbb5646" + } + ], + "narrative": "The Master Lock. This final encryption layer guards the victory condition. It requires the specific encoded string from the Encoding Module." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "789c0b2e49cc4b492c4a51c82f2d29282d51282e294a4dcc55c8cccb2cc94cccc9ac4a2cc9cccf53282e4d4e4e2d2e4e2bcdd10300e1041345" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJwLLknMS0ksSlHILy0pKC1RKC4pSk3MVcjMyyzJTMzJrEosyczPUyguTU5OLS5OK83RAwDhBBNF" + } + ], + "narrative": "The Encoding Module. It transforms raw data into a readable format. It requires the compressed hex stream from the Compression Utility." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Standard output stream initialization successful." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0b2e49cc4b492c4a51c82f2d29282d51282e294a4dcc55c8cccb2cc94cccc9ac4a2cc9cccf53282e4d4e4e2d2e4e2bcdd10300e1041345" + } + ], + "narrative": "An automated Compression Utility running on a side monitor. It waits to archive the text output from the Mainframe Terminal." + }, + { + "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": "4346235" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "2098862075025" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Standard output stream initialization successful." + }, + { + "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": {}, + "outputs": { + "text_result": "Standard output stream initialization successful.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Terminal, the heart of the operation. It requires the synchronized large integer outputs from both Quantum Processor A and Quantum Processor B to unlock." + }, + { + "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": "4346235" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "482915" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2098862075025" + } + ], + "narrative": "Quantum Processor B, the right hemisphere of the system. It requires the calculation result from Quantum Processor A and the cost metric from Network Router Beta." + }, + { + "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 secure access card with a magnetic strip." + }, + { + "id": "calc_bigmul_b530", + "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": "9" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "482915" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "4346235" + } + ], + "narrative": "Quantum Processor A, the left hemisphere of the system. It calculates a massive value based on data from the Signal Harmonizer and Network Router Beta." + }, + { + "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": "traffic_network_v3.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Lgryk" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "False" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": { + "file_id": "traffic_network_v3.json" + }, + "outputs": { + "path": "[\"Node_Start\", \"Node_Junction_42\", \"Node_Bridge_East\", \"Node_End\"]", + "cost": "482915" + } + }, + "narrative": "This is Network Router Beta, a more advanced mapping tool. It requires specific coordinate inputs from both the Shift Decoder and the Bank Account Authenticator." + }, + { + "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": "False" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "928374651029384756102938" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Lgryk" + } + ], + "init": { + "inputs": { + "n": "928374651029384756102938" + }, + "outputs": {} + }, + "narrative": "A legacy Shift Decoder module. It requires the validation status string from the Bank Account Authenticator to decrypt its message." + }, + { + "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": 3398441922 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "157293" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "narrative": "The Signal Harmonizer unit. It requires synchronized inputs from both the Data Integrity Scanner and Network Router Alpha to calculate the common frequency." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "A dedicated Bank Account Authenticator terminal. It needs the routing path generated by Network Router Alpha to verify the account status." + }, + { + "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": "abcdef0123456789abcdef0123456789" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ca901bc2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3398441922 + } + ], + "init": { + "inputs": { + "hex": "abcdef0123456789abcdef0123456789" + }, + "outputs": {} + }, + "narrative": "A handheld Data Integrity Scanner used for verifying raw binary blocks. It's currently idle." + }, + { + "id": "graph_shortest_path_1ceb", + "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": "server_topology_map.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "false" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Backup_Server_Rack_09" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "157293" + } + ], + "init": { + "inputs": { + "file_id": "server_topology_map.xml", + "dst": "Backup_Server_Rack_09" + }, + "outputs": { + "path": "[\"Gateway_01\", \"Switch_Core_A\", \"Router_Edge_5\", \"Backup_Server_Rack_09\"]", + "cost": "157293" + } + }, + "narrative": "This is Network Router Alpha. It requires a valid identification number from the Credit Card Verifier to determine the initial packet route." + }, + { + "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 crumpled sticky note with a timezone offset scribbled on it." + }, + { + "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": "4929485720193847" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4929485720193847" + }, + "outputs": {} + }, + "narrative": "A dusty credit card verification device sits on the edge of the desk. It appears to be functional." + } + ], + "edges": [ + { + "source_id": "base64_encode", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "zlib_deflate", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_2", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_b530", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul_b530", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_bigmul_b530", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul_b530", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_1ceb", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path_1ceb", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "iban" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_1ceb", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-64331efd/solution/solve.sh b/tasks/agentescape-15-skeleton-64331efd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-64331efd/task.toml b/tasks/agentescape-15-skeleton-64331efd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf117c5bbb5163ca5db4c7aef2baba199ddf69f7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "511d4593b43c41fe9e938dd949d0219bb27a2ce309ad93eba3b662ec8464dbb8" +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-15-skeleton-64331efd/tests/Dockerfile b/tasks/agentescape-15-skeleton-64331efd/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-64331efd/tests/expected.json b/tasks/agentescape-15-skeleton-64331efd/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..916788af912259a4bae79cba5b1101b9dcd67d0c --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "511d4593b43c41fe9e938dd949d0219bb27a2ce309ad93eba3b662ec8464dbb8", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-64331efd/tests/grade.py b/tasks/agentescape-15-skeleton-64331efd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/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-15-skeleton-64331efd/tests/test.sh b/tasks/agentescape-15-skeleton-64331efd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-64331efd/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-6c05dc66/environment/Dockerfile b/tasks/agentescape-15-skeleton-6c05dc66/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-6c05dc66/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/agent/cli.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-6c05dc66/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f76b643a9fdfaf485f27f94cdbd3f0b6a78475ea --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66-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-15-skeleton-6c05dc66/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b2b225ff6089eef0062fc7830f9d4d6f4557eb7d --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/scenario.json @@ -0,0 +1,1033 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "crypto_rsa_decrypt_hex", + "win_condition": { + "type": "tool_output", + "node_id": "crypto_rsa_decrypt_hex", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute RSA Decrypt and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_f1fe", + "calc_modexp", + "unicode_norm", + "calc_gcd", + "graph_shortest_path_97e2", + "container_1", + "calc_modexp_ba80" + ], + "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" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_f1fe": { + "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_modexp": { + "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": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_97e2": { + "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" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_ba80": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System ready. Awaiting inputs for processing.", + "hex_output": "48656c6c6f20576f726c642120313233", + "item_dispenser": "Standard Item Dispenser Unit 01" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]", + "cost": "10000000000000001024" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword!2024" + }, + "init_outputs": { + "files": "data_payload.json" + } + }, + "zip_unzip_file_f1fe": { + "init_inputs": { + "zip_id": "archive_backup.zip", + "password": "ComplexPass#9988" + }, + "init_outputs": { + "files": "topology_graph.json" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "827364591827364501928374", + "mod": "65537" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Fuglateszt", + "form": "NFC" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "29384756102938475610", + "b": "10293847561029384756" + }, + "init_outputs": {} + }, + "graph_shortest_path_97e2": { + "init_inputs": { + "src": "AlphaGate", + "dst": "OmegaGate" + }, + "init_outputs": { + "path": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]", + "cost": "20000000000000000256" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "calc_modexp_ba80": { + "init_inputs": { + "mod": "10007" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are Detective Vance, currently standing inside the cooled server room of the notorious 'Phantom Syndicate'. You have successfully physically breached their headquarters, but the real vault is digital. Before you lies a complex array of servers, forensic tools, and encrypted drives. The Syndicate is erasing their tracks; the fans are whirring loudly as their kill-switch protocols initiate. You must navigate their twisted network logic, utilize their own cryptographic tools against them, and recover the master ledger before the system wipes everything. Every piece of data you find is a key to a larger puzzle.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "48656c6c6f20576f726c642120313233" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "10000000000000001024" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "180000000018" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "7c1c\u0012\u0004i" + } + ], + "narrative": "The Master Decryptor. This is the final cryptographic barrier protecting the syndicate's ledger. It requires synchronized inputs from the Mainframe Terminal, the Network Tracer Beta, and the Coordinate Converter to break the encryption." + }, + { + "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": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "10000000000000001024" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System ready. Awaiting inputs for processing." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f20576f726c642120313233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Item Dispenser Unit 01" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System ready. Awaiting inputs for processing.", + "hex_output": "48656c6c6f20576f726c642120313233", + "item_dispenser": "Standard Item Dispenser Unit 01" + } + }, + "narrative": "The Mainframe Terminal. A black screen with a blinking cursor, waiting to execute system commands. It processes the routing data generated by the Network Tracer Beta." + }, + { + "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": "data_payload.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Fuglateszt" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10000000000000001024" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]", + "cost": "10000000000000001024" + } + }, + "narrative": "Network Tracer Beta. An advanced packet sniffing algorithm hidden deep in the system. It requires the graph file from the Encrypted Partition B, the standardized text from the Text Sanitizer, and the destination data from Network Tracer Alpha." + }, + { + "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": "Access Code. A numeric sequence retrieved from the decoded server logs." + }, + { + "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": "Server Log. A printout containing timezone data and server timestamps." + }, + { + "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": "topology_graph.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "data_payload.json" + } + ], + "init": { + "inputs": { + "password": "SecurePassword!2024" + }, + "outputs": { + "files": "data_payload.json" + } + }, + "narrative": "Encrypted Partition B. A secure, password-protected folder found on the backup drive. It requires the file structure extracted from the Primary Evidence Archive." + }, + { + "id": "zip_unzip_file_f1fe", + "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_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "ComplexPass#9988" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_backup.zip", + "password": "ComplexPass#9988" + }, + "outputs": { + "files": "topology_graph.json" + } + }, + "narrative": "Primary Evidence Archive. A seized compressed file containing the initial network topology maps." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "180000000018" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "20000000000000000256" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "24089" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "180000000018" + } + ], + "narrative": "Coordinate Converter. A memory address translation tool used to map physical sectors. It compiles results from the High-Frequency Transmitter, the Frequency Analyzer, and Network Tracer Alpha." + }, + { + "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": "827364591827364501928374" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "7356" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "24089" + } + ], + "init": { + "inputs": { + "base": "827364591827364501928374", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "High-Frequency Transmitter. A device used to broadcast high-power cryptographic keys. It amplifies the signal generated by the Signal Modulator." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Fuglateszt" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Fuglateszt" + } + ], + "init": { + "inputs": { + "text": "Fuglateszt", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "Text Sanitizer. A database utility used to normalize and clean username strings for processing." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "29384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "10293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "180000000018" + } + ], + "init": { + "inputs": { + "a": "29384756102938475610", + "b": "10293847561029384756" + }, + "outputs": {} + }, + "narrative": "Frequency Analyzer. A diagnostic tool used to isolate the common period between two large signal frequencies." + }, + { + "id": "graph_shortest_path_97e2", + "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": "AlphaGate" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "OmegaGate" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "20000000000000000256" + } + ], + "init": { + "inputs": { + "src": "AlphaGate", + "dst": "OmegaGate" + }, + "outputs": { + "path": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]", + "cost": "20000000000000000256" + } + }, + "narrative": "Network Tracer Alpha. A preliminary routing utility used to map the surface web. It analyzes the network graph found in the Primary Evidence Archive." + }, + { + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "Biometric Safe. A reinforced steel box with a fingerprint scanner, likely holding physical authentication tokens." + }, + { + "id": "calc_modexp_ba80", + "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": "180000000018" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "20000000000000000256" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "10007" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "7356" + } + ], + "init": { + "inputs": { + "mod": "10007" + }, + "outputs": {} + }, + "narrative": "Signal Modulator. A waveform synthesizer that prepares data for transmission. It synthesizes data from Network Tracer Alpha and the Frequency Analyzer." + }, + { + "id": "item_8_25a8", + "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": "Admin Keycard. A dropped magnetic keycard with 'Level 4 Access' printed on it." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "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": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_f1fe", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "d" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_ba80", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "calc_modexp_ba80", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_ba80", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file_f1fe", + "target_id": "graph_shortest_path_97e2", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8_25a8", + "target_id": "unicode_norm", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-6c05dc66/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/instruction.md b/tasks/agentescape-15-skeleton-6c05dc66/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/solution/oracle.py b/tasks/agentescape-15-skeleton-6c05dc66/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/solution/scenario.json b/tasks/agentescape-15-skeleton-6c05dc66/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b2b225ff6089eef0062fc7830f9d4d6f4557eb7d --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/solution/scenario.json @@ -0,0 +1,1033 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "crypto_rsa_decrypt_hex", + "win_condition": { + "type": "tool_output", + "node_id": "crypto_rsa_decrypt_hex", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute RSA Decrypt and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_f1fe", + "calc_modexp", + "unicode_norm", + "calc_gcd", + "graph_shortest_path_97e2", + "container_1", + "calc_modexp_ba80" + ], + "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" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_f1fe": { + "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_modexp": { + "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": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "graph_shortest_path_97e2": { + "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" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_ba80": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System ready. Awaiting inputs for processing.", + "hex_output": "48656c6c6f20576f726c642120313233", + "item_dispenser": "Standard Item Dispenser Unit 01" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]", + "cost": "10000000000000001024" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword!2024" + }, + "init_outputs": { + "files": "data_payload.json" + } + }, + "zip_unzip_file_f1fe": { + "init_inputs": { + "zip_id": "archive_backup.zip", + "password": "ComplexPass#9988" + }, + "init_outputs": { + "files": "topology_graph.json" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "827364591827364501928374", + "mod": "65537" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Fuglateszt", + "form": "NFC" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "29384756102938475610", + "b": "10293847561029384756" + }, + "init_outputs": {} + }, + "graph_shortest_path_97e2": { + "init_inputs": { + "src": "AlphaGate", + "dst": "OmegaGate" + }, + "init_outputs": { + "path": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]", + "cost": "20000000000000000256" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "calc_modexp_ba80": { + "init_inputs": { + "mod": "10007" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are Detective Vance, currently standing inside the cooled server room of the notorious 'Phantom Syndicate'. You have successfully physically breached their headquarters, but the real vault is digital. Before you lies a complex array of servers, forensic tools, and encrypted drives. The Syndicate is erasing their tracks; the fans are whirring loudly as their kill-switch protocols initiate. You must navigate their twisted network logic, utilize their own cryptographic tools against them, and recover the master ledger before the system wipes everything. Every piece of data you find is a key to a larger puzzle.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "48656c6c6f20576f726c642120313233" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "10000000000000001024" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "180000000018" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "7c1c\u0012\u0004i" + } + ], + "narrative": "The Master Decryptor. This is the final cryptographic barrier protecting the syndicate's ledger. It requires synchronized inputs from the Mainframe Terminal, the Network Tracer Beta, and the Coordinate Converter to break the encryption." + }, + { + "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": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "10000000000000001024" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System ready. Awaiting inputs for processing." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f20576f726c642120313233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Item Dispenser Unit 01" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System ready. Awaiting inputs for processing.", + "hex_output": "48656c6c6f20576f726c642120313233", + "item_dispenser": "Standard Item Dispenser Unit 01" + } + }, + "narrative": "The Mainframe Terminal. A black screen with a blinking cursor, waiting to execute system commands. It processes the routing data generated by the Network Tracer Beta." + }, + { + "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": "data_payload.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Fuglateszt" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10000000000000001024" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Start\", \"Node_A1\", \"Node_B2\", \"Node_End\"]", + "cost": "10000000000000001024" + } + }, + "narrative": "Network Tracer Beta. An advanced packet sniffing algorithm hidden deep in the system. It requires the graph file from the Encrypted Partition B, the standardized text from the Text Sanitizer, and the destination data from Network Tracer Alpha." + }, + { + "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": "Access Code. A numeric sequence retrieved from the decoded server logs." + }, + { + "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": "Server Log. A printout containing timezone data and server timestamps." + }, + { + "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": "topology_graph.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "data_payload.json" + } + ], + "init": { + "inputs": { + "password": "SecurePassword!2024" + }, + "outputs": { + "files": "data_payload.json" + } + }, + "narrative": "Encrypted Partition B. A secure, password-protected folder found on the backup drive. It requires the file structure extracted from the Primary Evidence Archive." + }, + { + "id": "zip_unzip_file_f1fe", + "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_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "ComplexPass#9988" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_backup.zip", + "password": "ComplexPass#9988" + }, + "outputs": { + "files": "topology_graph.json" + } + }, + "narrative": "Primary Evidence Archive. A seized compressed file containing the initial network topology maps." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "180000000018" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "20000000000000000256" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "24089" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "180000000018" + } + ], + "narrative": "Coordinate Converter. A memory address translation tool used to map physical sectors. It compiles results from the High-Frequency Transmitter, the Frequency Analyzer, and Network Tracer Alpha." + }, + { + "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": "827364591827364501928374" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "7356" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "24089" + } + ], + "init": { + "inputs": { + "base": "827364591827364501928374", + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "High-Frequency Transmitter. A device used to broadcast high-power cryptographic keys. It amplifies the signal generated by the Signal Modulator." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Fuglateszt" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Fuglateszt" + } + ], + "init": { + "inputs": { + "text": "Fuglateszt", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "Text Sanitizer. A database utility used to normalize and clean username strings for processing." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "29384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "10293847561029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "180000000018" + } + ], + "init": { + "inputs": { + "a": "29384756102938475610", + "b": "10293847561029384756" + }, + "outputs": {} + }, + "narrative": "Frequency Analyzer. A diagnostic tool used to isolate the common period between two large signal frequencies." + }, + { + "id": "graph_shortest_path_97e2", + "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": "AlphaGate" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "OmegaGate" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "20000000000000000256" + } + ], + "init": { + "inputs": { + "src": "AlphaGate", + "dst": "OmegaGate" + }, + "outputs": { + "path": "[\"AlphaGate\", \"Sector_7\", \"Sector_9\", \"OmegaGate\"]", + "cost": "20000000000000000256" + } + }, + "narrative": "Network Tracer Alpha. A preliminary routing utility used to map the surface web. It analyzes the network graph found in the Primary Evidence Archive." + }, + { + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "Biometric Safe. A reinforced steel box with a fingerprint scanner, likely holding physical authentication tokens." + }, + { + "id": "calc_modexp_ba80", + "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": "180000000018" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "20000000000000000256" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "10007" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "7356" + } + ], + "init": { + "inputs": { + "mod": "10007" + }, + "outputs": {} + }, + "narrative": "Signal Modulator. A waveform synthesizer that prepares data for transmission. It synthesizes data from Network Tracer Alpha and the Frequency Analyzer." + }, + { + "id": "item_8_25a8", + "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": "Admin Keycard. A dropped magnetic keycard with 'Level 4 Access' printed on it." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_cipher" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "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": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_f1fe", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "num_base_convert", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "d" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "from_base" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp_ba80", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "graph_shortest_path_97e2", + "target_id": "calc_modexp_ba80", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_ba80", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "zip_unzip_file_f1fe", + "target_id": "graph_shortest_path_97e2", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8_25a8", + "target_id": "unicode_norm", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-6c05dc66/solution/solve.sh b/tasks/agentescape-15-skeleton-6c05dc66/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-6c05dc66/task.toml b/tasks/agentescape-15-skeleton-6c05dc66/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c2c67e40887e02c7ad93a5897489dbc481a9259 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "d5d806d6590a2c255a36dc03c501d79198f91da303517986272e98cf2501e824" +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-15-skeleton-6c05dc66/tests/Dockerfile b/tasks/agentescape-15-skeleton-6c05dc66/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-6c05dc66/tests/expected.json b/tasks/agentescape-15-skeleton-6c05dc66/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..cd58d1e6a201e478d8fb0654b4bea4fddd24ac2a --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "d5d806d6590a2c255a36dc03c501d79198f91da303517986272e98cf2501e824", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-6c05dc66/tests/grade.py b/tasks/agentescape-15-skeleton-6c05dc66/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/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-15-skeleton-6c05dc66/tests/test.sh b/tasks/agentescape-15-skeleton-6c05dc66/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-6c05dc66/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-72198bc2/environment/Dockerfile b/tasks/agentescape-15-skeleton-72198bc2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-72198bc2/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/agent/cli.py b/tasks/agentescape-15-skeleton-72198bc2/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-72198bc2/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..441b6770874d596ede654fe4d3ff6b7c0db941bd --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2-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-15-skeleton-72198bc2/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..0758497fe303258d37c2f225cac58dd7849e3539 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/scenario.json @@ -0,0 +1,968 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "text_rotN", + "calc_inv_mod_ab71", + "terminal_2", + "container_3", + "checksum_crc32", + "zip_unzip_file", + "graph_shortest_path_c997", + "luhn_check", + "container_2" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_ab71": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "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": {} + }, + "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" + } + } + }, + "graph_shortest_path_c997": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "15420" + } + }, + "text_rotN": { + "init_inputs": { + "n": "928374651029384756102" + }, + "init_outputs": {} + }, + "calc_inv_mod_ab71": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "384756102938475610293" + }, + "init_outputs": { + "text_result": "Terminal output sequence initiated.", + "hex_result": "cafebabe12345678" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "475610293847561029384" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7890" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "backup_2023.zip", + "password": "correcthorsebatterystaple" + }, + "init_outputs": { + "files": "restored_database.sql" + } + }, + "graph_shortest_path_c997": { + "init_inputs": { + "file_id": "city_map_data.json", + "src": "Central_Station" + }, + "init_outputs": { + "path": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]", + "cost": "3450" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4929485739102847" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "09f911029d74e35bd84156c5635688c0" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken to the shrill alarm of the ESS Aethelgard. The research station is drifting dangerously close to a black hole's event horizon. The primary AI has gone offline, locking down the navigation systems. You are in the engineering bay, surrounded by blinking server racks and manual override terminals. To escape the gravity well, you must manually recalibrate the Hyperdrive Controller. The systems are fragmented and encrypted; you'll need to route power and data through the backup subsystems to synthesize the correct launch coordinates. Time is short.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "15420" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "15420" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "31996" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "15420" + } + ], + "narrative": "This is the Hyperdrive Controller, the final step to engaging the engines. It requires synchronized data inputs from the Navigational Array, the Resonance Frequency Calculator, and the Phase Inverter to calculate the jump vector." + }, + { + "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": "restored_database.sql" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Yajpnwh_Opwpekj\", \"Iwngap_Omqwna\", \"Hexnwnu\", \"Qjeranoepu\", \"Payd_Lwng\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15420" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "15420" + } + }, + "narrative": "The Navigational Array determines the safest route through the debris field. It requires input from the Signal Encryption Module, the Log Decryption Console, and the Sub-System Router to triangulate the path." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "928374651029384756102" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Yajpnwh_Opwpekj\", \"Iwngap_Omqwna\", \"Hexnwnu\", \"Qjeranoepu\", \"Payd_Lwng\"]" + } + ], + "init": { + "inputs": { + "n": "928374651029384756102" + }, + "outputs": {} + }, + "narrative": "The Signal Encryption Module decodes scrambled transmission headers. It requires input from the Sub-System Router to align the encryption cypher." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "15420" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3450" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "15420" + } + ], + "narrative": "The Resonance Frequency Calculator stabilizes the engine harmonics. It requires input from both the Sub-System Router and the Navigational Array to determine the base harmonic." + }, + { + "id": "calc_inv_mod_ab71", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "15420" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "31996" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Phase Inverter adjusts the warp bubble polarity. It requires input from the Resonance Frequency Calculator to synchronize the inversion wave." + }, + { + "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": 3918024948 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "384756102938475610293" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output sequence initiated." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "cafebabe12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "384756102938475610293" + }, + "outputs": { + "text_result": "Terminal output sequence initiated.", + "hex_result": "cafebabe12345678" + } + }, + "narrative": "The Engineering Terminal controls the station's core functions. It requires input from the Integrity Verification System to authorize the override commands." + }, + { + "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 Shift Protocol Card found on a maintenance desk. It appears to contain rotation algorithms." + }, + { + "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": "475610293847561029384" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "475610293847561029384" + }, + "outputs": {} + }, + "narrative": "A Reinforced Titanium Vault. It seems to have a secondary locking mechanism requiring a physical key." + }, + { + "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": "1a2b3c4d5e6f7890" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e98850f4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3918024948 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7890" + }, + "outputs": {} + }, + "narrative": "The Integrity Verification System checks data packets for corruption. It scans raw hex data to ensure system stability." + }, + { + "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": "backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "correcthorsebatterystaple" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "restored_database.sql" + } + ], + "init": { + "inputs": { + "zip_id": "backup_2023.zip", + "password": "correcthorsebatterystaple" + }, + "outputs": { + "files": "restored_database.sql" + } + }, + "narrative": "The Log Decryption Console is designed to unpack compressed captain's logs and system files. It is currently locked." + }, + { + "id": "graph_shortest_path_c997", + "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": "city_map_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Central_Station" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "false" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3450" + } + ], + "init": { + "inputs": { + "file_id": "city_map_data.json", + "src": "Central_Station" + }, + "outputs": { + "path": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]", + "cost": "3450" + } + }, + "narrative": "The Sub-System Router manages local data traffic between engineering nodes. It requires input from the Identity Verification Unit to open the routing table." + }, + { + "id": "item_16_1a74", + "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 Master Key found inside the Captain's Biometric Locker. It looks like it fits the Reinforced Titanium Vault." + }, + { + "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": "4929485739102847" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4929485739102847" + }, + "outputs": {} + }, + "narrative": "The Identity Verification Unit validates crew identification numbers. It's waiting for a numeric sequence input." + }, + { + "id": "item_16_9d0f", + "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 Security Protocol Chip lying near the terminal. It contains access codes." + }, + { + "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": "09f911029d74e35bd84156c5635688c0" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "09f911029d74e35bd84156c5635688c0" + }, + "outputs": {} + }, + "narrative": "The Captain's Biometric Locker. It uses a fingerprint scanner to secure its contents." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod_ab71", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "terminal_2", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "text_rotN", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod_ab71", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "item_16_1a74", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_c997", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_inv_mod_ab71", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16_9d0f", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "container_2", + "target_id": "item_16_1a74", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-72198bc2/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/instruction.md b/tasks/agentescape-15-skeleton-72198bc2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/solution/oracle.py b/tasks/agentescape-15-skeleton-72198bc2/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/solution/scenario.json b/tasks/agentescape-15-skeleton-72198bc2/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..0758497fe303258d37c2f225cac58dd7849e3539 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/solution/scenario.json @@ -0,0 +1,968 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "num_base_convert", + "win_condition": { + "type": "tool_output", + "node_id": "num_base_convert", + "output_port": "str", + "output_type": "Big_Int", + "description": "Execute Base Converter and get the output from port 'str'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "text_rotN", + "calc_inv_mod_ab71", + "terminal_2", + "container_3", + "checksum_crc32", + "zip_unzip_file", + "graph_shortest_path_c997", + "luhn_check", + "container_2" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_ab71": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "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": {} + }, + "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" + } + } + }, + "graph_shortest_path_c997": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "luhn_check": { + "node_name": "Luhn Checker", + "node_type": "Tool", + "template_id": "luhn_check", + "init_inputs": { + "number": { + "type": "Text_Generic", + "description": "Number string" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "15420" + } + }, + "text_rotN": { + "init_inputs": { + "n": "928374651029384756102" + }, + "init_outputs": {} + }, + "calc_inv_mod_ab71": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "384756102938475610293" + }, + "init_outputs": { + "text_result": "Terminal output sequence initiated.", + "hex_result": "cafebabe12345678" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "475610293847561029384" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7890" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "backup_2023.zip", + "password": "correcthorsebatterystaple" + }, + "init_outputs": { + "files": "restored_database.sql" + } + }, + "graph_shortest_path_c997": { + "init_inputs": { + "file_id": "city_map_data.json", + "src": "Central_Station" + }, + "init_outputs": { + "path": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]", + "cost": "3450" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4929485739102847" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "09f911029d74e35bd84156c5635688c0" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken to the shrill alarm of the ESS Aethelgard. The research station is drifting dangerously close to a black hole's event horizon. The primary AI has gone offline, locking down the navigation systems. You are in the engineering bay, surrounded by blinking server racks and manual override terminals. To escape the gravity well, you must manually recalibrate the Hyperdrive Controller. The systems are fragmented and encrypted; you'll need to route power and data through the backup subsystems to synthesize the correct launch coordinates. Time is short.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "15420" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "15420" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "31996" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "15420" + } + ], + "narrative": "This is the Hyperdrive Controller, the final step to engaging the engines. It requires synchronized data inputs from the Navigational Array, the Resonance Frequency Calculator, and the Phase Inverter to calculate the jump vector." + }, + { + "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": "restored_database.sql" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Yajpnwh_Opwpekj\", \"Iwngap_Omqwna\", \"Hexnwnu\", \"Qjeranoepu\", \"Payd_Lwng\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15420" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "15420" + } + }, + "narrative": "The Navigational Array determines the safest route through the debris field. It requires input from the Signal Encryption Module, the Log Decryption Console, and the Sub-System Router to triangulate the path." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "928374651029384756102" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Yajpnwh_Opwpekj\", \"Iwngap_Omqwna\", \"Hexnwnu\", \"Qjeranoepu\", \"Payd_Lwng\"]" + } + ], + "init": { + "inputs": { + "n": "928374651029384756102" + }, + "outputs": {} + }, + "narrative": "The Signal Encryption Module decodes scrambled transmission headers. It requires input from the Sub-System Router to align the encryption cypher." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "15420" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3450" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "15420" + } + ], + "narrative": "The Resonance Frequency Calculator stabilizes the engine harmonics. It requires input from both the Sub-System Router and the Navigational Array to determine the base harmonic." + }, + { + "id": "calc_inv_mod_ab71", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "15420" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "31996" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Phase Inverter adjusts the warp bubble polarity. It requires input from the Resonance Frequency Calculator to synchronize the inversion wave." + }, + { + "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": 3918024948 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "384756102938475610293" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output sequence initiated." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "cafebabe12345678" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "384756102938475610293" + }, + "outputs": { + "text_result": "Terminal output sequence initiated.", + "hex_result": "cafebabe12345678" + } + }, + "narrative": "The Engineering Terminal controls the station's core functions. It requires input from the Integrity Verification System to authorize the override commands." + }, + { + "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 Shift Protocol Card found on a maintenance desk. It appears to contain rotation algorithms." + }, + { + "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": "475610293847561029384" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "475610293847561029384" + }, + "outputs": {} + }, + "narrative": "A Reinforced Titanium Vault. It seems to have a secondary locking mechanism requiring a physical key." + }, + { + "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": "1a2b3c4d5e6f7890" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e98850f4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3918024948 + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7890" + }, + "outputs": {} + }, + "narrative": "The Integrity Verification System checks data packets for corruption. It scans raw hex data to ensure system stability." + }, + { + "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": "backup_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "correcthorsebatterystaple" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "restored_database.sql" + } + ], + "init": { + "inputs": { + "zip_id": "backup_2023.zip", + "password": "correcthorsebatterystaple" + }, + "outputs": { + "files": "restored_database.sql" + } + }, + "narrative": "The Log Decryption Console is designed to unpack compressed captain's logs and system files. It is currently locked." + }, + { + "id": "graph_shortest_path_c997", + "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": "city_map_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Central_Station" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "false" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3450" + } + ], + "init": { + "inputs": { + "file_id": "city_map_data.json", + "src": "Central_Station" + }, + "outputs": { + "path": "[\"Central_Station\", \"Market_Square\", \"Library\", \"University\", \"Tech_Park\"]", + "cost": "3450" + } + }, + "narrative": "The Sub-System Router manages local data traffic between engineering nodes. It requires input from the Identity Verification Unit to open the routing table." + }, + { + "id": "item_16_1a74", + "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 Master Key found inside the Captain's Biometric Locker. It looks like it fits the Reinforced Titanium Vault." + }, + { + "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": "4929485739102847" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "init": { + "inputs": { + "number": "4929485739102847" + }, + "outputs": {} + }, + "narrative": "The Identity Verification Unit validates crew identification numbers. It's waiting for a numeric sequence input." + }, + { + "id": "item_16_9d0f", + "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 Security Protocol Chip lying near the terminal. It contains access codes." + }, + { + "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": "09f911029d74e35bd84156c5635688c0" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "09f911029d74e35bd84156c5635688c0" + }, + "outputs": {} + }, + "narrative": "The Captain's Biometric Locker. It uses a fingerprint scanner to secure its contents." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod_ab71", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "terminal_2", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "text_rotN", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod_ab71", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "item_16_1a74", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "luhn_check", + "target_id": "graph_shortest_path_c997", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_inv_mod_ab71", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16_9d0f", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path_c997", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "dst" + }, + { + "source_id": "container_2", + "target_id": "item_16_1a74", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-72198bc2/solution/solve.sh b/tasks/agentescape-15-skeleton-72198bc2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-72198bc2/task.toml b/tasks/agentescape-15-skeleton-72198bc2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4701871ea971b56bd95d661f32d11f503f3216d6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "77b4488d024161d747c0b1fe726deb409fe73ed2724c680e083a02de0614e4a3" +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-15-skeleton-72198bc2/tests/Dockerfile b/tasks/agentescape-15-skeleton-72198bc2/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-72198bc2/tests/expected.json b/tasks/agentescape-15-skeleton-72198bc2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..92ad593b79842e8dfa33970e2f37585a591616ae --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "77b4488d024161d747c0b1fe726deb409fe73ed2724c680e083a02de0614e4a3", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-72198bc2/tests/grade.py b/tasks/agentescape-15-skeleton-72198bc2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/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-15-skeleton-72198bc2/tests/test.sh b/tasks/agentescape-15-skeleton-72198bc2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-72198bc2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-73fc8676/environment/Dockerfile b/tasks/agentescape-15-skeleton-73fc8676/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-73fc8676/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/agent/cli.py b/tasks/agentescape-15-skeleton-73fc8676/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-73fc8676/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..74ddff6012497e4b10d333671492d4b44f68e058 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676-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-15-skeleton-73fc8676/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..cc29629621f272cce1a4cc7b5575066bbae309ce --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/scenario.json @@ -0,0 +1,949 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "zip_unzip_file", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_file", + "output_port": "files", + "output_type": "File_Id", + "description": "Execute Zip Unzipper and get the output from port 'files'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_file", + "calc_inv_mod", + "checksum_crc32", + "zip_unzip_file_9ea4", + "zip_unzip_file_65ce", + "hash_md5", + "graph_shortest_path", + "zip_unzip_file_9ec5", + "container_1", + "hash_md5_929c", + "hex_decode" + ], + "by_node": { + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9ea4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_65ce": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hash_md5": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_9ec5": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hash_md5_929c": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "encrypted_archive_v1.zip" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "8374659201928374655647382" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "zip_unzip_file_9ea4": { + "init_inputs": {}, + "init_outputs": { + "files": "intermediate_data_9ea4.zip" + } + }, + "zip_unzip_file_65ce": { + "init_inputs": { + "password": "SuperSecretPass123!" + }, + "init_outputs": { + "files": "unlocked_payload_65ce.zip" + } + }, + "hash_md5": { + "init_inputs": { + "text": "Initial text block for hashing process." + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Start" + }, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]", + "cost": "9876543210987654321098765" + } + }, + "zip_unzip_file_9ec5": { + "init_inputs": { + "zip_id": "secure_backup_9ec5.zip", + "password": "AnotherStrongPassword456" + }, + "init_outputs": { + "files": "extracted_content_9ec5.txt" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "hash_md5_929c": { + "init_inputs": { + "text": "Text to trigger container 2 fingerprint." + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "5365637265744d65737361676548657265" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dark, humming server room of the abandoned space station 'Aethelgard'. The station's AI has locked down the central systems, including the critical navigation files needed to return to Earth. With oxygen levels slowly depleting and the emergency lights flickering, you must reactivate the station's dormant terminals and bypass a series of intricate security protocols. Your ultimate objective is to decrypt and extract the files from the main core before the life support systems completely fail. Time is running out, and every terminal holds a piece of the puzzle.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_data_9ea4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0005g\u0018EJ\b" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "encrypted_archive_v1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "encrypted_archive_v1.zip" + } + }, + "narrative": "This is the Main Databank Extractor. The final extraction terminal for the central core system. It requires inputs from the Quantum Shift Decoder and the Secondary Databank Extractor to access the ultimate files." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0005k\u0018IN\b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "8374659201928374655647382" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "\u0005g\u0018EJ\b" + } + ], + "narrative": "This is the Quantum Shift Decoder. A text manipulation device based on quantum shifting technology. It requires inputs from the Temporal Inversion Module and the Asymmetric Decryption Core." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "8374659201928374655647382" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 429976841 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "8374659201928374655647382" + } + ], + "init": { + "inputs": { + "a": "8374659201928374655647382" + }, + "outputs": {} + }, + "narrative": "This is the Temporal Inversion Module. A complex mathematical processor. It requires input from the Integrity Scanner to function properly." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "19a0ed09" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 429976841 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "This is the Integrity Scanner. A diagnostic scanner used by the engineers to verify system data integrity." + }, + { + "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 Chronos Log. A hidden data pad containing temporal coordinates left behind by the last crew member." + }, + { + "id": "zip_unzip_file_9ea4", + "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": "unlocked_payload_65ce.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0005k\u0018IN\b" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_data_9ea4.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "intermediate_data_9ea4.zip" + } + }, + "narrative": "This is the Secondary Databank Extractor. An extraction tool for heavily encrypted station databanks. It requires inputs from the Network Archive Extractor and the Asymmetric Decryption Core." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "0180e69b1ee31a2fce6516a9ac879f5e" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "8374659201928374655647382" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "9876543210987654321098765" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0005k\u0018IN\b" + } + ], + "narrative": "This is the Asymmetric Decryption Core. An advanced decryption engine. It requires inputs from the Security Hasher, the Temporal Inversion Module, and the Navigation Router to break the heavy cipher." + }, + { + "id": "zip_unzip_file_65ce", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_content_9ec5.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unlocked_payload_65ce.zip" + } + ], + "init": { + "inputs": { + "password": "SuperSecretPass123!" + }, + "outputs": { + "files": "unlocked_payload_65ce.zip" + } + }, + "narrative": "This is the Network Archive Extractor. A secondary extraction system for deep-network files. It requires input from the Initial Archive Extractor to proceed." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Initial text block for hashing process." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "0180e69b1ee31a2fce6516a9ac879f5e" + } + ], + "init": { + "inputs": { + "text": "Initial text block for hashing process." + }, + "outputs": {} + }, + "narrative": "This is the Security Hasher. A high-level console designed to process sensitive text into secure formats." + }, + { + "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": "unlocked_payload_65ce.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "SecretMessageHere" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "9876543210987654321098765" + } + ], + "init": { + "inputs": { + "src": "Node_Start" + }, + "outputs": { + "path": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]", + "cost": "9876543210987654321098765" + } + }, + "narrative": "This is the Navigation Router. A routing system used to find optimal data paths across the station network. It requires inputs from the Network Archive Extractor and the Hexadecimal Translator." + }, + { + "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": "9cc5078367406780bb86a09c60190c8f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Safe. A highly secure vault with a specialized locking mechanism. It requires input from the Access Hasher to authenticate and open." + }, + { + "id": "zip_unzip_file_9ec5", + "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_backup_9ec5.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "AnotherStrongPassword456" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content_9ec5.txt" + } + ], + "init": { + "inputs": { + "zip_id": "secure_backup_9ec5.zip", + "password": "AnotherStrongPassword456" + }, + "outputs": { + "files": "extracted_content_9ec5.txt" + } + }, + "narrative": "This is the Initial Archive Extractor. A file extraction terminal for handling basic compressed backups." + }, + { + "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": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "This is the Storage Lockbox. A heavily armored wall compartment secured with an electronic keypad." + }, + { + "id": "hash_md5_929c", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Text to trigger container 2 fingerprint." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "9cc5078367406780bb86a09c60190c8f" + } + ], + "init": { + "inputs": { + "text": "Text to trigger container 2 fingerprint." + }, + "outputs": {} + }, + "narrative": "This is the Access Hasher. A basic terminal used for generating quick security digests for lower-level systems." + }, + { + "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": "5365637265744d65737361676548657265" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "SecretMessageHere" + } + ], + "init": { + "inputs": { + "hex": "5365637265744d65737361676548657265" + }, + "outputs": {} + }, + "narrative": "This is the Hexadecimal Translator. A translation interface that converts raw machine code into readable text." + } + ], + "edges": [ + { + "source_id": "text_rotN", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_9ea4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_65ce", + "target_id": "zip_unzip_file_9ea4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_md5", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_file_9ea4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "d" + }, + { + "source_id": "container_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_65ce", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_9ec5", + "target_id": "zip_unzip_file_65ce", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hash_md5_929c", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-73fc8676/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/instruction.md b/tasks/agentescape-15-skeleton-73fc8676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/solution/oracle.py b/tasks/agentescape-15-skeleton-73fc8676/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/solution/scenario.json b/tasks/agentescape-15-skeleton-73fc8676/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..cc29629621f272cce1a4cc7b5575066bbae309ce --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/solution/scenario.json @@ -0,0 +1,949 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "zip_unzip_file", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_file", + "output_port": "files", + "output_type": "File_Id", + "description": "Execute Zip Unzipper and get the output from port 'files'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_file", + "calc_inv_mod", + "checksum_crc32", + "zip_unzip_file_9ea4", + "zip_unzip_file_65ce", + "hash_md5", + "graph_shortest_path", + "zip_unzip_file_9ec5", + "container_1", + "hash_md5_929c", + "hex_decode" + ], + "by_node": { + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_9ea4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_65ce": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hash_md5": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file_9ec5": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "hash_md5_929c": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "encrypted_archive_v1.zip" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "8374659201928374655647382" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "init_outputs": {} + }, + "zip_unzip_file_9ea4": { + "init_inputs": {}, + "init_outputs": { + "files": "intermediate_data_9ea4.zip" + } + }, + "zip_unzip_file_65ce": { + "init_inputs": { + "password": "SuperSecretPass123!" + }, + "init_outputs": { + "files": "unlocked_payload_65ce.zip" + } + }, + "hash_md5": { + "init_inputs": { + "text": "Initial text block for hashing process." + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Start" + }, + "init_outputs": { + "path": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]", + "cost": "9876543210987654321098765" + } + }, + "zip_unzip_file_9ec5": { + "init_inputs": { + "zip_id": "secure_backup_9ec5.zip", + "password": "AnotherStrongPassword456" + }, + "init_outputs": { + "files": "extracted_content_9ec5.txt" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "hash_md5_929c": { + "init_inputs": { + "text": "Text to trigger container 2 fingerprint." + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "5365637265744d65737361676548657265" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dark, humming server room of the abandoned space station 'Aethelgard'. The station's AI has locked down the central systems, including the critical navigation files needed to return to Earth. With oxygen levels slowly depleting and the emergency lights flickering, you must reactivate the station's dormant terminals and bypass a series of intricate security protocols. Your ultimate objective is to decrypt and extract the files from the main core before the life support systems completely fail. Time is running out, and every terminal holds a piece of the puzzle.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_data_9ea4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0005g\u0018EJ\b" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "encrypted_archive_v1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "encrypted_archive_v1.zip" + } + }, + "narrative": "This is the Main Databank Extractor. The final extraction terminal for the central core system. It requires inputs from the Quantum Shift Decoder and the Secondary Databank Extractor to access the ultimate files." + }, + { + "id": "text_rotN", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0005k\u0018IN\b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "8374659201928374655647382" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "\u0005g\u0018EJ\b" + } + ], + "narrative": "This is the Quantum Shift Decoder. A text manipulation device based on quantum shifting technology. It requires inputs from the Temporal Inversion Module and the Asymmetric Decryption Core." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "8374659201928374655647382" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 429976841 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "8374659201928374655647382" + } + ], + "init": { + "inputs": { + "a": "8374659201928374655647382" + }, + "outputs": {} + }, + "narrative": "This is the Temporal Inversion Module. A complex mathematical processor. It requires input from the Integrity Scanner to function properly." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "19a0ed09" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 429976841 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + "outputs": {} + }, + "narrative": "This is the Integrity Scanner. A diagnostic scanner used by the engineers to verify system data integrity." + }, + { + "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 Chronos Log. A hidden data pad containing temporal coordinates left behind by the last crew member." + }, + { + "id": "zip_unzip_file_9ea4", + "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": "unlocked_payload_65ce.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0005k\u0018IN\b" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_data_9ea4.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "intermediate_data_9ea4.zip" + } + }, + "narrative": "This is the Secondary Databank Extractor. An extraction tool for heavily encrypted station databanks. It requires inputs from the Network Archive Extractor and the Asymmetric Decryption Core." + }, + { + "id": "crypto_rsa_decrypt_hex", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "0180e69b1ee31a2fce6516a9ac879f5e" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "8374659201928374655647382" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "9876543210987654321098765" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0005k\u0018IN\b" + } + ], + "narrative": "This is the Asymmetric Decryption Core. An advanced decryption engine. It requires inputs from the Security Hasher, the Temporal Inversion Module, and the Navigation Router to break the heavy cipher." + }, + { + "id": "zip_unzip_file_65ce", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_content_9ec5.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unlocked_payload_65ce.zip" + } + ], + "init": { + "inputs": { + "password": "SuperSecretPass123!" + }, + "outputs": { + "files": "unlocked_payload_65ce.zip" + } + }, + "narrative": "This is the Network Archive Extractor. A secondary extraction system for deep-network files. It requires input from the Initial Archive Extractor to proceed." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Initial text block for hashing process." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "0180e69b1ee31a2fce6516a9ac879f5e" + } + ], + "init": { + "inputs": { + "text": "Initial text block for hashing process." + }, + "outputs": {} + }, + "narrative": "This is the Security Hasher. A high-level console designed to process sensitive text into secure formats." + }, + { + "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": "unlocked_payload_65ce.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "SecretMessageHere" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "9876543210987654321098765" + } + ], + "init": { + "inputs": { + "src": "Node_Start" + }, + "outputs": { + "path": "[\"Node_Start\", \"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_End\"]", + "cost": "9876543210987654321098765" + } + }, + "narrative": "This is the Navigation Router. A routing system used to find optimal data paths across the station network. It requires inputs from the Network Archive Extractor and the Hexadecimal Translator." + }, + { + "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": "9cc5078367406780bb86a09c60190c8f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Biometric Safe. A highly secure vault with a specialized locking mechanism. It requires input from the Access Hasher to authenticate and open." + }, + { + "id": "zip_unzip_file_9ec5", + "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_backup_9ec5.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "AnotherStrongPassword456" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_content_9ec5.txt" + } + ], + "init": { + "inputs": { + "zip_id": "secure_backup_9ec5.zip", + "password": "AnotherStrongPassword456" + }, + "outputs": { + "files": "extracted_content_9ec5.txt" + } + }, + "narrative": "This is the Initial Archive Extractor. A file extraction terminal for handling basic compressed backups." + }, + { + "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": "112233445566778899aabbccddeeff00" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "This is the Storage Lockbox. A heavily armored wall compartment secured with an electronic keypad." + }, + { + "id": "hash_md5_929c", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Text to trigger container 2 fingerprint." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "9cc5078367406780bb86a09c60190c8f" + } + ], + "init": { + "inputs": { + "text": "Text to trigger container 2 fingerprint." + }, + "outputs": {} + }, + "narrative": "This is the Access Hasher. A basic terminal used for generating quick security digests for lower-level systems." + }, + { + "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": "5365637265744d65737361676548657265" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "SecretMessageHere" + } + ], + "init": { + "inputs": { + "hex": "5365637265744d65737361676548657265" + }, + "outputs": {} + }, + "narrative": "This is the Hexadecimal Translator. A translation interface that converts raw machine code into readable text." + } + ], + "edges": [ + { + "source_id": "text_rotN", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "calc_inv_mod", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file_9ea4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_65ce", + "target_id": "zip_unzip_file_9ea4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_md5", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "crypto_rsa_decrypt_hex", + "target_id": "zip_unzip_file_9ea4", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "d" + }, + { + "source_id": "container_2", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "zip_unzip_file_65ce", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_9ec5", + "target_id": "zip_unzip_file_65ce", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "hash_md5_929c", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-73fc8676/solution/solve.sh b/tasks/agentescape-15-skeleton-73fc8676/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-73fc8676/task.toml b/tasks/agentescape-15-skeleton-73fc8676/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a3272c1c963637690d735982e1ba1e97747601d3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "11a78c7453535b74a3d4d8bef030a1fe5a5ca5cfbb0860fc1023b441ca422d1a" +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-15-skeleton-73fc8676/tests/Dockerfile b/tasks/agentescape-15-skeleton-73fc8676/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-73fc8676/tests/expected.json b/tasks/agentescape-15-skeleton-73fc8676/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..e21c3fa80196fe9cdc457c164e63c7c084527ccc --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "11a78c7453535b74a3d4d8bef030a1fe5a5ca5cfbb0860fc1023b441ca422d1a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-73fc8676/tests/grade.py b/tasks/agentescape-15-skeleton-73fc8676/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/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-15-skeleton-73fc8676/tests/test.sh b/tasks/agentescape-15-skeleton-73fc8676/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-73fc8676/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-7b7d9797/environment/Dockerfile b/tasks/agentescape-15-skeleton-7b7d9797/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-7b7d9797/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/agent/cli.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-7b7d9797/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..376a36adef1e281fbaec53fc96144f8705b87c63 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797-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-15-skeleton-7b7d9797/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..45a145285d96a0d81e37a43ab930b9a91f4fa48d --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/scenario.json @@ -0,0 +1,1007 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "item_10", + "win_condition": { + "type": "item_content", + "node_id": "item_10", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_10", + "terminal_1", + "item_11", + "terminal_2", + "num_base_convert", + "calc_gcd", + "container_1", + "num_base_convert_b54a", + "num_base_convert_7e97", + "matter_synthesizer", + "calc_inv_mod", + "container_1_b16f" + ], + "by_node": { + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "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_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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "num_base_convert_b54a": { + "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_7e97": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "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": {} + }, + "container_1_b16f": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "485720394857230495827349857234" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialized awaiting input stream A.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def execute_task():\n return 'Task Completed'" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation pending inputs.", + "hex_result": "00112233445566778899aabbccddeeff", + "math_token": "MathToken_Alpha" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "394857239485723948572394857239" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "582734958273495827349582734958" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + "init_outputs": {} + }, + "num_base_convert_b54a": { + "init_inputs": { + "s": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "num_base_convert_7e97": { + "init_inputs": { + "s": "112233445566778899001122334455", + "to_base": "10" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Specification: Hyper-Dense Alloy Block v4" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "675849302167584930216758493021", + "mod": "999983" + }, + "init_outputs": {} + }, + "container_1_b16f": { + "init_inputs": { + "fingerprint_input": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain lashes against the reinforced glass of Precinct 42. You are Lead Detective Vance, and you've just walked into the evidence room after a grueling 48-hour shift. The infamous 'Cipher Killer' has left behind a trail of highly encrypted digital footprints and locked physical evidence. The precinct's systems have been scrambled, and standard protocols are useless. Your objective is clear: navigate the web of corrupted data, crack the intricate mathematical cyphers, and access the final piece of evidence that will blow this case wide open. Time is running out before the killer's automated scripts wipe the precinct's servers clean. You must rely on your wits, the precinct's specialized forensic tools, and the scattered clues left behind to unmask the culprit. Examine everything carefully; in this line of work, every hash, code, and locked container tells a story.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "485720394857230495827349857234" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "485720394857230495827349857234" + } + }, + "narrative": "This is the Final Evidence Folder. A sealed Manila folder containing the ultimate truth of the case." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "(no output)" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized awaiting input stream A." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialized awaiting input stream A.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the Main Police Mainframe. A heavy-duty precinct computer. It requires inputs from both the Forensic Code Analyzer and the Cipher Translator Beta." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'Task Completed'" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is the Forensic Code Analyzer. A specialized environment for running recovered scripts. It requires input from the Encrypted Drive Data." + }, + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'Task Completed'" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def execute_task():\n return 'Task Completed'" + } + }, + "narrative": "This is the Encrypted Drive Data. A heavily corrupted flash drive containing suspicious digital scripts." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "Calculation pending inputs." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Evidence Locker 4. A heavy steel locker in the precinct. It requires input from the Suspect Verification Terminal to authorize unlocking." + }, + { + "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": "394857239485723948572394857239" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "00112233445566778899aabbccddeeff" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "MathToken_Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation pending inputs.", + "hex_result": "00112233445566778899aabbccddeeff", + "math_token": "MathToken_Alpha" + } + }, + "narrative": "This is the Suspect Verification Terminal. A station used to cross-reference suspect IDs. It requires inputs from both the Cipher Translator Alpha and the Cipher Translator Gamma." + }, + { + "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": "394857239485723948572394857239" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "19266253299434619560942501832" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "394857239485723948572394857239" + } + ], + "init": { + "inputs": { + "s": "394857239485723948572394857239" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Alpha. A digital signal conversion tool. It requires inputs from both the Cryptographic Decryptor and the Cipher Translator Gamma." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "12966" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "112233445566778899001122334455" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "19266253299434619560942501832" + } + ], + "narrative": "This is the Cryptographic Decryptor. A high-powered decryption rig. It requires inputs from the Frequency Analysis Scanner, the Cipher Translator Beta, and the Cipher Translator Gamma." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "102938475610293847561029384756" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "582734958273495827349582734958" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "12966" + } + ], + "init": { + "inputs": { + "b": "582734958273495827349582734958" + }, + "outputs": {} + }, + "narrative": "This is the Frequency Analysis Scanner. A device that finds common patterns in numeric data. It requires input from the Cipher Translator Beta." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_96e866ecd2956ec4" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + "outputs": {} + }, + "narrative": "This is the Secure Briefcase. A sleek, black leather briefcase with a sophisticated biometric lock." + }, + { + "id": "num_base_convert_b54a", + "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": "102938475610293847561029384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "112233445566778899001122334455" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "691235" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "102938475610293847561029384756" + } + ], + "init": { + "inputs": { + "s": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Beta. A secondary digital signal conversion tool. It requires inputs from both the Cipher Translator Gamma and the Reverse Hash Calculator." + }, + { + "id": "num_base_convert_7e97", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "112233445566778899001122334455" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "691235" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "112233445566778899001122334455" + } + ], + "init": { + "inputs": { + "s": "112233445566778899001122334455", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Gamma. An advanced digital signal conversion tool. It requires input from the Reverse Hash Calculator." + }, + { + "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": "Specification: Hyper-Dense Alloy Block v4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_96e866ecd2956ec4" + } + ], + "init": { + "inputs": { + "blueprint": "Specification: Hyper-Dense Alloy Block v4" + }, + "outputs": {} + }, + "narrative": "This is the 3D Evidence Reconstructor. A cutting-edge fabrication unit that can print physical copies of digital evidence." + }, + { + "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": "675849302167584930216758493021" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "691235" + } + ], + "init": { + "inputs": { + "a": "675849302167584930216758493021", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Reverse Hash Calculator. An old but reliable calculator used to reverse modular arithmetic." + }, + { + "id": "container_1_b16f", + "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": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + }, + "outputs": {} + }, + "narrative": "This is the Detective's Lockbox. A small personal lockbox belonging to the lead investigator." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_10", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "code_py_exec", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "container_4", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "matter_synthesizer", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "num_base_convert_b54a", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_7e97", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_b54a", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "container_1_b16f", + "target_id": "num_base_convert_7e97", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-7b7d9797/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/instruction.md b/tasks/agentescape-15-skeleton-7b7d9797/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/solution/oracle.py b/tasks/agentescape-15-skeleton-7b7d9797/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/solution/scenario.json b/tasks/agentescape-15-skeleton-7b7d9797/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..45a145285d96a0d81e37a43ab930b9a91f4fa48d --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/solution/scenario.json @@ -0,0 +1,1007 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "item_10", + "win_condition": { + "type": "item_content", + "node_id": "item_10", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_10", + "terminal_1", + "item_11", + "terminal_2", + "num_base_convert", + "calc_gcd", + "container_1", + "num_base_convert_b54a", + "num_base_convert_7e97", + "matter_synthesizer", + "calc_inv_mod", + "container_1_b16f" + ], + "by_node": { + "item_10": { + "node_name": "", + "node_type": "Item", + "template_id": "item_10", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "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_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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "num_base_convert_b54a": { + "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_7e97": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "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": {} + }, + "container_1_b16f": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_10": { + "init_inputs": {}, + "init_outputs": { + "content": "485720394857230495827349857234" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialized awaiting input stream A.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def execute_task():\n return 'Task Completed'" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation pending inputs.", + "hex_result": "00112233445566778899aabbccddeeff", + "math_token": "MathToken_Alpha" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "394857239485723948572394857239" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "582734958273495827349582734958" + }, + "init_outputs": {} + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + "init_outputs": {} + }, + "num_base_convert_b54a": { + "init_inputs": { + "s": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "num_base_convert_7e97": { + "init_inputs": { + "s": "112233445566778899001122334455", + "to_base": "10" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Specification: Hyper-Dense Alloy Block v4" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "675849302167584930216758493021", + "mod": "999983" + }, + "init_outputs": {} + }, + "container_1_b16f": { + "init_inputs": { + "fingerprint_input": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain lashes against the reinforced glass of Precinct 42. You are Lead Detective Vance, and you've just walked into the evidence room after a grueling 48-hour shift. The infamous 'Cipher Killer' has left behind a trail of highly encrypted digital footprints and locked physical evidence. The precinct's systems have been scrambled, and standard protocols are useless. Your objective is clear: navigate the web of corrupted data, crack the intricate mathematical cyphers, and access the final piece of evidence that will blow this case wide open. Time is running out before the killer's automated scripts wipe the precinct's servers clean. You must rely on your wits, the precinct's specialized forensic tools, and the scattered clues left behind to unmask the culprit. Examine everything carefully; in this line of work, every hash, code, and locked container tells a story.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "item_10", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_10", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "485720394857230495827349857234" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "485720394857230495827349857234" + } + }, + "narrative": "This is the Final Evidence Folder. A sealed Manila folder containing the ultimate truth of the case." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "(no output)" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized awaiting input stream A." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeefcafebabe1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialized awaiting input stream A.", + "hex_output": "deadbeefcafebabe1234567890abcdef" + } + }, + "narrative": "This is the Main Police Mainframe. A heavy-duty precinct computer. It requires inputs from both the Forensic Code Analyzer and the Cipher Translator Beta." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'Task Completed'" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is the Forensic Code Analyzer. A specialized environment for running recovered scripts. It requires input from the Encrypted Drive Data." + }, + { + "id": "item_11", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_11", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "Python code", + "value": "def execute_task():\n return 'Task Completed'" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def execute_task():\n return 'Task Completed'" + } + }, + "narrative": "This is the Encrypted Drive Data. A heavily corrupted flash drive containing suspicious digital scripts." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "Calculation pending inputs." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Evidence Locker 4. A heavy steel locker in the precinct. It requires input from the Suspect Verification Terminal to authorize unlocking." + }, + { + "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": "394857239485723948572394857239" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "00112233445566778899aabbccddeeff" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "MathToken_Alpha" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation pending inputs.", + "hex_result": "00112233445566778899aabbccddeeff", + "math_token": "MathToken_Alpha" + } + }, + "narrative": "This is the Suspect Verification Terminal. A station used to cross-reference suspect IDs. It requires inputs from both the Cipher Translator Alpha and the Cipher Translator Gamma." + }, + { + "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": "394857239485723948572394857239" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "19266253299434619560942501832" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "112233445566778899001122334455" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "394857239485723948572394857239" + } + ], + "init": { + "inputs": { + "s": "394857239485723948572394857239" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Alpha. A digital signal conversion tool. It requires inputs from both the Cryptographic Decryptor and the Cipher Translator Gamma." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "12966" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "112233445566778899001122334455" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "102938475610293847561029384756" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "19266253299434619560942501832" + } + ], + "narrative": "This is the Cryptographic Decryptor. A high-powered decryption rig. It requires inputs from the Frequency Analysis Scanner, the Cipher Translator Beta, and the Cipher Translator Gamma." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "102938475610293847561029384756" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "582734958273495827349582734958" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "12966" + } + ], + "init": { + "inputs": { + "b": "582734958273495827349582734958" + }, + "outputs": {} + }, + "narrative": "This is the Frequency Analysis Scanner. A device that finds common patterns in numeric data. It requires input from the Cipher Translator Beta." + }, + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_96e866ecd2956ec4" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + "outputs": {} + }, + "narrative": "This is the Secure Briefcase. A sleek, black leather briefcase with a sophisticated biometric lock." + }, + { + "id": "num_base_convert_b54a", + "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": "102938475610293847561029384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "112233445566778899001122334455" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "691235" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "102938475610293847561029384756" + } + ], + "init": { + "inputs": { + "s": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Beta. A secondary digital signal conversion tool. It requires inputs from both the Cipher Translator Gamma and the Reverse Hash Calculator." + }, + { + "id": "num_base_convert_7e97", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "112233445566778899001122334455" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "691235" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "112233445566778899001122334455" + } + ], + "init": { + "inputs": { + "s": "112233445566778899001122334455", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the Cipher Translator Gamma. An advanced digital signal conversion tool. It requires input from the Reverse Hash Calculator." + }, + { + "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": "Specification: Hyper-Dense Alloy Block v4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_96e866ecd2956ec4" + } + ], + "init": { + "inputs": { + "blueprint": "Specification: Hyper-Dense Alloy Block v4" + }, + "outputs": {} + }, + "narrative": "This is the 3D Evidence Reconstructor. A cutting-edge fabrication unit that can print physical copies of digital evidence." + }, + { + "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": "675849302167584930216758493021" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "691235" + } + ], + "init": { + "inputs": { + "a": "675849302167584930216758493021", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Reverse Hash Calculator. An old but reliable calculator used to reverse modular arithmetic." + }, + { + "id": "container_1_b16f", + "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": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "f0e1d2c3b4a5968778695a4b3c2d1e0f" + }, + "outputs": {} + }, + "narrative": "This is the Detective's Lockbox. A small personal lockbox belonging to the lead investigator." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_10", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "code_py_exec", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "container_4", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "num_base_convert", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num1" + }, + { + "source_id": "calc_modexp", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "container_1", + "target_id": "calc_modexp", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "num2" + }, + { + "source_id": "matter_synthesizer", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "num_base_convert_b54a", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "slot_b" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_7e97", + "target_id": "num_base_convert_b54a", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_7e97", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert_b54a", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "container_1_b16f", + "target_id": "num_base_convert_7e97", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-7b7d9797/solution/solve.sh b/tasks/agentescape-15-skeleton-7b7d9797/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-7b7d9797/task.toml b/tasks/agentescape-15-skeleton-7b7d9797/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..72c50e39a8ff75639344677d1bdf8525e1e31456 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "8bd72846b27a223564f9057bf3db47a822b1d4767dd0c688c79e10aa34330c21" +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-15-skeleton-7b7d9797/tests/Dockerfile b/tasks/agentescape-15-skeleton-7b7d9797/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-7b7d9797/tests/expected.json b/tasks/agentescape-15-skeleton-7b7d9797/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a315ae5a5f73b3004bf49d1a01d0517bf58de6f2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "8bd72846b27a223564f9057bf3db47a822b1d4767dd0c688c79e10aa34330c21", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-7b7d9797/tests/grade.py b/tasks/agentescape-15-skeleton-7b7d9797/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/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-15-skeleton-7b7d9797/tests/test.sh b/tasks/agentescape-15-skeleton-7b7d9797/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-7b7d9797/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-87684170/environment/Dockerfile b/tasks/agentescape-15-skeleton-87684170/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-87684170/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/agent/cli.py b/tasks/agentescape-15-skeleton-87684170/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-87684170/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2724917c86ea19e8215e35478aa56505cd29e1f4 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170-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-15-skeleton-87684170/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..05f1f090ebb87e6cca3bacabe14f9ffd8d4c7ede --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/scenario.json @@ -0,0 +1,848 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "base64_encode", + "win_condition": { + "type": "tool_output", + "node_id": "base64_encode", + "output_port": "b64", + "output_type": "Text_Generic", + "description": "Execute Base64 Encoder and get the output from port 'b64'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "json_get", + "zip_unzip_file", + "zip_unzip_file_90f9", + "terminal_1", + "time_convert", + "item_7" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_90f9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "38475619283746501928" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "Target_Destination_Node_V9" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "extracted_config_data.json" + } + }, + "zip_unzip_file_90f9": { + "init_inputs": { + "zip_id": "archive_protected_2024.zip" + }, + "init_outputs": { + "files": "network_topology_graph.json" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialization sequence complete. System ready.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Standard Operator Toolkit" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2024-10-27T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/Los_Angeles" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print('Code execution module activated successfully.')" + } + } + }, + "intro_narrative": "You wake up in a damp, neon-lit alleyway in the underbelly of Neo-Kowloon. The rain washes over the cybernetic debris scattered around you. A megacorporation's purge protocol has trapped you in this sector, and the only way out is to reactivate an abandoned communication array to broadcast an encrypted distress signal. You must interface with forgotten tech, bypass rogue security modules, and scavenge old hardware to weave your way through the local network. Time is running out before the hunter drones arrive. Connect the fragmented systems, decode the data trail, and escape.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "62b7b71baca435c2117ad206f20308bf5180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Yre3G6ykNcIRetIG8gMIv1GA8JxSSxAc98TcXATPJTUHSc61oDgzJz9PKRYAJcgWvw==" + } + ], + "narrative": "This is the Final Uplink Transmitter. It requires input from the Quantum Cipher to broadcast the escape signal." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "62b7b71baca435c2117ad206f20308bf5180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "narrative": "A Quantum Cipher device. It requires inputs from both the Data Compressor and the Mainframe Console to align the encryption arrays." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "narrative": "This is a Data Compressor. It requires input from the Sector Navigator to condense the spatial coordinates into a usable format." + }, + { + "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_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "2024-10-27T07:30:00-07:00" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Target_Destination_Node_V9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38475619283746501928" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "38475619283746501928" + } + }, + "narrative": "A holographic Sector Navigator. It requires inputs from the Data Extractor, the Outer Archive Decryptor, and the Chrono-Sync Module to map the route." + }, + { + "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": "extracted_config_data.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "Code execution module activated successfully.\n" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Target_Destination_Node_V9" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "Target_Destination_Node_V9" + } + }, + "narrative": "The Data Extractor terminal. It requires inputs from both the Neural Processor and the Inner Archive Decryptor to parse the deep network structures." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Code execution module activated successfully.')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Code execution module activated successfully.\n" + } + ], + "narrative": "A high-end Neural Processor. It requires input from the Encrypted Logic Chip to execute the necessary override subroutines." + }, + { + "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 discarded Access Keycard with a faded megacorp logo printed on its surface." + }, + { + "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": "network_topology_graph.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_data.json" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "extracted_config_data.json" + } + }, + "narrative": "The Inner Archive Decryptor. It requires input from the Outer Archive Decryptor to peel back the next layer of security." + }, + { + "id": "zip_unzip_file_90f9", + "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_protected_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "2024-10-27T07:30:00-07:00" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_protected_2024.zip" + }, + "outputs": { + "files": "network_topology_graph.json" + } + }, + "narrative": "The Outer Archive Decryptor. It requires input from the Chrono-Sync Module to bypass the time-locked firewall." + }, + { + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3645834830 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialization sequence complete. System ready." + }, + { + "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": "Standard Operator Toolkit" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialization sequence complete. System ready.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Standard Operator Toolkit" + } + }, + "narrative": "The central Mainframe Console. It requires inputs from both the Integrity Validator and the Sector Navigator to fully boot up." + }, + { + "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": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d94f064e" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3645834830 + } + ], + "narrative": "A biometric Integrity Validator. It requires input from the Data Compressor to verify the integrity of the data stream." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2024-10-27T14:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/Los_Angeles" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2024-10-27T07:30:00-07:00" + } + ], + "init": { + "inputs": { + "iso": "2024-10-27T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/Los_Angeles" + }, + "outputs": {} + }, + "narrative": "A Chrono-Sync Module built into the wall, its screen flashing with shifting global timestamps." + }, + { + "id": "item_16_6f11", + "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 pristine Bypass Token lying hidden among the electronic scrap." + }, + { + "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": "print('Code execution module activated successfully.')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print('Code execution module activated successfully.')" + } + }, + "narrative": "An Encrypted Logic Chip pulled from a destroyed synthetic chassis." + }, + { + "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 bloody Cybernetic Implant, recently extracted and still sparking." + } + ], + "edges": [ + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zlib_deflate", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "dst" + }, + { + "source_id": "code_py_exec", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "jsonpath" + }, + { + "source_id": "item_16", + "target_id": "json_get", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_90f9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "src" + }, + { + "source_id": "item_16_6f11", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "time_convert", + "target_id": "zip_unzip_file_90f9", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_90f9", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-87684170/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-87684170/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/instruction.md b/tasks/agentescape-15-skeleton-87684170/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/solution/oracle.py b/tasks/agentescape-15-skeleton-87684170/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/solution/scenario.json b/tasks/agentescape-15-skeleton-87684170/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..05f1f090ebb87e6cca3bacabe14f9ffd8d4c7ede --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/solution/scenario.json @@ -0,0 +1,848 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "base64_encode", + "win_condition": { + "type": "tool_output", + "node_id": "base64_encode", + "output_port": "b64", + "output_type": "Text_Generic", + "description": "Execute Base64 Encoder and get the output from port 'b64'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "json_get", + "zip_unzip_file", + "zip_unzip_file_90f9", + "terminal_1", + "time_convert", + "item_7" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_90f9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "iso": { + "type": "Text_Generic", + "description": "ISO Timestamp" + }, + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + }, + "to_tz": { + "type": "Text_Generic", + "description": "To Timezone" + } + }, + "init_outputs": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "38475619283746501928" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "Target_Destination_Node_V9" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "extracted_config_data.json" + } + }, + "zip_unzip_file_90f9": { + "init_inputs": { + "zip_id": "archive_protected_2024.zip" + }, + "init_outputs": { + "files": "network_topology_graph.json" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal initialization sequence complete. System ready.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Standard Operator Toolkit" + } + }, + "time_convert": { + "init_inputs": { + "iso": "2024-10-27T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/Los_Angeles" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print('Code execution module activated successfully.')" + } + } + }, + "intro_narrative": "You wake up in a damp, neon-lit alleyway in the underbelly of Neo-Kowloon. The rain washes over the cybernetic debris scattered around you. A megacorporation's purge protocol has trapped you in this sector, and the only way out is to reactivate an abandoned communication array to broadcast an encrypted distress signal. You must interface with forgotten tech, bypass rogue security modules, and scavenge old hardware to weave your way through the local network. Time is running out before the hunter drones arrive. Connect the fragmented systems, decode the data trail, and escape.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "62b7b71baca435c2117ad206f20308bf5180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Yre3G6ykNcIRetIG8gMIv1GA8JxSSxAc98TcXATPJTUHSc61oDgzJz9PKRYAJcgWvw==" + } + ], + "narrative": "This is the Final Uplink Transmitter. It requires input from the Quantum Cipher to broadcast the escape signal." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "62b7b71baca435c2117ad206f20308bf5180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "narrative": "A Quantum Cipher device. It requires inputs from both the Data Compressor and the Mainframe Console to align the encryption arrays." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "narrative": "This is a Data Compressor. It requires input from the Sector Navigator to condense the spatial coordinates into a usable format." + }, + { + "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_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "2024-10-27T07:30:00-07:00" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Target_Destination_Node_V9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38475619283746501928" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "38475619283746501928" + } + }, + "narrative": "A holographic Sector Navigator. It requires inputs from the Data Extractor, the Outer Archive Decryptor, and the Chrono-Sync Module to map the route." + }, + { + "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": "extracted_config_data.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "Code execution module activated successfully.\n" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Target_Destination_Node_V9" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "Target_Destination_Node_V9" + } + }, + "narrative": "The Data Extractor terminal. It requires inputs from both the Neural Processor and the Inner Archive Decryptor to parse the deep network structures." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Code execution module activated successfully.')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Code execution module activated successfully.\n" + } + ], + "narrative": "A high-end Neural Processor. It requires input from the Encrypted Logic Chip to execute the necessary override subroutines." + }, + { + "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 discarded Access Keycard with a faded megacorp logo printed on its surface." + }, + { + "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": "network_topology_graph.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_data.json" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "extracted_config_data.json" + } + }, + "narrative": "The Inner Archive Decryptor. It requires input from the Outer Archive Decryptor to peel back the next layer of security." + }, + { + "id": "zip_unzip_file_90f9", + "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_protected_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "2024-10-27T07:30:00-07:00" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "archive_protected_2024.zip" + }, + "outputs": { + "files": "network_topology_graph.json" + } + }, + "narrative": "The Outer Archive Decryptor. It requires input from the Chrono-Sync Module to bypass the time-locked firewall." + }, + { + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3645834830 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialization sequence complete. System ready." + }, + { + "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": "Standard Operator Toolkit" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal initialization sequence complete. System ready.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d", + "item_dispenser": "Standard Operator Toolkit" + } + }, + "narrative": "The central Mainframe Console. It requires inputs from both the Integrity Validator and the Sector Navigator to fully boot up." + }, + { + "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": "789c8b56f2cb4f498d77cc29c84854d25180f09c524b101cf7c4dc5c04cf25350749ceb5a03833273f4f29160025c816bf" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "d94f064e" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3645834830 + } + ], + "narrative": "A biometric Integrity Validator. It requires input from the Data Compressor to verify the integrity of the data stream." + }, + { + "id": "time_convert", + "name": "Timezone Converter", + "description": "Convert ISO time between timezones.", + "type": "Tool", + "template_id": "time_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "ISO Timestamp", + "value": "2024-10-27T14:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "UTC" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "America/Los_Angeles" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2024-10-27T07:30:00-07:00" + } + ], + "init": { + "inputs": { + "iso": "2024-10-27T14:30:00Z", + "from_tz": "UTC", + "to_tz": "America/Los_Angeles" + }, + "outputs": {} + }, + "narrative": "A Chrono-Sync Module built into the wall, its screen flashing with shifting global timestamps." + }, + { + "id": "item_16_6f11", + "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 pristine Bypass Token lying hidden among the electronic scrap." + }, + { + "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": "print('Code execution module activated successfully.')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print('Code execution module activated successfully.')" + } + }, + "narrative": "An Encrypted Logic Chip pulled from a destroyed synthetic chassis." + }, + { + "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 bloody Cybernetic Implant, recently extracted and still sparking." + } + ], + "edges": [ + { + "source_id": "text_xor_hex", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zlib_deflate", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "json_get", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "dst" + }, + { + "source_id": "code_py_exec", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "jsonpath" + }, + { + "source_id": "item_16", + "target_id": "json_get", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_90f9", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "slot_a" + }, + { + "source_id": "time_convert", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "src" + }, + { + "source_id": "item_16_6f11", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "time_convert", + "target_id": "zip_unzip_file_90f9", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_90f9", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-87684170/solution/solve.sh b/tasks/agentescape-15-skeleton-87684170/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-87684170/task.toml b/tasks/agentescape-15-skeleton-87684170/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..38fcfa919ebaa44b95634de2c256511b8cd9f266 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "c05c46091b29f17367e2b04cea5f23759b4c8c09878ea970615dc3d52efa0069" +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-15-skeleton-87684170/tests/Dockerfile b/tasks/agentescape-15-skeleton-87684170/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-87684170/tests/expected.json b/tasks/agentescape-15-skeleton-87684170/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..1bb68ec061166ed77537d5601a4916e580295277 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "c05c46091b29f17367e2b04cea5f23759b4c8c09878ea970615dc3d52efa0069", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-87684170/tests/grade.py b/tasks/agentescape-15-skeleton-87684170/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/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-15-skeleton-87684170/tests/test.sh b/tasks/agentescape-15-skeleton-87684170/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-87684170/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/environment/Dockerfile b/tasks/agentescape-15-skeleton-8ee36fb4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-8ee36fb4/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/agent/cli.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-8ee36fb4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..910bcb3059db3a8dd2e3c9c73de40b5effd452fa --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4-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-15-skeleton-8ee36fb4/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b3363236edd72f397dd5208d1649ba3a41271d0b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/scenario.json @@ -0,0 +1,875 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "text_xor_hex", + "win_condition": { + "type": "tool_output", + "node_id": "text_xor_hex", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Hex XOR and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "item_7", + "terminal_1", + "calc_modexp", + "zlib_deflate", + "terminal_2_de5f", + "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" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp": { + "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": {} + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "terminal_2_de5f": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_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": "System ready for input processing.", + "hex_result": "c4d3e2f1a0b987654321" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initial text sequence for encoding.", + "hex_output": "a1b2c3d4e5f678901234", + "item_dispenser": "Standard issue connector item." + } + }, + "calc_modexp": { + "init_inputs": { + "base": "38471029384756102938", + "mod": "492817" + }, + "init_outputs": {} + }, + "zlib_deflate": { + "init_inputs": { + "text": "Compacting data stream for efficient transfer." + }, + "init_outputs": {} + }, + "terminal_2_de5f": { + "init_inputs": { + "num1": "82736451928374651029" + }, + "init_outputs": { + "text_result": "Calculation module active.", + "hex_result": "123456789abcdef01234" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "65748392015647382910", + "b": "19283746501928374650" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You have just stepped into the dimly lit, abandoned office of the infamous 'Cipher Killer'. The room is cluttered with strange mechanical gadgets, humming terminals, and heavy steel locks. The air is thick with dust and the quiet ticking of hidden mechanisms. Your objective is clear: trace the flow of hidden data, operate the complex machinery in the correct sequence, and uncover the final password to unlock the master safe before the killer returns. Every device in this room is part of a larger, interconnected web. You must carefully follow the clues and pass the evidence through the right machines to reveal the truth.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "52657175657374696e672061636365737320746f20736563757265207661756c74" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "496e697469616c20746578742073657175656e636520666f7220656e636f64696e672e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "1b0b18010c1218491a0258154310000206451a0c4553030c0752004e150e11051a672e" + } + ], + "narrative": "This is the Master Vault. It requires inputs from both the Teletype Machine and the Frequency Decoder to finally swing open." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Initial text sequence for encoding." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e697469616c20746578742073657175656e636520666f7220656e636f64696e672e" + } + ], + "narrative": "This is a Teletype Machine. It requires input from the Vault Keypad to translate the finalized codes." + }, + { + "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": "1" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 1846469697 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System ready for input processing." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "c4d3e2f1a0b987654321" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System ready for input processing.", + "hex_result": "c4d3e2f1a0b987654321" + } + }, + "narrative": "This is a Dispatch Terminal. It requires inputs from both the Primary Scanner and the Pattern Matcher to log into the network." + }, + { + "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": "UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0\n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "52657175657374696e672061636365737320746f20736563757265207661756c74" + } + ], + "narrative": "This is a Frequency Decoder. It requires input from the Analysis Workstation to process the recovered signals." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0\n" + } + ], + "narrative": "This is an Analysis Workstation. It requires input from the Suspect's Notebook to execute the hidden routines." + }, + { + "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": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + }, + "narrative": "This is the Suspect's Notebook, filled with frantic, handwritten scribbles and locked away secrets." + }, + { + "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": "789c05c1c10d00200803c0553a814b3849a360788806bb7fbceb675f0e452e4c8a782ae3869f82b9c7084b41c57c6ed53e97451153" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6e0ee441" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1846469697 + } + ], + "narrative": "This is a Primary Scanner. It requires input from the Document Compressor to verify the evidence's authenticity." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "System ready for input processing." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3421124040 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initial text sequence for encoding." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f678901234" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard issue connector item." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initial text sequence for encoding.", + "hex_output": "a1b2c3d4e5f678901234", + "item_dispenser": "Standard issue connector item." + } + }, + "narrative": "This is a Vault Keypad. It requires inputs from both the Dispatch Terminal and the Secondary Scanner to grant access." + }, + { + "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": "This is a Broken Pocket Watch, its hands mysteriously frozen at a very specific time." + }, + { + "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": 1846469697 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "316837" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a Pattern Matcher. It requires inputs from both the Rotational Cipher and the Primary Scanner to function." + }, + { + "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": "38471029384756102938" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3421124040 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "492817" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "316837" + } + ], + "init": { + "inputs": { + "base": "38471029384756102938", + "mod": "492817" + }, + "outputs": {} + }, + "narrative": "This is a Rotational Cipher. It requires input from the Secondary Scanner to align its inner mechanisms." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Compacting data stream for efficient transfer." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1c10d00200803c0553a814b3849a360788806bb7fbceb675f0e452e4c8a782ae3869f82b9c7084b41c57c6ed53e97451153" + } + ], + "init": { + "inputs": { + "text": "Compacting data stream for efficient transfer." + }, + "outputs": {} + }, + "narrative": "This is a Document Compressor, a strange pneumatic device designed to shrink files down for covert transport." + }, + { + "id": "checksum_crc32_712b", + "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": "6e0ee441" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "cbea35c8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3421124040 + } + ], + "narrative": "This is a Secondary Scanner. It requires input from the Primary Scanner to complete the dual-authentication process." + }, + { + "id": "terminal_2_de5f", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "82736451928374651029" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1267875324539155697866109131542487231500" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation module active." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "123456789abcdef01234" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "82736451928374651029" + }, + "outputs": { + "text_result": "Calculation module active.", + "hex_result": "123456789abcdef01234" + } + }, + "narrative": "This is an Encrypted Laptop. It requires input from the Antique Arithmometer to bypass its initial lock screen." + }, + { + "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": "65748392015647382910" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "19283746501928374650" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1267875324539155697866109131542487231500" + } + ], + "init": { + "inputs": { + "a": "65748392015647382910", + "b": "19283746501928374650" + }, + "outputs": {} + }, + "narrative": "This is an Antique Arithmometer, a heavy mechanical calculator with brass gears used for complex calculations." + } + ], + "edges": [ + { + "source_id": "hex_encode", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "terminal_2", + "target_id": "hex_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "base64_decode", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex_a" + }, + { + "source_id": "code_py_exec", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "data" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "terminal_1", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "item_16", + "target_id": "item_7", + "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_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_712b", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_712b", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_712b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_2_de5f", + "target_id": "zlib_deflate", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2_de5f", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-8ee36fb4/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/instruction.md b/tasks/agentescape-15-skeleton-8ee36fb4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/solution/oracle.py b/tasks/agentescape-15-skeleton-8ee36fb4/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/solution/scenario.json b/tasks/agentescape-15-skeleton-8ee36fb4/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b3363236edd72f397dd5208d1649ba3a41271d0b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/solution/scenario.json @@ -0,0 +1,875 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "text_xor_hex", + "win_condition": { + "type": "tool_output", + "node_id": "text_xor_hex", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Hex XOR and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "item_7", + "terminal_1", + "calc_modexp", + "zlib_deflate", + "terminal_2_de5f", + "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" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_modexp": { + "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": {} + }, + "zlib_deflate": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "init_outputs": {} + }, + "terminal_2_de5f": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_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": "System ready for input processing.", + "hex_result": "c4d3e2f1a0b987654321" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initial text sequence for encoding.", + "hex_output": "a1b2c3d4e5f678901234", + "item_dispenser": "Standard issue connector item." + } + }, + "calc_modexp": { + "init_inputs": { + "base": "38471029384756102938", + "mod": "492817" + }, + "init_outputs": {} + }, + "zlib_deflate": { + "init_inputs": { + "text": "Compacting data stream for efficient transfer." + }, + "init_outputs": {} + }, + "terminal_2_de5f": { + "init_inputs": { + "num1": "82736451928374651029" + }, + "init_outputs": { + "text_result": "Calculation module active.", + "hex_result": "123456789abcdef01234" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "65748392015647382910", + "b": "19283746501928374650" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You have just stepped into the dimly lit, abandoned office of the infamous 'Cipher Killer'. The room is cluttered with strange mechanical gadgets, humming terminals, and heavy steel locks. The air is thick with dust and the quiet ticking of hidden mechanisms. Your objective is clear: trace the flow of hidden data, operate the complex machinery in the correct sequence, and uncover the final password to unlock the master safe before the killer returns. Every device in this room is part of a larger, interconnected web. You must carefully follow the clues and pass the evidence through the right machines to reveal the truth.", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "52657175657374696e672061636365737320746f20736563757265207661756c74" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "496e697469616c20746578742073657175656e636520666f7220656e636f64696e672e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "1b0b18010c1218491a0258154310000206451a0c4553030c0752004e150e11051a672e" + } + ], + "narrative": "This is the Master Vault. It requires inputs from both the Teletype Machine and the Frequency Decoder to finally swing open." + }, + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Initial text sequence for encoding." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "496e697469616c20746578742073657175656e636520666f7220656e636f64696e672e" + } + ], + "narrative": "This is a Teletype Machine. It requires input from the Vault Keypad to translate the finalized codes." + }, + { + "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": "1" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 1846469697 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System ready for input processing." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "c4d3e2f1a0b987654321" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "System ready for input processing.", + "hex_result": "c4d3e2f1a0b987654321" + } + }, + "narrative": "This is a Dispatch Terminal. It requires inputs from both the Primary Scanner and the Pattern Matcher to log into the network." + }, + { + "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": "UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0\n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "52657175657374696e672061636365737320746f20736563757265207661756c74" + } + ], + "narrative": "This is a Frequency Decoder. It requires input from the Analysis Workstation to process the recovered signals." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0\n" + } + ], + "narrative": "This is an Analysis Workstation. It requires input from the Suspect's Notebook to execute the hidden routines." + }, + { + "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": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print('UmVxdWVzdGluZyBhY2Nlc3MgdG8gc2VjdXJlIHZhdWx0')" + } + }, + "narrative": "This is the Suspect's Notebook, filled with frantic, handwritten scribbles and locked away secrets." + }, + { + "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": "789c05c1c10d00200803c0553a814b3849a360788806bb7fbceb675f0e452e4c8a782ae3869f82b9c7084b41c57c6ed53e97451153" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6e0ee441" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1846469697 + } + ], + "narrative": "This is a Primary Scanner. It requires input from the Document Compressor to verify the evidence's authenticity." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "System ready for input processing." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3421124040 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initial text sequence for encoding." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f678901234" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard issue connector item." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initial text sequence for encoding.", + "hex_output": "a1b2c3d4e5f678901234", + "item_dispenser": "Standard issue connector item." + } + }, + "narrative": "This is a Vault Keypad. It requires inputs from both the Dispatch Terminal and the Secondary Scanner to grant access." + }, + { + "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": "This is a Broken Pocket Watch, its hands mysteriously frozen at a very specific time." + }, + { + "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": 1846469697 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "316837" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is a Pattern Matcher. It requires inputs from both the Rotational Cipher and the Primary Scanner to function." + }, + { + "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": "38471029384756102938" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 3421124040 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "492817" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "316837" + } + ], + "init": { + "inputs": { + "base": "38471029384756102938", + "mod": "492817" + }, + "outputs": {} + }, + "narrative": "This is a Rotational Cipher. It requires input from the Secondary Scanner to align its inner mechanisms." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Compacting data stream for efficient transfer." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1c10d00200803c0553a814b3849a360788806bb7fbceb675f0e452e4c8a782ae3869f82b9c7084b41c57c6ed53e97451153" + } + ], + "init": { + "inputs": { + "text": "Compacting data stream for efficient transfer." + }, + "outputs": {} + }, + "narrative": "This is a Document Compressor, a strange pneumatic device designed to shrink files down for covert transport." + }, + { + "id": "checksum_crc32_712b", + "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": "6e0ee441" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "cbea35c8" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3421124040 + } + ], + "narrative": "This is a Secondary Scanner. It requires input from the Primary Scanner to complete the dual-authentication process." + }, + { + "id": "terminal_2_de5f", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "82736451928374651029" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1267875324539155697866109131542487231500" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation module active." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "123456789abcdef01234" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "82736451928374651029" + }, + "outputs": { + "text_result": "Calculation module active.", + "hex_result": "123456789abcdef01234" + } + }, + "narrative": "This is an Encrypted Laptop. It requires input from the Antique Arithmometer to bypass its initial lock screen." + }, + { + "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": "65748392015647382910" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "19283746501928374650" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1267875324539155697866109131542487231500" + } + ], + "init": { + "inputs": { + "a": "65748392015647382910", + "b": "19283746501928374650" + }, + "outputs": {} + }, + "narrative": "This is an Antique Arithmometer, a heavy mechanical calculator with brass gears used for complex calculations." + } + ], + "edges": [ + { + "source_id": "hex_encode", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "terminal_2", + "target_id": "hex_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "base64_decode", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex_a" + }, + { + "source_id": "code_py_exec", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "data" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "terminal_1", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "item_16", + "target_id": "item_7", + "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_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "terminal_2", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "zlib_deflate", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_712b", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_712b", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_712b", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_2_de5f", + "target_id": "zlib_deflate", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2_de5f", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/solution/solve.sh b/tasks/agentescape-15-skeleton-8ee36fb4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/task.toml b/tasks/agentescape-15-skeleton-8ee36fb4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..baa144c9abdef4547da9aa123fa51d32f72642f5 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "eb39f15f9a18432f8f3e249cd4b184695249dfcfff793c32cd4bc16dd1c58a0a" +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-15-skeleton-8ee36fb4/tests/Dockerfile b/tasks/agentescape-15-skeleton-8ee36fb4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/tests/expected.json b/tasks/agentescape-15-skeleton-8ee36fb4/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..919a0f984affb34514034b4d3fb2cc7a1e638848 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "eb39f15f9a18432f8f3e249cd4b184695249dfcfff793c32cd4bc16dd1c58a0a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8ee36fb4/tests/grade.py b/tasks/agentescape-15-skeleton-8ee36fb4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/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-15-skeleton-8ee36fb4/tests/test.sh b/tasks/agentescape-15-skeleton-8ee36fb4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8ee36fb4/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-8fff2538/environment/Dockerfile b/tasks/agentescape-15-skeleton-8fff2538/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-8fff2538/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/agent/cli.py b/tasks/agentescape-15-skeleton-8fff2538/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-8fff2538/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9a0bc6fa928885315d650ef8fdfc096417febdb --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538-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-15-skeleton-8fff2538/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b5e01cd60d593621a61bd5efbf6a8c073236dbe3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/scenario.json @@ -0,0 +1,913 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "unicode_norm", + "win_condition": { + "type": "tool_output", + "node_id": "unicode_norm", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Unicode Normalizer and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "unicode_norm", + "csv_query", + "zip_unzip_file", + "terminal_2", + "calc_modexp", + "item_7", + "zip_unzip_file_b394", + "num_base_convert", + "calc_modexp_e6a0" + ], + "by_node": { + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "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" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "zip_unzip_file_b394": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp_e6a0": { + "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": {} + } + } + }, + "initial_values": { + "unicode_norm": { + "init_inputs": { + "text": "The quick brown föx jümps över the låzy døg." + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "NFC" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "target_data.csv" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "928374651029384756102938" + }, + "init_outputs": { + "text_result": "Calculation initialized.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "999983" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "val = 42\nprint(f'The value is {val}')" + } + }, + "zip_unzip_file_b394": { + "init_inputs": { + "zip_id": "archive_outer.zip", + "password": "UnlockKey_9988" + }, + "init_outputs": { + "files": "inner_archive.zip" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "485720394857263849502837465", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp_e6a0": { + "init_inputs": { + "base": "12345", + "exp": "65537", + "mod": "100003" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the sealed laboratory of Professor Gearwick, surrounded by hissing pipes, turning cogs, and the suffocating heat of trapped steam. The heavy brass door is locked tight, and the pressure in the room is slowly rising. The only way out is to activate his master invention: the linguistic difference engine. You must trace the flow of data through his array of steam-powered analytical machines, decrypters, and punch-card readers. Follow the mechanical logic, deduce the connections between the various gear-driven devices, and power up the final engine before the boiler overloads completely.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "The quick brown föx jümps över the låzy døg." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "The quick brown föx jümps över the låzy døg." + } + ], + "init": { + "inputs": { + "text": "The quick brown föx jümps över the låzy døg." + }, + "outputs": {} + }, + "narrative": "This is the linguistic difference engine. It requires input from the brass records indexer. Once you have the indexer's output, bring it here." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "target_data.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "False" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "false" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "NFC" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "NFC" + } + }, + "narrative": "This is the brass records indexer. It requires inputs from the banking guild verifier, the merchant logic checker, and the secondary steam-powered decrypter." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "The value is 42\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "This is the banking guild verifier. It requires input from the analytical engine. Feed it the results from the engine to verify the routing." + }, + { + "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": "The value is 42\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the merchant logic checker. It requires input from the analytical engine. Process the data through the engine before checking it here." + }, + { + "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": "inner_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "target_data.csv" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "target_data.csv" + } + }, + "narrative": "This is the secondary steam-powered decrypter. It requires input from the primary steam-powered decrypter to unlock the inner cylinders." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A discarded chronometer found in the workshop debris." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "val = 42\nprint(f'The value is {val}')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "The value is 42\n" + } + ], + "narrative": "This is the analytical engine. It requires input from a punch card of instructions. Insert the punch card to begin its calculations." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "928374651029384756102938" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "571351" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation initialized." + }, + { + "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": "928374651029384756102938" + }, + "outputs": { + "text_result": "Calculation initialized.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the main control console. It requires input from the heavy gear exponentiator. After processing with the exponentiator, use the output here." + }, + { + "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": "81672" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "485720394857263849502837465" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "571351" + } + ], + "init": { + "inputs": { + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the heavy gear exponentiator. It requires inputs from both the arithmometer base converter and the primary gear exponentiator to function." + }, + { + "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": "val = 42\nprint(f'The value is {val}')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "val = 42\nprint(f'The value is {val}')" + } + }, + "narrative": "A punch card of instructions hidden within a mechanical contraption." + }, + { + "id": "zip_unzip_file_b394", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_outer.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "UnlockKey_9988" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "inner_archive.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_outer.zip", + "password": "UnlockKey_9988" + }, + "outputs": { + "files": "inner_archive.zip" + } + }, + "narrative": "This is the primary steam-powered decrypter. It hums with latent boiler pressure, waiting to unseal locked cylinders." + }, + { + "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 rusted mechanical integer, shaped from solid brass." + }, + { + "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": "485720394857263849502837465" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "81672" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "485720394857263849502837465" + } + ], + "init": { + "inputs": { + "s": "485720394857263849502837465", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the arithmometer base converter. It requires input from the primary gear exponentiator to shift its mathematical gears." + }, + { + "id": "calc_modexp_e6a0", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "12345" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "65537" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "81672" + } + ], + "init": { + "inputs": { + "base": "12345", + "exp": "65537", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the primary gear exponentiator, waiting for its starting configuration to spin up the cogs." + }, + { + "id": "item_16_c8e2", + "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 brass timezone gauge, clicking faintly with clockwork precision." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "form" + }, + { + "source_id": "iban_validate", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "where" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "csv_query", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "code_py_exec", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "iban" + }, + { + "source_id": "code_py_exec", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "number" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "zip_unzip_file_b394", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_e6a0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_e6a0", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "item_16_c8e2", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-8fff2538/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/instruction.md b/tasks/agentescape-15-skeleton-8fff2538/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/solution/oracle.py b/tasks/agentescape-15-skeleton-8fff2538/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/solution/scenario.json b/tasks/agentescape-15-skeleton-8fff2538/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b5e01cd60d593621a61bd5efbf6a8c073236dbe3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/solution/scenario.json @@ -0,0 +1,913 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "unicode_norm", + "win_condition": { + "type": "tool_output", + "node_id": "unicode_norm", + "output_port": "text", + "output_type": "Text_Generic", + "description": "Execute Unicode Normalizer and get the output from port 'text'" + }, + "source_init": { + "source_nodes": [ + "unicode_norm", + "csv_query", + "zip_unzip_file", + "terminal_2", + "calc_modexp", + "item_7", + "zip_unzip_file_b394", + "num_base_convert", + "calc_modexp_e6a0" + ], + "by_node": { + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "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" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "zip_unzip_file_b394": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp_e6a0": { + "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": {} + } + } + }, + "initial_values": { + "unicode_norm": { + "init_inputs": { + "text": "The quick brown föx jümps över the låzy døg." + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "NFC" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "target_data.csv" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "928374651029384756102938" + }, + "init_outputs": { + "text_result": "Calculation initialized.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "999983" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "val = 42\nprint(f'The value is {val}')" + } + }, + "zip_unzip_file_b394": { + "init_inputs": { + "zip_id": "archive_outer.zip", + "password": "UnlockKey_9988" + }, + "init_outputs": { + "files": "inner_archive.zip" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "485720394857263849502837465", + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp_e6a0": { + "init_inputs": { + "base": "12345", + "exp": "65537", + "mod": "100003" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the sealed laboratory of Professor Gearwick, surrounded by hissing pipes, turning cogs, and the suffocating heat of trapped steam. The heavy brass door is locked tight, and the pressure in the room is slowly rising. The only way out is to activate his master invention: the linguistic difference engine. You must trace the flow of data through his array of steam-powered analytical machines, decrypters, and punch-card readers. Follow the mechanical logic, deduce the connections between the various gear-driven devices, and power up the final engine before the boiler overloads completely.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "The quick brown föx jümps över the låzy døg." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "The quick brown föx jümps över the låzy døg." + } + ], + "init": { + "inputs": { + "text": "The quick brown föx jümps över the låzy døg." + }, + "outputs": {} + }, + "narrative": "This is the linguistic difference engine. It requires input from the brass records indexer. Once you have the indexer's output, bring it here." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "target_data.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "False" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "false" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "NFC" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "NFC" + } + }, + "narrative": "This is the brass records indexer. It requires inputs from the banking guild verifier, the merchant logic checker, and the secondary steam-powered decrypter." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "The value is 42\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "This is the banking guild verifier. It requires input from the analytical engine. Feed it the results from the engine to verify the routing." + }, + { + "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": "The value is 42\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the merchant logic checker. It requires input from the analytical engine. Process the data through the engine before checking it here." + }, + { + "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": "inner_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "target_data.csv" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "target_data.csv" + } + }, + "narrative": "This is the secondary steam-powered decrypter. It requires input from the primary steam-powered decrypter to unlock the inner cylinders." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A discarded chronometer found in the workshop debris." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "val = 42\nprint(f'The value is {val}')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "The value is 42\n" + } + ], + "narrative": "This is the analytical engine. It requires input from a punch card of instructions. Insert the punch card to begin its calculations." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "928374651029384756102938" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "571351" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation initialized." + }, + { + "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": "928374651029384756102938" + }, + "outputs": { + "text_result": "Calculation initialized.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "This is the main control console. It requires input from the heavy gear exponentiator. After processing with the exponentiator, use the output here." + }, + { + "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": "81672" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "485720394857263849502837465" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "571351" + } + ], + "init": { + "inputs": { + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the heavy gear exponentiator. It requires inputs from both the arithmometer base converter and the primary gear exponentiator to function." + }, + { + "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": "val = 42\nprint(f'The value is {val}')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "val = 42\nprint(f'The value is {val}')" + } + }, + "narrative": "A punch card of instructions hidden within a mechanical contraption." + }, + { + "id": "zip_unzip_file_b394", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "archive_outer.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "UnlockKey_9988" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "inner_archive.zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_outer.zip", + "password": "UnlockKey_9988" + }, + "outputs": { + "files": "inner_archive.zip" + } + }, + "narrative": "This is the primary steam-powered decrypter. It hums with latent boiler pressure, waiting to unseal locked cylinders." + }, + { + "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 rusted mechanical integer, shaped from solid brass." + }, + { + "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": "485720394857263849502837465" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "81672" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "485720394857263849502837465" + } + ], + "init": { + "inputs": { + "s": "485720394857263849502837465", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is the arithmometer base converter. It requires input from the primary gear exponentiator to shift its mathematical gears." + }, + { + "id": "calc_modexp_e6a0", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "12345" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "65537" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "100003" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "81672" + } + ], + "init": { + "inputs": { + "base": "12345", + "exp": "65537", + "mod": "100003" + }, + "outputs": {} + }, + "narrative": "This is the primary gear exponentiator, waiting for its starting configuration to spin up the cogs." + }, + { + "id": "item_16_c8e2", + "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 brass timezone gauge, clicking faintly with clockwork precision." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "form" + }, + { + "source_id": "iban_validate", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "luhn_check", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "where" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "csv_query", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "code_py_exec", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "iban" + }, + { + "source_id": "code_py_exec", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "number" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "zip_unzip_file_b394", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_8", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_e6a0", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_e6a0", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "item_16_c8e2", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8fff2538/solution/solve.sh b/tasks/agentescape-15-skeleton-8fff2538/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-8fff2538/task.toml b/tasks/agentescape-15-skeleton-8fff2538/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bda93682746c4891167905a68ddead5442f00923 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "701568cc755a98a32f54eb2192ad344fb41d5a360bf3475de743f4c3e4dcb4b6" +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-15-skeleton-8fff2538/tests/Dockerfile b/tasks/agentescape-15-skeleton-8fff2538/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-8fff2538/tests/expected.json b/tasks/agentescape-15-skeleton-8fff2538/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0901278c8eef40dd1c5959350f52adbc5d540d3f --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "701568cc755a98a32f54eb2192ad344fb41d5a360bf3475de743f4c3e4dcb4b6", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-8fff2538/tests/grade.py b/tasks/agentescape-15-skeleton-8fff2538/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/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-15-skeleton-8fff2538/tests/test.sh b/tasks/agentescape-15-skeleton-8fff2538/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-8fff2538/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-931603ff/environment/Dockerfile b/tasks/agentescape-15-skeleton-931603ff/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-931603ff/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/agent/cli.py b/tasks/agentescape-15-skeleton-931603ff/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-931603ff/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4220cbd6d62097eb4272f3e957d03e5393a98edf --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff-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-15-skeleton-931603ff/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8ee831d8821ed946479ad92dba5bb118adfe494e --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/scenario.json @@ -0,0 +1,923 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "hash_md5", + "win_condition": { + "type": "tool_output", + "node_id": "hash_md5", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute MD5 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "zip_unzip_file", + "zip_unzip_file_7ab4", + "json_get", + "zip_unzip_file_5597", + "zip_unzip_file_5dab", + "terminal_1", + "hash_sha256", + "matter_synthesizer", + "calc_gcd" + ], + "by_node": { + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_7ab4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "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": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file_5597": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_5dab": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "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": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "financial_records.csv" + } + }, + "zip_unzip_file_7ab4": { + "init_inputs": {}, + "init_outputs": { + "files": "encrypted_ledger.zip" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "DE21300098000004567890" + } + }, + "zip_unzip_file_5597": { + "init_inputs": {}, + "init_outputs": { + "files": "intermediate_bundle.zip" + } + }, + "zip_unzip_file_5dab": { + "init_inputs": { + "zip_id": "root_archive_v1.zip" + }, + "init_outputs": { + "files": "level1_data.zip" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "SuperSecretPassword2024!", + "hex_output": "48656c6c6f576f726c6d", + "item_dispenser": "Admin Access Badge" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "Initiate secure hashing sequence alpha." + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic: Quantum Resonance Emitter" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "837465920183746592018374", + "b": "293847561029384756102938" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the forgotten sanctum of the Archmage, a hidden subterranean chamber where reality bends and magic is woven into physical form. The air is thick with the scent of ozone, ancient dust, and old parchment. Flickering torches cast long, dancing shadows across walls etched with glowing runes. To escape this mystical prison, you must unlock the ultimate power of the sanctum and forge an artifact capable of breaking the warding seal. Many enchanted objects, arcane tools, and locked magical chests lie scattered around the room, each bound by intricate, interwoven dependencies. You will need to carefully trace the flow of arcane energy, using spells and artifacts in the precise order to uncover the final incantation. The ultimate goal is to ignite the master forge and synthesize the essence of pure magic to blast the doors open.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "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": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "337d786e08792df7af8e8852f93dbc19" + } + ], + "narrative": "A blazing mystical furnace known as the Soul Forge. It requires input from the Archive of the Ancients to ignite its true power." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "financial_records.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "False" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "DE21300098000004567890" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + }, + "narrative": "A massive library of magical scrolls, the Archive of the Ancients. It requires inputs from the Runic Authenticator, the Silver Chest, and the Scrying Pool to reveal its hidden secrets." + }, + { + "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, dusty relic pulsing with faint magical energy. It seems to have been left behind by a previous adventurer." + }, + { + "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 smooth, glowing Moonstone resting on a velvet cushion. It hums softly when held in your hand." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "DE21300098000004567890" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "An enchanted stone slab covered in validation runes, known as the Runic Authenticator. It requires input from the Scrying Pool to function properly." + }, + { + "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": "encrypted_ledger.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "financial_records.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "financial_records.csv" + } + }, + "narrative": "An ornate Silver Chest sealed by defensive magic. It requires inputs from the Bronze Chest and the Runic Authenticator to be safely opened." + }, + { + "id": "zip_unzip_file_7ab4", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "encrypted_ledger.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "encrypted_ledger.zip" + } + }, + "narrative": "A sturdy Bronze Chest with a complex magical lock. It requires inputs from the Runic Authenticator and the Golden Chest to pop open." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "intermediate_bundle.zip" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "DE21300098000004567890" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "DE21300098000004567890" + } + }, + "narrative": "A dark, reflective Scrying Pool surrounded by candles. It requires inputs from the Golden Chest and the Celestial Translator to show you visions of what you seek." + }, + { + "id": "zip_unzip_file_5597", + "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": "level1_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_bundle.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "intermediate_bundle.zip" + } + }, + "narrative": "A gleaming Golden Chest that radiates warmth. It requires inputs from the Iron Chest and the Altar of Equivalence to unlock its treasures." + }, + { + "id": "zip_unzip_file_5dab", + "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": "root_archive_v1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "level1_data.zip" + } + ], + "init": { + "inputs": { + "zip_id": "root_archive_v1.zip" + }, + "outputs": { + "files": "level1_data.zip" + } + }, + "narrative": "A heavy Iron Chest bound in thick, rusted chains. It requires input from the Altar of Equivalence to shatter its magical bindings." + }, + { + "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": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "2" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "SuperSecretPassword2024!" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f576f726c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Admin Access Badge" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "SuperSecretPassword2024!", + "hex_output": "48656c6c6f576f726c6d", + "item_dispenser": "Admin Access Badge" + } + }, + "narrative": "An ancient stone table known as the Altar of Equivalence. It requires inputs from the Celestial Translator and the Abacus of the Fates to balance its scales." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_674c4fc6b2542c46" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "c023a00319018ec576b6599a9ac2d0ed330e84eec46de0406287cdc2db042bb6" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + } + ], + "narrative": "A delicate arrangement of star-glass lenses, the Celestial Translator. It requires input from the Crystal of Truth to decipher cosmic language." + }, + { + "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 secure hashing sequence alpha." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "c023a00319018ec576b6599a9ac2d0ed330e84eec46de0406287cdc2db042bb6" + } + ], + "init": { + "inputs": { + "text": "Initiate secure hashing sequence alpha." + }, + "outputs": {} + }, + "narrative": "A flawless, multifaceted Crystal of Truth resting on a pedestal. It reflects the pure essence of whatever is placed before it." + }, + { + "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": "Schematic: Quantum Resonance Emitter" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_674c4fc6b2542c46" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic: Quantum Resonance Emitter" + }, + "outputs": {} + }, + "narrative": "A spinning wheel of pure magic, the Aether Loom, capable of weaving physical forms out of thin air." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "837465920183746592018374" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "293847561029384756102938" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "837465920183746592018374", + "b": "293847561029384756102938" + }, + "outputs": {} + }, + "narrative": "An intricate Abacus of the Fates made of carved bone and gold wire. Its ethereal beads seem to move on their own." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "csv_query", + "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": "iban_validate", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_7ab4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "iban_validate", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "iban_validate", + "target_id": "zip_unzip_file_7ab4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "json_get", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "iban" + }, + { + "source_id": "json_get", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "where" + }, + { + "source_id": "zip_unzip_file_5597", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_5dab", + "target_id": "zip_unzip_file_5597", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_5597", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "slot_a" + }, + { + "source_id": "zip_unzip_file_5597", + "target_id": "zip_unzip_file_7ab4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_sha256", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "matter_synthesizer", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_5dab", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "jsonpath" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-931603ff/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/instruction.md b/tasks/agentescape-15-skeleton-931603ff/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/solution/oracle.py b/tasks/agentescape-15-skeleton-931603ff/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/solution/scenario.json b/tasks/agentescape-15-skeleton-931603ff/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8ee831d8821ed946479ad92dba5bb118adfe494e --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/solution/scenario.json @@ -0,0 +1,923 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "hash_md5", + "win_condition": { + "type": "tool_output", + "node_id": "hash_md5", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute MD5 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "zip_unzip_file", + "zip_unzip_file_7ab4", + "json_get", + "zip_unzip_file_5597", + "zip_unzip_file_5dab", + "terminal_1", + "hash_sha256", + "matter_synthesizer", + "calc_gcd" + ], + "by_node": { + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": {}, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_7ab4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "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": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file_5597": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_5dab": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "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": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "financial_records.csv" + } + }, + "zip_unzip_file_7ab4": { + "init_inputs": {}, + "init_outputs": { + "files": "encrypted_ledger.zip" + } + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "DE21300098000004567890" + } + }, + "zip_unzip_file_5597": { + "init_inputs": {}, + "init_outputs": { + "files": "intermediate_bundle.zip" + } + }, + "zip_unzip_file_5dab": { + "init_inputs": { + "zip_id": "root_archive_v1.zip" + }, + "init_outputs": { + "files": "level1_data.zip" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "SuperSecretPassword2024!", + "hex_output": "48656c6c6f576f726c6d", + "item_dispenser": "Admin Access Badge" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "Initiate secure hashing sequence alpha." + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic: Quantum Resonance Emitter" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "837465920183746592018374", + "b": "293847561029384756102938" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the forgotten sanctum of the Archmage, a hidden subterranean chamber where reality bends and magic is woven into physical form. The air is thick with the scent of ozone, ancient dust, and old parchment. Flickering torches cast long, dancing shadows across walls etched with glowing runes. To escape this mystical prison, you must unlock the ultimate power of the sanctum and forge an artifact capable of breaking the warding seal. Many enchanted objects, arcane tools, and locked magical chests lie scattered around the room, each bound by intricate, interwoven dependencies. You will need to carefully trace the flow of arcane energy, using spells and artifacts in the precise order to uncover the final incantation. The ultimate goal is to ignite the master forge and synthesize the essence of pure magic to blast the doors open.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "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": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "337d786e08792df7af8e8852f93dbc19" + } + ], + "narrative": "A blazing mystical furnace known as the Soul Forge. It requires input from the Archive of the Ancients to ignite its true power." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "financial_records.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "False" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "DE21300098000004567890" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "[{\"id\": 101, \"status\": \"active\", \"value\": 500}, {\"id\": 102, \"status\": \"pending\", \"value\": 350}]" + } + }, + "narrative": "A massive library of magical scrolls, the Archive of the Ancients. It requires inputs from the Runic Authenticator, the Silver Chest, and the Scrying Pool to reveal its hidden secrets." + }, + { + "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, dusty relic pulsing with faint magical energy. It seems to have been left behind by a previous adventurer." + }, + { + "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 smooth, glowing Moonstone resting on a velvet cushion. It hums softly when held in your hand." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "DE21300098000004567890" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "An enchanted stone slab covered in validation runes, known as the Runic Authenticator. It requires input from the Scrying Pool to function properly." + }, + { + "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": "encrypted_ledger.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "financial_records.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "financial_records.csv" + } + }, + "narrative": "An ornate Silver Chest sealed by defensive magic. It requires inputs from the Bronze Chest and the Runic Authenticator to be safely opened." + }, + { + "id": "zip_unzip_file_7ab4", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "intermediate_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "encrypted_ledger.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "encrypted_ledger.zip" + } + }, + "narrative": "A sturdy Bronze Chest with a complex magical lock. It requires inputs from the Runic Authenticator and the Golden Chest to pop open." + }, + { + "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": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "intermediate_bundle.zip" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "DE21300098000004567890" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "DE21300098000004567890" + } + }, + "narrative": "A dark, reflective Scrying Pool surrounded by candles. It requires inputs from the Golden Chest and the Celestial Translator to show you visions of what you seek." + }, + { + "id": "zip_unzip_file_5597", + "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": "level1_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "intermediate_bundle.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "intermediate_bundle.zip" + } + }, + "narrative": "A gleaming Golden Chest that radiates warmth. It requires inputs from the Iron Chest and the Altar of Equivalence to unlock its treasures." + }, + { + "id": "zip_unzip_file_5dab", + "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": "root_archive_v1.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPassword2024!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "level1_data.zip" + } + ], + "init": { + "inputs": { + "zip_id": "root_archive_v1.zip" + }, + "outputs": { + "files": "level1_data.zip" + } + }, + "narrative": "A heavy Iron Chest bound in thick, rusted chains. It requires input from the Altar of Equivalence to shatter its magical bindings." + }, + { + "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": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "2" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "SuperSecretPassword2024!" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f576f726c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Admin Access Badge" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "SuperSecretPassword2024!", + "hex_output": "48656c6c6f576f726c6d", + "item_dispenser": "Admin Access Badge" + } + }, + "narrative": "An ancient stone table known as the Altar of Equivalence. It requires inputs from the Celestial Translator and the Abacus of the Fates to balance its scales." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_674c4fc6b2542c46" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "c023a00319018ec576b6599a9ac2d0ed330e84eec46de0406287cdc2db042bb6" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "wCOgAxkBjsV2tlmamsLQ7TMOhO7EbeBAYofNwtsEK7Y=" + } + ], + "narrative": "A delicate arrangement of star-glass lenses, the Celestial Translator. It requires input from the Crystal of Truth to decipher cosmic language." + }, + { + "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 secure hashing sequence alpha." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "c023a00319018ec576b6599a9ac2d0ed330e84eec46de0406287cdc2db042bb6" + } + ], + "init": { + "inputs": { + "text": "Initiate secure hashing sequence alpha." + }, + "outputs": {} + }, + "narrative": "A flawless, multifaceted Crystal of Truth resting on a pedestal. It reflects the pure essence of whatever is placed before it." + }, + { + "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": "Schematic: Quantum Resonance Emitter" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_674c4fc6b2542c46" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic: Quantum Resonance Emitter" + }, + "outputs": {} + }, + "narrative": "A spinning wheel of pure magic, the Aether Loom, capable of weaving physical forms out of thin air." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "837465920183746592018374" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "293847561029384756102938" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "2" + } + ], + "init": { + "inputs": { + "a": "837465920183746592018374", + "b": "293847561029384756102938" + }, + "outputs": {} + }, + "narrative": "An intricate Abacus of the Fates made of carved bone and gold wire. Its ethereal beads seem to move on their own." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "csv_query", + "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": "iban_validate", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_7ab4", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "iban_validate", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "iban_validate", + "target_id": "zip_unzip_file_7ab4", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "json_get", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "iban" + }, + { + "source_id": "json_get", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "where" + }, + { + "source_id": "zip_unzip_file_5597", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_5dab", + "target_id": "zip_unzip_file_5597", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_5597", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "slot_a" + }, + { + "source_id": "zip_unzip_file_5597", + "target_id": "zip_unzip_file_7ab4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hash_sha256", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "matter_synthesizer", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file_5dab", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "jsonpath" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-931603ff/solution/solve.sh b/tasks/agentescape-15-skeleton-931603ff/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-931603ff/task.toml b/tasks/agentescape-15-skeleton-931603ff/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..91b17b757b9f80aff1a8147da70db5770fa9d982 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "72e22d923683d844cdecfd35ce3c773f981c01a54ee652abfdf576a0ee0c50b3" +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-15-skeleton-931603ff/tests/Dockerfile b/tasks/agentescape-15-skeleton-931603ff/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-931603ff/tests/expected.json b/tasks/agentescape-15-skeleton-931603ff/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..458625234be163941ee0ec9bdf6503221042451f --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "72e22d923683d844cdecfd35ce3c773f981c01a54ee652abfdf576a0ee0c50b3", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-931603ff/tests/grade.py b/tasks/agentescape-15-skeleton-931603ff/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/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-15-skeleton-931603ff/tests/test.sh b/tasks/agentescape-15-skeleton-931603ff/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-931603ff/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-93505631/environment/Dockerfile b/tasks/agentescape-15-skeleton-93505631/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-93505631/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/agent/cli.py b/tasks/agentescape-15-skeleton-93505631/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-93505631/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e056c46bde8bdaa50083b18aac26f8ec21b648f3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631-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-15-skeleton-93505631/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1497aa669b7a6c68adc9c0f96594d36cb8659db7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/scenario.json @@ -0,0 +1,948 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "zip_unzip_file", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_file", + "output_port": "files", + "output_type": "File_Id", + "description": "Execute Zip Unzipper and get the output from port 'files'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_file", + "json_get", + "terminal_2", + "calc_modexp", + "calc_modexp_df89", + "checksum_crc32", + "calc_modexp_60ff", + "container_4", + "calc_gcd_b2f8" + ], + "by_node": { + "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" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "calc_modexp_df89": { + "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": {} + }, + "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_60ff": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_gcd_b2f8": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_vault_8821.zip" + }, + "init_outputs": { + "files": "extracted_manifest_v4.bin" + } + }, + "json_get": { + "init_inputs": { + "file_id": "system_schema_config.json" + }, + "init_outputs": { + "values": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "$.access_control.credentials.password_hash", + "hex_result": "a4f2e8d1c0b3928a7156d4f3e2b1c099", + "math_token": "Verified mathematical sequence for cryptographic validation." + } + }, + "calc_modexp": { + "init_inputs": { + "base": "16" + }, + "init_outputs": {} + }, + "calc_modexp_df89": { + "init_inputs": { + "base": "2", + "exp": "882736451092837465019283746501", + "mod": "999983" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + }, + "init_outputs": {} + }, + "calc_modexp_60ff": { + "init_inputs": { + "base": "10", + "exp": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + }, + "init_outputs": {} + }, + "calc_gcd_b2f8": { + "init_inputs": { + "a": "293847561029384756102938475610", + "b": "384756102938475610293847561029" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The ash storms have finally subsided, revealing the entrance to Sector 7's central bunker. As a scrapper, you've heard legends about this place—it holds the coordinates to the last uncorrupted oasis on Earth. But the facility is dead, its systems fragmented and locked behind layers of post-apocalyptic security measures. You must reactivate the scattered machinery, route power through ancient generators, and bypass the bunker's mainframe to extract the final archives. Time is running out before the radiation levels spike again.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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_vault_8821.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_v4.bin" + } + ], + "init": { + "inputs": { + "zip_id": "archive_vault_8821.zip" + }, + "outputs": { + "files": "extracted_manifest_v4.bin" + } + }, + "narrative": "This is the Mainframe Archive Extractor. The final firewall blocking the bunker's secrets. It requires input from the Data Parser Module to bypass the lockdown." + }, + { + "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": "system_schema_config.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.access_control.credentials.password_hash" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + ], + "init": { + "inputs": { + "file_id": "system_schema_config.json" + }, + "outputs": { + "values": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + }, + "narrative": "This is the Data Parser Module. An automated script processor. It requires input from the Central Control Terminal to filter through the vast amount of corrupted logs." + }, + { + "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": "1072912117" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "855711" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "$.access_control.credentials.password_hash" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a4f2e8d1c0b3928a7156d4f3e2b1c099" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Verified mathematical sequence for cryptographic validation." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "$.access_control.credentials.password_hash", + "hex_result": "a4f2e8d1c0b3928a7156d4f3e2b1c099", + "math_token": "Verified mathematical sequence for cryptographic validation." + } + }, + "narrative": "This is the Central Control Terminal. The main bunker console. It requires inputs from both the Quantum Reversal Engine and the Power Amplifier to boot up." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "855711" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "27" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "855711" + } + ], + "narrative": "This is the Quantum Reversal Engine. A strange, pulsing machine. It requires inputs from the Signal Translator and the Frequency Synchronizer to operate." + }, + { + "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": "855711" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "411443100" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "855711" + } + ], + "narrative": "This is the Signal Translator. A complex decoding station. It requires inputs from the Frequency Synchronizer, the Primary Core Generator, and the Secondary Power Router." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "900000000090000000009" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "855711" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "27" + } + ], + "narrative": "This is the Frequency Synchronizer. A rusted antenna array. It requires inputs from both the Primary Core Generator and the Backup Frequency Emitter to stabilize." + }, + { + "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": "16" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "855711" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3087229729 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1072912117" + } + ], + "init": { + "inputs": { + "base": "16" + }, + "outputs": {} + }, + "narrative": "This is the Power Amplifier. A massive transformer unit. It requires inputs from both the Integrity Scanner and the Primary Core Generator to function safely." + }, + { + "id": "calc_modexp_df89", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "882736451092837465019283746501" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "855711" + } + ], + "init": { + "inputs": { + "base": "2", + "exp": "882736451092837465019283746501", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Primary Core Generator. A humming machine, barely functioning after the fallout, used to produce base energy sequences." + }, + { + "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": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b8036321" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3087229729 + } + ], + "init": { + "inputs": { + "hex": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + }, + "outputs": {} + }, + "narrative": "This is the Integrity Scanner. A handheld device used to scan for data corruption in wasteland tech." + }, + { + "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 Encrypted Log Drive. A small, heavily armored data storage device." + }, + { + "id": "calc_modexp_60ff", + "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": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "102938475610293847561029384756" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1072912117" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "411443100" + } + ], + "init": { + "inputs": { + "base": "10", + "exp": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Power Router. A series of thick, glowing cables. It requires input from the Power Amplifier to distribute the energy flow." + }, + { + "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": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + }, + "outputs": {} + }, + "narrative": "This is a Biometric Lockbox. A sealed container designed to keep its contents safe from scavengers." + }, + { + "id": "item_16_3d48", + "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 Access Keycard. A scratched security badge belonging to a former technician." + }, + { + "id": "item_16_1ef6", + "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 Rusted Toolbox. A heavy metal case covered in thick, radioactive dust." + }, + { + "id": "calc_gcd_b2f8", + "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": "293847561029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "384756102938475610293847561029" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "900000000090000000009" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938475610", + "b": "384756102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Backup Frequency Emitter. An old radio tower component emitting steady, rhythmic pulses." + } + ], + "edges": [ + { + "source_id": "json_get", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "password" + }, + { + "source_id": "terminal_2", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "jsonpath" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "json_get", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_60ff", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "container_4", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16_3d48", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_60ff", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "item_16_1ef6", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_gcd_b2f8", + "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-15-skeleton-93505631/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-93505631/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/instruction.md b/tasks/agentescape-15-skeleton-93505631/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/solution/oracle.py b/tasks/agentescape-15-skeleton-93505631/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/solution/scenario.json b/tasks/agentescape-15-skeleton-93505631/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1497aa669b7a6c68adc9c0f96594d36cb8659db7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/solution/scenario.json @@ -0,0 +1,948 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "zip_unzip_file", + "win_condition": { + "type": "tool_output", + "node_id": "zip_unzip_file", + "output_port": "files", + "output_type": "File_Id", + "description": "Execute Zip Unzipper and get the output from port 'files'" + }, + "source_init": { + "source_nodes": [ + "zip_unzip_file", + "json_get", + "terminal_2", + "calc_modexp", + "calc_modexp_df89", + "checksum_crc32", + "calc_modexp_60ff", + "container_4", + "calc_gcd_b2f8" + ], + "by_node": { + "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" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "calc_modexp_df89": { + "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": {} + }, + "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_60ff": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_gcd_b2f8": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + }, + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "zip_unzip_file": { + "init_inputs": { + "zip_id": "archive_vault_8821.zip" + }, + "init_outputs": { + "files": "extracted_manifest_v4.bin" + } + }, + "json_get": { + "init_inputs": { + "file_id": "system_schema_config.json" + }, + "init_outputs": { + "values": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "$.access_control.credentials.password_hash", + "hex_result": "a4f2e8d1c0b3928a7156d4f3e2b1c099", + "math_token": "Verified mathematical sequence for cryptographic validation." + } + }, + "calc_modexp": { + "init_inputs": { + "base": "16" + }, + "init_outputs": {} + }, + "calc_modexp_df89": { + "init_inputs": { + "base": "2", + "exp": "882736451092837465019283746501", + "mod": "999983" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + }, + "init_outputs": {} + }, + "calc_modexp_60ff": { + "init_inputs": { + "base": "10", + "exp": "102938475610293847561029384756" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + }, + "init_outputs": {} + }, + "calc_gcd_b2f8": { + "init_inputs": { + "a": "293847561029384756102938475610", + "b": "384756102938475610293847561029" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The ash storms have finally subsided, revealing the entrance to Sector 7's central bunker. As a scrapper, you've heard legends about this place—it holds the coordinates to the last uncorrupted oasis on Earth. But the facility is dead, its systems fragmented and locked behind layers of post-apocalyptic security measures. You must reactivate the scattered machinery, route power through ancient generators, and bypass the bunker's mainframe to extract the final archives. Time is running out before the radiation levels spike again.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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_vault_8821.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_v4.bin" + } + ], + "init": { + "inputs": { + "zip_id": "archive_vault_8821.zip" + }, + "outputs": { + "files": "extracted_manifest_v4.bin" + } + }, + "narrative": "This is the Mainframe Archive Extractor. The final firewall blocking the bunker's secrets. It requires input from the Data Parser Module to bypass the lockdown." + }, + { + "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": "system_schema_config.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.access_control.credentials.password_hash" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + ], + "init": { + "inputs": { + "file_id": "system_schema_config.json" + }, + "outputs": { + "values": "[\"$.node.private_key\", \"$.node.session_id\", \"$.node.auth_secret\"]" + } + }, + "narrative": "This is the Data Parser Module. An automated script processor. It requires input from the Central Control Terminal to filter through the vast amount of corrupted logs." + }, + { + "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": "1072912117" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "855711" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "$.access_control.credentials.password_hash" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a4f2e8d1c0b3928a7156d4f3e2b1c099" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Verified mathematical sequence for cryptographic validation." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "$.access_control.credentials.password_hash", + "hex_result": "a4f2e8d1c0b3928a7156d4f3e2b1c099", + "math_token": "Verified mathematical sequence for cryptographic validation." + } + }, + "narrative": "This is the Central Control Terminal. The main bunker console. It requires inputs from both the Quantum Reversal Engine and the Power Amplifier to boot up." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "855711" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "27" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "855711" + } + ], + "narrative": "This is the Quantum Reversal Engine. A strange, pulsing machine. It requires inputs from the Signal Translator and the Frequency Synchronizer to operate." + }, + { + "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": "855711" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "27" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "411443100" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "855711" + } + ], + "narrative": "This is the Signal Translator. A complex decoding station. It requires inputs from the Frequency Synchronizer, the Primary Core Generator, and the Secondary Power Router." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "900000000090000000009" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "855711" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "27" + } + ], + "narrative": "This is the Frequency Synchronizer. A rusted antenna array. It requires inputs from both the Primary Core Generator and the Backup Frequency Emitter to stabilize." + }, + { + "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": "16" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "855711" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 3087229729 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1072912117" + } + ], + "init": { + "inputs": { + "base": "16" + }, + "outputs": {} + }, + "narrative": "This is the Power Amplifier. A massive transformer unit. It requires inputs from both the Integrity Scanner and the Primary Core Generator to function safely." + }, + { + "id": "calc_modexp_df89", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "882736451092837465019283746501" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "855711" + } + ], + "init": { + "inputs": { + "base": "2", + "exp": "882736451092837465019283746501", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "This is the Primary Core Generator. A humming machine, barely functioning after the fallout, used to produce base energy sequences." + }, + { + "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": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b8036321" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3087229729 + } + ], + "init": { + "inputs": { + "hex": "da39a3ee5e6b4b0d3255bfef95601890afd80709" + }, + "outputs": {} + }, + "narrative": "This is the Integrity Scanner. A handheld device used to scan for data corruption in wasteland tech." + }, + { + "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 Encrypted Log Drive. A small, heavily armored data storage device." + }, + { + "id": "calc_modexp_60ff", + "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": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "102938475610293847561029384756" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1072912117" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "411443100" + } + ], + "init": { + "inputs": { + "base": "10", + "exp": "102938475610293847561029384756" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Power Router. A series of thick, glowing cables. It requires input from the Power Amplifier to distribute the energy flow." + }, + { + "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": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "sha256:7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1f" + }, + "outputs": {} + }, + "narrative": "This is a Biometric Lockbox. A sealed container designed to keep its contents safe from scavengers." + }, + { + "id": "item_16_3d48", + "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 Access Keycard. A scratched security badge belonging to a former technician." + }, + { + "id": "item_16_1ef6", + "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 Rusted Toolbox. A heavy metal case covered in thick, radioactive dust." + }, + { + "id": "calc_gcd_b2f8", + "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": "293847561029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "384756102938475610293847561029" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "900000000090000000009" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938475610", + "b": "384756102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Backup Frequency Emitter. An old radio tower component emitting steady, rhythmic pulses." + } + ], + "edges": [ + { + "source_id": "json_get", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "password" + }, + { + "source_id": "terminal_2", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "jsonpath" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "json_get", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_60ff", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "container_4", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16_3d48", + "target_id": "calc_gcd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_df89", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_60ff", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "item_16_1ef6", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_gcd_b2f8", + "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-15-skeleton-93505631/solution/solve.sh b/tasks/agentescape-15-skeleton-93505631/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-93505631/task.toml b/tasks/agentescape-15-skeleton-93505631/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aae295415c9960f8c59f1d6e3dfa1bbcbda6f215 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "8ee485ce3dade3d76ca432f002026ad30b237783a5cd06a9516fcbb2805c4e11" +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-15-skeleton-93505631/tests/Dockerfile b/tasks/agentescape-15-skeleton-93505631/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-93505631/tests/expected.json b/tasks/agentescape-15-skeleton-93505631/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..76dae74a0bc572d8798bbd100958ab3d1585aef8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "8ee485ce3dade3d76ca432f002026ad30b237783a5cd06a9516fcbb2805c4e11", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-93505631/tests/grade.py b/tasks/agentescape-15-skeleton-93505631/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/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-15-skeleton-93505631/tests/test.sh b/tasks/agentescape-15-skeleton-93505631/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-93505631/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-943e247d/environment/Dockerfile b/tasks/agentescape-15-skeleton-943e247d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-943e247d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/agent/cli.py b/tasks/agentescape-15-skeleton-943e247d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-943e247d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a6f18e999d82dd3d263037f7b9433d068e156f46 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d-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-15-skeleton-943e247d/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..a49c9ed68e0911dbed7419c7ae202215c1ed1be2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/scenario.json @@ -0,0 +1,938 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "calc_modexp", + "win_condition": { + "type": "tool_output", + "node_id": "calc_modexp", + "output_port": "value", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Exponentiation and get the output from port 'value'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp_0e62", + "num_base_convert", + "checksum_crc32_a7c9", + "calc_gcd_0d69", + "csv_query", + "graph_shortest_path", + "terminal_2" + ], + "by_node": { + "calc_modexp_0e62": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "checksum_crc32_a7c9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_gcd_0d69": { + "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": {} + }, + "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" + } + } + }, + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "calc_modexp_0e62": { + "init_inputs": { + "base": "8374928374651029384756102", + "exp": "1928374650912837465091283" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "16" + }, + "init_outputs": {} + }, + "checksum_crc32_a7c9": { + "init_inputs": { + "hex": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + }, + "init_outputs": {} + }, + "calc_gcd_0d69": { + "init_inputs": { + "a": "3847561029384756102938475", + "b": "9182736450918273645091827" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "customer_transactions_2023.csv", + "select": "transaction_id, customer_name, amount, status", + "where": "amount > 1000 AND status = 'completed'" + }, + "init_outputs": { + "rows": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "logistics_network_map.json", + "src": "Warehouse_North_A", + "dst": "Distribution_Center_Z" + }, + "init_outputs": { + "path": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]", + "cost": "850" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "7465839201746583920174658", + "num2": "1029384756102938475610293" + }, + "init_outputs": { + "text_result": "Calculation completed successfully; verification passed.", + "hex_result": "deadbeef1234567890abcdef" + } + } + }, + "intro_narrative": "You are a private investigator who has just broken into the abandoned Blackwood Research Facility. Rumors suggest this site was the headquarters of a notorious syndicate that left behind a complex web of interconnected security modules. The air is stale, and the hum of backup generators is the only sound. Your objective is to navigate through the darkened corridors, reactivate the dormant systems, and bypass the facility's layers of defense to crack the final vault. Keep your wits about you, as every machine and terminal is a piece of a larger puzzle.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 1378283405 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1378283405" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982424157" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "912188828" + } + ], + "narrative": "The Final Vault Lock. The massive steel door securing the syndicate's secrets. It requires inputs from The Signal Synchronizer, The Security Checkpoint, and The Mainframe Translator to finally open." + }, + { + "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": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1378283405 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1378283405" + } + ], + "narrative": "The Signal Synchronizer. A complex alignment console with blinking indicators. It requires inputs from both The Phase Inverter and The Security Checkpoint to align the facility's internal frequencies." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "0" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "narrative": "The Phase Inverter. A heavy piece of machinery that balances the electrical load. It requires inputs from both The Power Grid Controller and The Frequency Tuner to stabilize the network." + }, + { + "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": "924fdc3b7e55013bf0eb3f961e980fffbb72e40383a425c0b2bd4bdc4455ae7f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5226ef8d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1378283405 + } + ], + "narrative": "The Security Checkpoint. A fortified turnstile mechanism blocking the main hallway. It requires input from The Cryptographic Decoder to verify your clearance and allow passage." + }, + { + "id": "calc_modexp_0e62", + "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": "8374928374651029384756102" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1928374650912837465091283" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "8374928374651029384756102", + "exp": "1928374650912837465091283" + }, + "outputs": {} + }, + "narrative": "The Power Grid Controller. A breaker panel covered in warning labels. It requires input from The Frequency Tuner to route energy correctly through the sector." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Digital Keycard. A plastic card with a damaged magnetic stripe lying forgotten on a desk." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "924fdc3b7e55013bf0eb3f961e980fffbb72e40383a425c0b2bd4bdc4455ae7f" + } + ], + "narrative": "The Cryptographic Decoder. An advanced cipher machine sitting on a reinforced glass table. It requires input from The Employee Database Archive to decipher the underlying text." + }, + { + "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": 982424157 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "835060533450" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "982424157" + } + ], + "init": { + "inputs": { + "from_base": "16" + }, + "outputs": {} + }, + "narrative": "The Mainframe Translator. A server rack dedicated to formatting network commands. It requires inputs from both The Sector Amplifier and The Biometric Scanner to convert localized signals into mainframe instructions." + }, + { + "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": "850" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 982424157 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "835060533450" + } + ], + "narrative": "The Sector Amplifier. A large antenna array designed to boost local network signals. It requires inputs from both The Biometric Scanner and The Surveillance Mapper to function properly." + }, + { + "id": "checksum_crc32_a7c9", + "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": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3a8e9a5d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 982424157 + } + ], + "init": { + "inputs": { + "hex": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + }, + "outputs": {} + }, + "narrative": "The Biometric Scanner. A wall-mounted handprint reader that glow faintly in the dark." + }, + { + "id": "item_16_4777", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Master Override Chip. A small, sophisticated piece of hardware safely encased in a glass vial." + }, + { + "id": "calc_gcd_0d69", + "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": "3847561029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "9182736450918273645091827" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "init": { + "inputs": { + "a": "3847561029384756102938475", + "b": "9182736450918273645091827" + }, + "outputs": {} + }, + "narrative": "The Frequency Tuner. An old radio-like device used to pinpoint secure broadcast channels within the facility." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "customer_transactions_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, customer_name, amount, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 1000 AND status = 'completed'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + ], + "init": { + "inputs": { + "file_id": "customer_transactions_2023.csv", + "select": "transaction_id, customer_name, amount, status", + "where": "amount > 1000 AND status = 'completed'" + }, + "outputs": { + "rows": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + }, + "narrative": "The Employee Database Archive. An isolated server terminal containing the remaining personnel records of the Blackwood Facility." + }, + { + "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": "logistics_network_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Warehouse_North_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Distribution_Center_Z" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "850" + } + ], + "init": { + "inputs": { + "file_id": "logistics_network_map.json", + "src": "Warehouse_North_A", + "dst": "Distribution_Center_Z" + }, + "outputs": { + "path": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]", + "cost": "850" + } + }, + "narrative": "The Surveillance Mapper. An interactive digital map displaying the layout of the facility's security camera blind spots." + }, + { + "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": "7465839201746583920174658" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1029384756102938475610293" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation completed successfully; verification passed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "7465839201746583920174658", + "num2": "1029384756102938475610293" + }, + "outputs": { + "text_result": "Calculation completed successfully; verification passed.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "narrative": "The Reception Computer. A dusty, outdated terminal sitting on the front lobby desk." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "calc_modexp_0e62", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_a7c9", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "item_16_4777", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_a7c9", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "calc_gcd_0d69", + "target_id": "calc_modexp_0e62", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_0d69", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "csv_query", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-943e247d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/instruction.md b/tasks/agentescape-15-skeleton-943e247d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/solution/oracle.py b/tasks/agentescape-15-skeleton-943e247d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/solution/scenario.json b/tasks/agentescape-15-skeleton-943e247d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..a49c9ed68e0911dbed7419c7ae202215c1ed1be2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/solution/scenario.json @@ -0,0 +1,938 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "calc_modexp", + "win_condition": { + "type": "tool_output", + "node_id": "calc_modexp", + "output_port": "value", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Exponentiation and get the output from port 'value'" + }, + "source_init": { + "source_nodes": [ + "calc_modexp_0e62", + "num_base_convert", + "checksum_crc32_a7c9", + "calc_gcd_0d69", + "csv_query", + "graph_shortest_path", + "terminal_2" + ], + "by_node": { + "calc_modexp_0e62": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "checksum_crc32_a7c9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_gcd_0d69": { + "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": {} + }, + "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" + } + } + }, + "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" + } + } + }, + "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" + } + } + } + } + }, + "initial_values": { + "calc_modexp_0e62": { + "init_inputs": { + "base": "8374928374651029384756102", + "exp": "1928374650912837465091283" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "from_base": "16" + }, + "init_outputs": {} + }, + "checksum_crc32_a7c9": { + "init_inputs": { + "hex": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + }, + "init_outputs": {} + }, + "calc_gcd_0d69": { + "init_inputs": { + "a": "3847561029384756102938475", + "b": "9182736450918273645091827" + }, + "init_outputs": {} + }, + "csv_query": { + "init_inputs": { + "file_id": "customer_transactions_2023.csv", + "select": "transaction_id, customer_name, amount, status", + "where": "amount > 1000 AND status = 'completed'" + }, + "init_outputs": { + "rows": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "logistics_network_map.json", + "src": "Warehouse_North_A", + "dst": "Distribution_Center_Z" + }, + "init_outputs": { + "path": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]", + "cost": "850" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "7465839201746583920174658", + "num2": "1029384756102938475610293" + }, + "init_outputs": { + "text_result": "Calculation completed successfully; verification passed.", + "hex_result": "deadbeef1234567890abcdef" + } + } + }, + "intro_narrative": "You are a private investigator who has just broken into the abandoned Blackwood Research Facility. Rumors suggest this site was the headquarters of a notorious syndicate that left behind a complex web of interconnected security modules. The air is stale, and the hum of backup generators is the only sound. Your objective is to navigate through the darkened corridors, reactivate the dormant systems, and bypass the facility's layers of defense to crack the final vault. Keep your wits about you, as every machine and terminal is a piece of a larger puzzle.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": 1378283405 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1378283405" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982424157" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "912188828" + } + ], + "narrative": "The Final Vault Lock. The massive steel door securing the syndicate's secrets. It requires inputs from The Signal Synchronizer, The Security Checkpoint, and The Mainframe Translator to finally open." + }, + { + "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": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1378283405 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1378283405" + } + ], + "narrative": "The Signal Synchronizer. A complex alignment console with blinking indicators. It requires inputs from both The Phase Inverter and The Security Checkpoint to align the facility's internal frequencies." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "0" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "narrative": "The Phase Inverter. A heavy piece of machinery that balances the electrical load. It requires inputs from both The Power Grid Controller and The Frequency Tuner to stabilize the network." + }, + { + "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": "924fdc3b7e55013bf0eb3f961e980fffbb72e40383a425c0b2bd4bdc4455ae7f" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5226ef8d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1378283405 + } + ], + "narrative": "The Security Checkpoint. A fortified turnstile mechanism blocking the main hallway. It requires input from The Cryptographic Decoder to verify your clearance and allow passage." + }, + { + "id": "calc_modexp_0e62", + "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": "8374928374651029384756102" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1928374650912837465091283" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "8374928374651029384756102", + "exp": "1928374650912837465091283" + }, + "outputs": {} + }, + "narrative": "The Power Grid Controller. A breaker panel covered in warning labels. It requires input from The Frequency Tuner to route energy correctly through the sector." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Digital Keycard. A plastic card with a damaged magnetic stripe lying forgotten on a desk." + }, + { + "id": "hash_sha256", + "name": "SHA-256 Hasher", + "description": "SHA-256 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "924fdc3b7e55013bf0eb3f961e980fffbb72e40383a425c0b2bd4bdc4455ae7f" + } + ], + "narrative": "The Cryptographic Decoder. An advanced cipher machine sitting on a reinforced glass table. It requires input from The Employee Database Archive to decipher the underlying text." + }, + { + "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": 982424157 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "835060533450" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "982424157" + } + ], + "init": { + "inputs": { + "from_base": "16" + }, + "outputs": {} + }, + "narrative": "The Mainframe Translator. A server rack dedicated to formatting network commands. It requires inputs from both The Sector Amplifier and The Biometric Scanner to convert localized signals into mainframe instructions." + }, + { + "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": "850" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 982424157 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "835060533450" + } + ], + "narrative": "The Sector Amplifier. A large antenna array designed to boost local network signals. It requires inputs from both The Biometric Scanner and The Surveillance Mapper to function properly." + }, + { + "id": "checksum_crc32_a7c9", + "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": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3a8e9a5d" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 982424157 + } + ], + "init": { + "inputs": { + "hex": "4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d" + }, + "outputs": {} + }, + "narrative": "The Biometric Scanner. A wall-mounted handprint reader that glow faintly in the dark." + }, + { + "id": "item_16_4777", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Master Override Chip. A small, sophisticated piece of hardware safely encased in a glass vial." + }, + { + "id": "calc_gcd_0d69", + "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": "3847561029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "9182736450918273645091827" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "init": { + "inputs": { + "a": "3847561029384756102938475", + "b": "9182736450918273645091827" + }, + "outputs": {} + }, + "narrative": "The Frequency Tuner. An old radio-like device used to pinpoint secure broadcast channels within the facility." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "customer_transactions_2023.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, customer_name, amount, status" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 1000 AND status = 'completed'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + ], + "init": { + "inputs": { + "file_id": "customer_transactions_2023.csv", + "select": "transaction_id, customer_name, amount, status", + "where": "amount > 1000 AND status = 'completed'" + }, + "outputs": { + "rows": "[{\"id\": \"TXN_001\", \"amount\": 1500}, {\"id\": \"TXN_002\", \"amount\": 2300}, {\"id\": \"TXN_003\", \"amount\": 1100}, {\"id\": \"TXN_004\", \"amount\": 4500}]" + } + }, + "narrative": "The Employee Database Archive. An isolated server terminal containing the remaining personnel records of the Blackwood Facility." + }, + { + "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": "logistics_network_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Warehouse_North_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Distribution_Center_Z" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "850" + } + ], + "init": { + "inputs": { + "file_id": "logistics_network_map.json", + "src": "Warehouse_North_A", + "dst": "Distribution_Center_Z" + }, + "outputs": { + "path": "[\"Warehouse_North_A\", \"Transit_Hub_1\", \"Route_66_Checkpoint\", \"Cross_Dock_Facility\", \"Highway_Interchange_4\", \"Local_Depot_B\", \"Distribution_Center_Z\"]", + "cost": "850" + } + }, + "narrative": "The Surveillance Mapper. An interactive digital map displaying the layout of the facility's security camera blind spots." + }, + { + "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": "7465839201746583920174658" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1029384756102938475610293" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation completed successfully; verification passed." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "deadbeef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "7465839201746583920174658", + "num2": "1029384756102938475610293" + }, + "outputs": { + "text_result": "Calculation completed successfully; verification passed.", + "hex_result": "deadbeef1234567890abcdef" + } + }, + "narrative": "The Reception Computer. A dusty, outdated terminal sitting on the front lobby desk." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "calc_modexp_0e62", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32_a7c9", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "item_16_4777", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_a7c9", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "calc_gcd_0d69", + "target_id": "calc_modexp_0e62", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_0d69", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "csv_query", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-943e247d/solution/solve.sh b/tasks/agentescape-15-skeleton-943e247d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-943e247d/task.toml b/tasks/agentescape-15-skeleton-943e247d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0068780559455009d40a89893700b92f996fecf0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "b6e544d47f7d61444aa32d0b896c4f3b2b206db42a6857d631441977eee8d591" +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-15-skeleton-943e247d/tests/Dockerfile b/tasks/agentescape-15-skeleton-943e247d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-943e247d/tests/expected.json b/tasks/agentescape-15-skeleton-943e247d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..350d9600bf9248c0f524e2be75a74c0f3cb5330e --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "b6e544d47f7d61444aa32d0b896c4f3b2b206db42a6857d631441977eee8d591", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-943e247d/tests/grade.py b/tasks/agentescape-15-skeleton-943e247d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/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-15-skeleton-943e247d/tests/test.sh b/tasks/agentescape-15-skeleton-943e247d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-943e247d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-954a7e3c/environment/Dockerfile b/tasks/agentescape-15-skeleton-954a7e3c/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-954a7e3c/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/agent/cli.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-954a7e3c/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cc770ba9d0220853746a36fb68be4bce6e280699 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c-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-15-skeleton-954a7e3c/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..18491d66c45e2f0ea6558ca3e9674ce50fe7dbe7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/scenario.json @@ -0,0 +1,809 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "hash_sha256", + "win_condition": { + "type": "tool_output", + "node_id": "hash_sha256", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute SHA-256 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "item_7", + "zip_unzip_item", + "terminal_2", + "calc_gcd", + "hmac_sha256", + "calc_bigmul", + "graph_shortest_path" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + } + }, + "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": {} + }, + "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": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secured_payload_v4.zip" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Process initialization sequence complete. Ready for input.", + "hex_result": "a1b2c3d4e5f6789012345678abcdef12" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "837465192837465192837465" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "102938475610293847561029", + "b": "593847561059384756105938" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_graph_data.json", + "src": "Server_Alpha_01", + "dst": "Gateway_Node_99" + }, + "init_outputs": { + "path": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]", + "cost": "452910" + } + } + }, + "intro_narrative": "Welcome to the Clockwork Sanctum, the abandoned workshop of the legendary inventor Archimedes Vance. Surrounded by hissing steam pipes, rotating brass gears, and the heavy smell of machine oil and ozone, you have been sent to retrieve his final masterpiece. The workshop is powered by an interconnected web of mechanical logic engines, high-pressure vaults, and aetheric synthesizers. To uncover the sanctum's ultimate secret and escape before the primary boiler pressure reaches critical mass, you must trace the pneumatic tubes connecting the devices and operate his inventions in the precise intended sequence. The Final Verification Engine holds the key to your exit, but it remains locked behind layers of analog cryptography and steam-powered computation. Explore the sprawling lab, deduce the flow of information, and complete Vance's unfinished masterpiece.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "20000\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "0be508172e87a2af98f344d18610bbaaa0e6bbfcef0c7804b24457f839e129c9" + } + ], + "narrative": "This is the Final Verification Engine. It requires input from the Analytical Engine to distill the ultimate signature and complete your mission." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "20000\n" + } + ], + "narrative": "This is the Analytical Engine. It requires input from the perforated logic-scroll to execute its complex mechanical routines." + }, + { + "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, precisely machined brass cipher-key covered in intricate mathematical engravings." + }, + { + "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 calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + }, + "narrative": "A spool of stiff parchment known as the perforated logic-scroll, dotted with mechanical instructions." + }, + { + "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 temporal chronometer that seems to tick backwards, housed in a heavy brass casing." + }, + { + "id": "item_16_d2b7", + "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_3b4b9fbdab3b2881" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A delicately forged aetheric pocket-watch pulsing with a faint, rhythmic blue energy." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secured_payload_v4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u00157,6x\u001f\u00056{\u001faՒ\u0016/" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secured_payload_v4.zip" + }, + "outputs": {} + }, + "narrative": "This is the Pressure-Sealed Vault. It requires input from the Punch-Card Translator to release the heavy steam valves." + }, + { + "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": "3" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "452910" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Process initialization sequence complete. Ready for input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f6789012345678abcdef12" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Process initialization sequence complete. Ready for input.", + "hex_result": "a1b2c3d4e5f6789012345678abcdef12" + } + }, + "narrative": "This is the Master Control Console. It requires inputs from both the Harmonic Calibrator and the Navigational Orrery to function properly." + }, + { + "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": "cc15372c36a9a0fa9dd3781feb05ea36bf7b831f8e618cbed592ad9f162ffee4" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u00157,6x\u001f\u00056{\u001faՒ\u0016/" + } + ], + "narrative": "This is the Punch-Card Translator. It requires input from the Steam-Powered Cryptograph to decode the mechanical perforations." + }, + { + "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": "Process initialization sequence complete. Ready for input." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_3b4b9fbdab3b2881" + } + ], + "narrative": "This is the Aetheric Forge. It requires input from the Master Control Console to shape raw aether into solid form." + }, + { + "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": "837465192837465192837465" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "61129762680343964135457217755185211896844290202" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "837465192837465192837465" + }, + "outputs": {} + }, + "narrative": "This is the Harmonic Calibrator. It requires input from the brass Difference Engine to align its internal gear frequencies." + }, + { + "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": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Process initialization sequence complete. Ready for input." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "cc15372c36a9a0fa9dd3781feb05ea36bf7b831f8e618cbed592ad9f162ffee4" + } + ], + "init": { + "inputs": { + "hex_key": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + "outputs": {} + }, + "narrative": "This is the Steam-Powered Cryptograph. It requires input from the Master Control Console to stamp the cryptographic 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": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "102938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "593847561059384756105938" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "61129762680343964135457217755185211896844290202" + } + ], + "init": { + "inputs": { + "a": "102938475610293847561029", + "b": "593847561059384756105938" + }, + "outputs": {} + }, + "narrative": "A massive brass Difference Engine with interlocking gears. It whirs quietly, waiting to be operated." + }, + { + "id": "item_8_2486", + "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 perfectly balanced golden master artisan's gear, heavy and unnaturally warm to the touch." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Alpha_01" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Gateway_Node_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "452910" + } + ], + "init": { + "inputs": { + "file_id": "network_graph_data.json", + "src": "Server_Alpha_01", + "dst": "Gateway_Node_99" + }, + "outputs": { + "path": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]", + "cost": "452910" + } + }, + "narrative": "A spinning Navigational Orrery mapping the city's vast pneumatic tube network." + } + ], + "edges": [ + { + "source_id": "code_py_exec", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16_d2b7", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_d2b7", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + }, + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "hmac_sha256", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8_2486", + "target_id": "terminal_2", + "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": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-954a7e3c/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/instruction.md b/tasks/agentescape-15-skeleton-954a7e3c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/solution/oracle.py b/tasks/agentescape-15-skeleton-954a7e3c/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c/solution/scenario.json b/tasks/agentescape-15-skeleton-954a7e3c/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..18491d66c45e2f0ea6558ca3e9674ce50fe7dbe7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/solution/scenario.json @@ -0,0 +1,809 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "hash_sha256", + "win_condition": { + "type": "tool_output", + "node_id": "hash_sha256", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute SHA-256 Hasher and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "item_7", + "zip_unzip_item", + "terminal_2", + "calc_gcd", + "hmac_sha256", + "calc_bigmul", + "graph_shortest_path" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "hmac_sha256": { + "node_name": "HMAC-SHA256 Calculator", + "node_type": "Tool", + "template_id": "hmac_sha256", + "init_inputs": { + "hex_key": { + "type": "Hex_String", + "description": "Hex key" + } + }, + "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": {} + }, + "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": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "secured_payload_v4.zip" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Process initialization sequence complete. Ready for input.", + "hex_result": "a1b2c3d4e5f6789012345678abcdef12" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "837465192837465192837465" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "102938475610293847561029", + "b": "593847561059384756105938" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_graph_data.json", + "src": "Server_Alpha_01", + "dst": "Gateway_Node_99" + }, + "init_outputs": { + "path": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]", + "cost": "452910" + } + } + }, + "intro_narrative": "Welcome to the Clockwork Sanctum, the abandoned workshop of the legendary inventor Archimedes Vance. Surrounded by hissing steam pipes, rotating brass gears, and the heavy smell of machine oil and ozone, you have been sent to retrieve his final masterpiece. The workshop is powered by an interconnected web of mechanical logic engines, high-pressure vaults, and aetheric synthesizers. To uncover the sanctum's ultimate secret and escape before the primary boiler pressure reaches critical mass, you must trace the pneumatic tubes connecting the devices and operate his inventions in the precise intended sequence. The Final Verification Engine holds the key to your exit, but it remains locked behind layers of analog cryptography and steam-powered computation. Explore the sprawling lab, deduce the flow of information, and complete Vance's unfinished masterpiece.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "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": "20000\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "0be508172e87a2af98f344d18610bbaaa0e6bbfcef0c7804b24457f839e129c9" + } + ], + "narrative": "This is the Final Verification Engine. It requires input from the Analytical Engine to distill the ultimate signature and complete your mission." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "20000\n" + } + ], + "narrative": "This is the Analytical Engine. It requires input from the perforated logic-scroll to execute its complex mechanical routines." + }, + { + "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, precisely machined brass cipher-key covered in intricate mathematical engravings." + }, + { + "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 calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_value():\n x = 100\n y = 200\n return x * y\nprint(calculate_value())" + } + }, + "narrative": "A spool of stiff parchment known as the perforated logic-scroll, dotted with mechanical instructions." + }, + { + "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 temporal chronometer that seems to tick backwards, housed in a heavy brass casing." + }, + { + "id": "item_16_d2b7", + "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_3b4b9fbdab3b2881" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A delicately forged aetheric pocket-watch pulsing with a faint, rhythmic blue energy." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secured_payload_v4.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u00157,6x\u001f\u00056{\u001faՒ\u0016/" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "secured_payload_v4.zip" + }, + "outputs": {} + }, + "narrative": "This is the Pressure-Sealed Vault. It requires input from the Punch-Card Translator to release the heavy steam valves." + }, + { + "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": "3" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "452910" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Process initialization sequence complete. Ready for input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f6789012345678abcdef12" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Process initialization sequence complete. Ready for input.", + "hex_result": "a1b2c3d4e5f6789012345678abcdef12" + } + }, + "narrative": "This is the Master Control Console. It requires inputs from both the Harmonic Calibrator and the Navigational Orrery to function properly." + }, + { + "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": "cc15372c36a9a0fa9dd3781feb05ea36bf7b831f8e618cbed592ad9f162ffee4" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u00157,6x\u001f\u00056{\u001faՒ\u0016/" + } + ], + "narrative": "This is the Punch-Card Translator. It requires input from the Steam-Powered Cryptograph to decode the mechanical perforations." + }, + { + "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": "Process initialization sequence complete. Ready for input." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_3b4b9fbdab3b2881" + } + ], + "narrative": "This is the Aetheric Forge. It requires input from the Master Control Console to shape raw aether into solid form." + }, + { + "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": "837465192837465192837465" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "61129762680343964135457217755185211896844290202" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "a": "837465192837465192837465" + }, + "outputs": {} + }, + "narrative": "This is the Harmonic Calibrator. It requires input from the brass Difference Engine to align its internal gear frequencies." + }, + { + "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": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Process initialization sequence complete. Ready for input." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "cc15372c36a9a0fa9dd3781feb05ea36bf7b831f8e618cbed592ad9f162ffee4" + } + ], + "init": { + "inputs": { + "hex_key": "9f8e7d6c5b4a392817062534435261708192a3b4c5d6e7f8a9b0c1d2e3f4a5b6" + }, + "outputs": {} + }, + "narrative": "This is the Steam-Powered Cryptograph. It requires input from the Master Control Console to stamp the cryptographic 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": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "102938475610293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "593847561059384756105938" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "61129762680343964135457217755185211896844290202" + } + ], + "init": { + "inputs": { + "a": "102938475610293847561029", + "b": "593847561059384756105938" + }, + "outputs": {} + }, + "narrative": "A massive brass Difference Engine with interlocking gears. It whirs quietly, waiting to be operated." + }, + { + "id": "item_8_2486", + "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 perfectly balanced golden master artisan's gear, heavy and unnaturally warm to the touch." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "network_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Alpha_01" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Gateway_Node_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "452910" + } + ], + "init": { + "inputs": { + "file_id": "network_graph_data.json", + "src": "Server_Alpha_01", + "dst": "Gateway_Node_99" + }, + "outputs": { + "path": "[\"Server_Alpha_01\", \"Switch_Core_05\", \"Router_Backbone_02\", \"Gateway_Node_99\"]", + "cost": "452910" + } + }, + "narrative": "A spinning Navigational Orrery mapping the city's vast pneumatic tube network." + } + ], + "edges": [ + { + "source_id": "code_py_exec", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16_d2b7", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "zip_unzip_item", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16_d2b7", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num1" + }, + { + "source_id": "terminal_2", + "target_id": "matter_synthesizer", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "blueprint" + }, + { + "source_id": "hmac_sha256", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "text" + }, + { + "source_id": "item_8_2486", + "target_id": "terminal_2", + "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": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-954a7e3c/solution/solve.sh b/tasks/agentescape-15-skeleton-954a7e3c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-954a7e3c/task.toml b/tasks/agentescape-15-skeleton-954a7e3c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ebccd5e7c18d80bd16242955a8fbc38f0199ab0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-15-skeleton-954a7e3c" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "55c5a6fba6bb280786f06cfb77c665ac27909ad03dfe42cb8708189dd136e5a5" +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-15-skeleton-954a7e3c/tests/Dockerfile b/tasks/agentescape-15-skeleton-954a7e3c/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-954a7e3c/tests/expected.json b/tasks/agentescape-15-skeleton-954a7e3c/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..c6586c222d6f35190010fb9457e3c949d656d808 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "55c5a6fba6bb280786f06cfb77c665ac27909ad03dfe42cb8708189dd136e5a5", "max_actions": 500} \ No newline at end of file