diff --git a/tasks/agentescape-15-skeleton-954a7e3c/tests/grade.py b/tasks/agentescape-15-skeleton-954a7e3c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/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-954a7e3c/tests/test.sh b/tasks/agentescape-15-skeleton-954a7e3c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-954a7e3c/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-99479deb/environment/Dockerfile b/tasks/agentescape-15-skeleton-99479deb/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-99479deb/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/agent/cli.py b/tasks/agentescape-15-skeleton-99479deb/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-99479deb/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7e9cfe0adc585cfac7d24afb549be052cb6cbc24 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb-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-99479deb/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..86701b1887208758f0383681df0571c1e670dad3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 26, + "win_node_id": "calc_inv_mod", + "win_condition": { + "type": "tool_output", + "node_id": "calc_inv_mod", + "output_port": "inv", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Inverse and get the output from port 'inv'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert_fae4", + "terminal_2", + "checksum_crc32", + "graph_shortest_path", + "calc_gcd_d0a4", + "num_base_convert_f03f", + "base64_encode", + "container_2" + ], + "by_node": { + "num_base_convert_fae4": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "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" + } + } + }, + "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": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_gcd_d0a4": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_f03f": { + "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": {} + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert_fae4": { + "init_inputs": { + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initialization sequence complete. Standby for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f67890123456789abcdef0" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "city_grid_v5.json", + "dst": "Sector_7G" + }, + "init_outputs": { + "path": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]", + "cost": "34982" + } + }, + "calc_gcd_d0a4": { + "init_inputs": { + "a": "847261539402837465192837465019" + }, + "init_outputs": {} + }, + "num_base_convert_f03f": { + "init_inputs": { + "s": "592837461029384756102938475610", + "from_base": "10" + }, + "init_outputs": {} + }, + "base64_encode": { + "init_inputs": { + "hex": "cafebabedeadbeef0123456789abcdef" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "ff00ee11dd22cc33bb44aa5599668877" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of Blackwood Manor, the former workshop of a notoriously reclusive cryptographer who vanished decades ago. The heavy steel door behind you is hermetically sealed. Dominating the center of the room is a massive, menacing mechanical vault door, humming with a strange, latent energy. Scattered across the decaying workbenches are various cryptic machines, interconnected by a chaotic web of thick cables and glowing data lines. Your only hope of escape is to unravel this complex network of devices, restoring the flow of information to eventually power up the master override mechanism. Time is ticking, and the shadows in the corners of the room seem to grow longer by the minute.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "34982" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Master Override Switch. The final, imposing mechanism controlling the main vault door. It requires inputs from The Tertiary Decoder and The Final Decoder to secure your escape." + }, + { + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2809552065 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "34982" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Tertiary Decoder. A sleek modern tablet connected to a mess of thick wires. It requires inputs from The Secondary Decoder, The Cryptographic Core, and The Digital Fingerprinter." + }, + { + "id": "num_base_convert_fae4", + "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": "34982" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "34982" + } + ], + "init": { + "inputs": { + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Final Decoder. A pristine quantum processing unit encased in glass. It requires input from The Map Analyzer." + }, + { + "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": "592837461029384756102938475610" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "291943375485759643570087127445" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initialization sequence complete. Standby 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" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initialization sequence complete. Standby for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Console. An imposing server rack with a single blinking green cursor. It requires inputs from The Power Amplifier and The Reversal Engine." + }, + { + "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": 2809552065 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "291943375485759643570087127445" + } + ], + "narrative": "The Power Amplifier. A massive, sparking capacitor bank. It requires inputs from The Reversal Engine, The Tertiary Decoder, and The Digital Fingerprinter." + }, + { + "id": "calc_inv_mod_d8fa", + "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": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Reversal Engine. A complex set of counter-rotating gears and logic boards. It requires inputs from The Tertiary Decoder and The Primary Decoder." + }, + { + "id": "num_base_convert_3c02", + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 2809552065 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Secondary Decoder. A modified wartime cipher machine. It requires inputs from The Digital Fingerprinter, The Signal Comparator, and The Primary Decoder." + }, + { + "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": "a1b2c3d4e5f67890123456789abcdef0" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a7765cc1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2809552065 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f67890123456789abcdef0" + }, + "outputs": {} + }, + "narrative": "The Digital Fingerprinter. A dusty biometric scanner that hums quietly with standby power." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "city_grid_v5.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "yv66vt6tvu8BI0VniavN7w==" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7G" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "34982" + } + ], + "init": { + "inputs": { + "file_id": "city_grid_v5.json", + "dst": "Sector_7G" + }, + "outputs": { + "path": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]", + "cost": "34982" + } + }, + "narrative": "The Map Analyzer. A glowing interactive cartography table. It requires input from The Symbol Translator." + }, + { + "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": 2809552065 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "34982" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Signal Comparator. A dual-screen oscilloscope. It requires inputs from The Cryptographic Core and The Digital Fingerprinter." + }, + { + "id": "calc_modexp_a542", + "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": "34982" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2809552065 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "34982" + } + ], + "narrative": "The Cryptographic Core. A pulsating crystal matrix. It requires inputs from The Digital Fingerprinter, The Resonance Tuner, and The Map Analyzer." + }, + { + "id": "calc_gcd_d0a4", + "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": "847261539402837465192837465019" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "847261539402837465192837465019" + }, + "outputs": {} + }, + "narrative": "The Resonance Tuner. An antique radio frequency modulator. It requires input from The Primary Decoder." + }, + { + "id": "num_base_convert_f03f", + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "34982" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "init": { + "inputs": { + "s": "592837461029384756102938475610", + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Primary Decoder. A heavy mechanical cipher wheel. It requires input from The Map Analyzer." + }, + { + "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": "cafebabedeadbeef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "yv66vt6tvu8BI0VniavN7w==" + } + ], + "init": { + "inputs": { + "hex": "cafebabedeadbeef0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "The Symbol Translator. An old brass typewriter retrofitted with a glowing digital screen." + }, + { + "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": "ff00ee11dd22cc33bb44aa5599668877" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "ff00ee11dd22cc33bb44aa5599668877" + }, + "outputs": {} + }, + "narrative": "The Lead-Lined Lockbox. A heavy, secure container sealed with an advanced electronic clasp." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_fae4", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "terminal_2", + "target_id": "num_base_convert_fae4", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_d8fa", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_d8fa", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_d8fa", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_3c02", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_fae4", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_a542", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp_a542", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd_d0a4", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "calc_gcd_d0a4", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "calc_inv_mod_d8fa", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_f03f", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "num_base_convert_3c02", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-99479deb/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/instruction.md b/tasks/agentescape-15-skeleton-99479deb/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/solution/oracle.py b/tasks/agentescape-15-skeleton-99479deb/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/solution/scenario.json b/tasks/agentescape-15-skeleton-99479deb/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..86701b1887208758f0383681df0571c1e670dad3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/solution/scenario.json @@ -0,0 +1,995 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 26, + "win_node_id": "calc_inv_mod", + "win_condition": { + "type": "tool_output", + "node_id": "calc_inv_mod", + "output_port": "inv", + "output_type": "Big_Int", + "description": "Execute BigInt Modular Inverse and get the output from port 'inv'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert_fae4", + "terminal_2", + "checksum_crc32", + "graph_shortest_path", + "calc_gcd_d0a4", + "num_base_convert_f03f", + "base64_encode", + "container_2" + ], + "by_node": { + "num_base_convert_fae4": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "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" + } + } + }, + "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": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "calc_gcd_d0a4": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "num_base_convert_f03f": { + "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": {} + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert_fae4": { + "init_inputs": { + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Initialization sequence complete. Standby for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "a1b2c3d4e5f67890123456789abcdef0" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "city_grid_v5.json", + "dst": "Sector_7G" + }, + "init_outputs": { + "path": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]", + "cost": "34982" + } + }, + "calc_gcd_d0a4": { + "init_inputs": { + "a": "847261539402837465192837465019" + }, + "init_outputs": {} + }, + "num_base_convert_f03f": { + "init_inputs": { + "s": "592837461029384756102938475610", + "from_base": "10" + }, + "init_outputs": {} + }, + "base64_encode": { + "init_inputs": { + "hex": "cafebabedeadbeef0123456789abcdef" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "ff00ee11dd22cc33bb44aa5599668877" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of Blackwood Manor, the former workshop of a notoriously reclusive cryptographer who vanished decades ago. The heavy steel door behind you is hermetically sealed. Dominating the center of the room is a massive, menacing mechanical vault door, humming with a strange, latent energy. Scattered across the decaying workbenches are various cryptic machines, interconnected by a chaotic web of thick cables and glowing data lines. Your only hope of escape is to unravel this complex network of devices, restoring the flow of information to eventually power up the master override mechanism. Time is ticking, and the shadows in the corners of the room seem to grow longer by the minute.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "34982" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Master Override Switch. The final, imposing mechanism controlling the main vault door. It requires inputs from The Tertiary Decoder and The Final Decoder to secure your escape." + }, + { + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2809552065 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "34982" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Tertiary Decoder. A sleek modern tablet connected to a mess of thick wires. It requires inputs from The Secondary Decoder, The Cryptographic Core, and The Digital Fingerprinter." + }, + { + "id": "num_base_convert_fae4", + "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": "34982" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "34982" + } + ], + "init": { + "inputs": { + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Final Decoder. A pristine quantum processing unit encased in glass. It requires input from The Map Analyzer." + }, + { + "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": "592837461029384756102938475610" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "291943375485759643570087127445" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Initialization sequence complete. Standby 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" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Initialization sequence complete. Standby for data stream.", + "hex_result": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Console. An imposing server rack with a single blinking green cursor. It requires inputs from The Power Amplifier and The Reversal Engine." + }, + { + "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": 2809552065 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "291943375485759643570087127445" + } + ], + "narrative": "The Power Amplifier. A massive, sparking capacitor bank. It requires inputs from The Reversal Engine, The Tertiary Decoder, and The Digital Fingerprinter." + }, + { + "id": "calc_inv_mod_d8fa", + "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": "592837461029384756102938475610" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Reversal Engine. A complex set of counter-rotating gears and logic boards. It requires inputs from The Tertiary Decoder and The Primary Decoder." + }, + { + "id": "num_base_convert_3c02", + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": 2809552065 + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "narrative": "The Secondary Decoder. A modified wartime cipher machine. It requires inputs from The Digital Fingerprinter, The Signal Comparator, and The Primary Decoder." + }, + { + "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": "a1b2c3d4e5f67890123456789abcdef0" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a7765cc1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2809552065 + } + ], + "init": { + "inputs": { + "hex": "a1b2c3d4e5f67890123456789abcdef0" + }, + "outputs": {} + }, + "narrative": "The Digital Fingerprinter. A dusty biometric scanner that hums quietly with standby power." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "city_grid_v5.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "yv66vt6tvu8BI0VniavN7w==" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7G" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "34982" + } + ], + "init": { + "inputs": { + "file_id": "city_grid_v5.json", + "dst": "Sector_7G" + }, + "outputs": { + "path": "[\"HQ_Hub\", \"Relay_Alpha\", \"Junction_42\", \"Sector_7G\"]", + "cost": "34982" + } + }, + "narrative": "The Map Analyzer. A glowing interactive cartography table. It requires input from The Symbol Translator." + }, + { + "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": 2809552065 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "34982" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Signal Comparator. A dual-screen oscilloscope. It requires inputs from The Cryptographic Core and The Digital Fingerprinter." + }, + { + "id": "calc_modexp_a542", + "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": "34982" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2809552065 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "34982" + } + ], + "narrative": "The Cryptographic Core. A pulsating crystal matrix. It requires inputs from The Digital Fingerprinter, The Resonance Tuner, and The Map Analyzer." + }, + { + "id": "calc_gcd_d0a4", + "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": "847261539402837465192837465019" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "592837461029384756102938475610" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "847261539402837465192837465019" + }, + "outputs": {} + }, + "narrative": "The Resonance Tuner. An antique radio frequency modulator. It requires input from The Primary Decoder." + }, + { + "id": "num_base_convert_f03f", + "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": "592837461029384756102938475610" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "34982" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "592837461029384756102938475610" + } + ], + "init": { + "inputs": { + "s": "592837461029384756102938475610", + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Primary Decoder. A heavy mechanical cipher wheel. It requires input from The Map Analyzer." + }, + { + "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": "cafebabedeadbeef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "yv66vt6tvu8BI0VniavN7w==" + } + ], + "init": { + "inputs": { + "hex": "cafebabedeadbeef0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "The Symbol Translator. An old brass typewriter retrofitted with a glowing digital screen." + }, + { + "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": "ff00ee11dd22cc33bb44aa5599668877" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "ff00ee11dd22cc33bb44aa5599668877" + }, + "outputs": {} + }, + "narrative": "The Lead-Lined Lockbox. A heavy, secure container sealed with an advanced electronic clasp." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_fae4", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "terminal_2", + "target_id": "num_base_convert_fae4", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_d8fa", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_d8fa", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod_d8fa", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_3c02", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_fae4", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_a542", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "calc_modexp_a542", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd_d0a4", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "num_base_convert_3c02", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "calc_gcd_d0a4", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_a542", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "num_base_convert_f03f", + "target_id": "calc_inv_mod_d8fa", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_f03f", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "src" + }, + { + "source_id": "container_2", + "target_id": "num_base_convert_3c02", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-99479deb/solution/solve.sh b/tasks/agentescape-15-skeleton-99479deb/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-99479deb/task.toml b/tasks/agentescape-15-skeleton-99479deb/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e917404140cc0f0ca84ce512eaa2c4fa939f941c --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "e820a58e4d99d80b86db8611d3a5b75a513bdc7819e8efd43f531e9c407e73c5" +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-99479deb/tests/Dockerfile b/tasks/agentescape-15-skeleton-99479deb/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-99479deb/tests/expected.json b/tasks/agentescape-15-skeleton-99479deb/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..59f9f4ed7548071ee45390f819bcc0f4e5b8c0dd --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "e820a58e4d99d80b86db8611d3a5b75a513bdc7819e8efd43f531e9c407e73c5", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-99479deb/tests/grade.py b/tasks/agentescape-15-skeleton-99479deb/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/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-99479deb/tests/test.sh b/tasks/agentescape-15-skeleton-99479deb/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-99479deb/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-a267e7bf/environment/Dockerfile b/tasks/agentescape-15-skeleton-a267e7bf/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-a267e7bf/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/agent/cli.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-a267e7bf/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9f973c536aa53b3c07a012458d6753beb9c084d --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf-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-a267e7bf/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bca14ee87a7a019793fa3f8dab7488f88341c3df --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/scenario.json @@ -0,0 +1,897 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "zlib_deflate", + "win_condition": { + "type": "tool_output", + "node_id": "zlib_deflate", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Zlib Deflate and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "zip_unzip_file", + "zip_unzip_file_9f8b", + "regex_search", + "zip_unzip_file_b3a1", + "json_get", + "checksum_crc32", + "regex_search_b430", + "container_2" + ], + "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_9f8b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": {}, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "zip_unzip_file_b3a1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + }, + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "regex_search_b430": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "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": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "inventory_data_sheet.csv" + } + }, + "zip_unzip_file_9f8b": { + "init_inputs": {}, + "init_outputs": { + "files": "secure_payload_v2.zip" + } + }, + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"S3cur3P@ssw0rd!\"]" + } + }, + "zip_unzip_file_b3a1": { + "init_inputs": { + "zip_id": "master_archive_2024.zip" + }, + "init_outputs": { + "files": "internal_docs_bundle.zip" + } + }, + "json_get": { + "init_inputs": { + "file_id": "app_config_production.json", + "jsonpath": "$.system.settings.export_path" + }, + "init_outputs": { + "values": "[\"/var/data/exports/2024/summary.txt\"]" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + }, + "init_outputs": {} + }, + "regex_search_b430": { + "init_inputs": { + "pattern": "(?<=Error_Code:)\\d{4}", + "file_id": "system_error_logs.txt", + "text": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + }, + "init_outputs": { + "matches": "[\"4004\"]" + } + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit office of a disgraced private investigator who vanished weeks ago. Rain lashes against the frosted glass window, casting distorted shadows across a chaotic array of retro-tech machines and locked archives. The investigator was on the verge of uncovering a city-wide conspiracy, and now the culprits are coming for you. Your only way out is to piece together the evidence left behind, navigate the interconnected systems, and send out the final compressed distress signal before they breach the door. Time is running out.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789ccb4cd12928ca4f294d2e01d299c9a95c8606863ae19929e9a925f18e3a46a67aa6064021239890938e89819e0148c81826e4ac6368aa676e0a0044011514" + } + ], + "narrative": "The Master Compressor. It requires input from the Suspect Database to generate the final transmission code and secure your escape." + }, + { + "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": "inventory_data_sheet.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "_)a" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "eJyLVtIvSyzST0ksSdRPrSjILyop1jcyMDLRLy7NzU0sqtQrqShRigUA/mINRA==" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + }, + "narrative": "The precinct's Suspect Database terminal. It requires inputs from the Cipher Translator, the Signal Encoder, and the Main Evidence Archive to run a full background check." + }, + { + "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": "5f29d461" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "_)a" + } + ], + "narrative": "A dusty Cipher Translator. It requires input from the Integrity Scanner to function properly and reveal hidden meanings." + }, + { + "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": "789c8b56d22f4b2cd24f492c49d44fad28c82f2a29d637323032d12f2ecdcd4d2caad42ba928518a0500fe620d44" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJyLVtIvSyzST0ksSdRPrSjILyop1jcyMDLRLy7NzU0sqtQrqShRigUA/mINRA==" + } + ], + "narrative": "A retro Signal Encoder. It requires input from the Data Minimizer to broadcast the signal securely." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "inventory_data_sheet.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "inventory_data_sheet.csv" + } + }, + "narrative": "The Main Evidence Archive of the agency. It requires inputs from the Text Purifier and the Secondary Evidence Archive to grant access to the most crucial files." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "_)a" + } + ], + "narrative": "A specialized Text Purifier. It requires input from the Cipher Translator to clear out anomalies from the documents." + }, + { + "id": "zip_unzip_file_9f8b", + "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": "internal_docs_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"S3cur3P@ssw0rd!\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "secure_payload_v2.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "secure_payload_v2.zip" + } + }, + "narrative": "A secure Secondary Evidence Archive. It requires inputs from the Pattern Analyzer and the Initial Evidence Archive to proceed." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An antique silver pocket watch resting on the detective's desk." + }, + { + "id": "zlib_deflate_ddfd", + "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": "[\"/var/data/exports/2024/summary.txt\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56d22f4b2cd24f492c49d44fad28c82f2a29d637323032d12f2ecdcd4d2caad42ba928518a0500fe620d44" + } + ], + "narrative": "An industrial Data Minimizer. It requires input from the Digital Ledger to condense the sprawling financial records." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "_)a" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "internal_docs_bundle.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"4004\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"S3cur3P@ssw0rd!\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"S3cur3P@ssw0rd!\"]" + } + }, + "narrative": "An advanced Pattern Analyzer. It requires inputs from the Text Purifier, the Initial Evidence Archive, and the Document Scanner to compile a complete profile." + }, + { + "id": "zip_unzip_file_b3a1", + "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": "master_archive_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_docs_bundle.zip" + } + ], + "init": { + "inputs": { + "zip_id": "master_archive_2024.zip" + }, + "outputs": { + "files": "internal_docs_bundle.zip" + } + }, + "narrative": "An encrypted Initial Evidence Archive. It requires input from the Cipher Translator to unlock its contents." + }, + { + "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": "app_config_production.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.system.settings.export_path" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"/var/data/exports/2024/summary.txt\"]" + } + ], + "init": { + "inputs": { + "file_id": "app_config_production.json", + "jsonpath": "$.system.settings.export_path" + }, + "outputs": { + "values": "[\"/var/data/exports/2024/summary.txt\"]" + } + }, + "narrative": "An old Digital Ledger abandoned on the desk, filled with cryptic transactions." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5f29d461" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1596576865 + } + ], + "init": { + "inputs": { + "hex": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + }, + "outputs": {} + }, + "narrative": "A handheld Integrity Scanner used for verifying raw data integrity." + }, + { + "id": "regex_search_b430", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "(?<=Error_Code:)\\d{4}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "system_error_logs.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"4004\"]" + } + ], + "init": { + "inputs": { + "pattern": "(?<=Error_Code:)\\d{4}", + "file_id": "system_error_logs.txt", + "text": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + }, + "outputs": { + "matches": "[\"4004\"]" + } + }, + "narrative": "A portable Document Scanner used for finding specific keywords in physical paperwork." + }, + { + "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": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A heavy Locked Briefcase with a biometric lock." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "b64", + "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": "text_bidi_sanitize", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_9f8b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hex_decode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zlib_deflate_ddfd", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "regex_search", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "pattern" + }, + { + "source_id": "zip_unzip_file_b3a1", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "json_get", + "target_id": "zlib_deflate_ddfd", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file_b3a1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_b3a1", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "regex_search_b430", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "regex_search_b430", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-a267e7bf/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/instruction.md b/tasks/agentescape-15-skeleton-a267e7bf/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/solution/oracle.py b/tasks/agentescape-15-skeleton-a267e7bf/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/solution/scenario.json b/tasks/agentescape-15-skeleton-a267e7bf/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bca14ee87a7a019793fa3f8dab7488f88341c3df --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/solution/scenario.json @@ -0,0 +1,897 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "zlib_deflate", + "win_condition": { + "type": "tool_output", + "node_id": "zlib_deflate", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Zlib Deflate and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "csv_query", + "zip_unzip_file", + "zip_unzip_file_9f8b", + "regex_search", + "zip_unzip_file_b3a1", + "json_get", + "checksum_crc32", + "regex_search_b430", + "container_2" + ], + "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_9f8b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": {}, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "zip_unzip_file_b3a1": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "JSON file ID" + }, + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "regex_search_b430": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "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": { + "csv_query": { + "init_inputs": {}, + "init_outputs": { + "rows": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "inventory_data_sheet.csv" + } + }, + "zip_unzip_file_9f8b": { + "init_inputs": {}, + "init_outputs": { + "files": "secure_payload_v2.zip" + } + }, + "regex_search": { + "init_inputs": {}, + "init_outputs": { + "matches": "[\"S3cur3P@ssw0rd!\"]" + } + }, + "zip_unzip_file_b3a1": { + "init_inputs": { + "zip_id": "master_archive_2024.zip" + }, + "init_outputs": { + "files": "internal_docs_bundle.zip" + } + }, + "json_get": { + "init_inputs": { + "file_id": "app_config_production.json", + "jsonpath": "$.system.settings.export_path" + }, + "init_outputs": { + "values": "[\"/var/data/exports/2024/summary.txt\"]" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + }, + "init_outputs": {} + }, + "regex_search_b430": { + "init_inputs": { + "pattern": "(?<=Error_Code:)\\d{4}", + "file_id": "system_error_logs.txt", + "text": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + }, + "init_outputs": { + "matches": "[\"4004\"]" + } + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit office of a disgraced private investigator who vanished weeks ago. Rain lashes against the frosted glass window, casting distorted shadows across a chaotic array of retro-tech machines and locked archives. The investigator was on the verge of uncovering a city-wide conspiracy, and now the culprits are coming for you. Your only way out is to piece together the evidence left behind, navigate the interconnected systems, and send out the final compressed distress signal before they breach the door. Time is running out.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789ccb4cd12928ca4f294d2e01d299c9a95c8606863ae19929e9a925f18e3a46a67aa6064021239890938e89819e0148c81826e4ac6368aa676e0a0044011514" + } + ], + "narrative": "The Master Compressor. It requires input from the Suspect Database to generate the final transmission code and secure your escape." + }, + { + "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": "inventory_data_sheet.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "_)a" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "eJyLVtIvSyzST0ksSdRPrSjILyop1jcyMDLRLy7NzU0sqtQrqShRigUA/mINRA==" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + ], + "init": { + "inputs": {}, + "outputs": { + "rows": "id,product,price\n101,Widget_A,25.50\n102,Widget_B,40.00\n103,Widget_C,15.75" + } + }, + "narrative": "The precinct's Suspect Database terminal. It requires inputs from the Cipher Translator, the Signal Encoder, and the Main Evidence Archive to run a full background check." + }, + { + "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": "5f29d461" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "_)a" + } + ], + "narrative": "A dusty Cipher Translator. It requires input from the Integrity Scanner to function properly and reveal hidden meanings." + }, + { + "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": "789c8b56d22f4b2cd24f492c49d44fad28c82f2a29d637323032d12f2ecdcd4d2caad42ba928518a0500fe620d44" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJyLVtIvSyzST0ksSdRPrSjILyop1jcyMDLRLy7NzU0sqtQrqShRigUA/mINRA==" + } + ], + "narrative": "A retro Signal Encoder. It requires input from the Data Minimizer to broadcast the signal securely." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_payload_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "inventory_data_sheet.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "inventory_data_sheet.csv" + } + }, + "narrative": "The Main Evidence Archive of the agency. It requires inputs from the Text Purifier and the Secondary Evidence Archive to grant access to the most crucial files." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "_)a" + } + ], + "narrative": "A specialized Text Purifier. It requires input from the Cipher Translator to clear out anomalies from the documents." + }, + { + "id": "zip_unzip_file_9f8b", + "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": "internal_docs_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"S3cur3P@ssw0rd!\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "secure_payload_v2.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "secure_payload_v2.zip" + } + }, + "narrative": "A secure Secondary Evidence Archive. It requires inputs from the Pattern Analyzer and the Initial Evidence Archive to proceed." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An antique silver pocket watch resting on the detective's desk." + }, + { + "id": "zlib_deflate_ddfd", + "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": "[\"/var/data/exports/2024/summary.txt\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c8b56d22f4b2cd24f492c49d44fad28c82f2a29d637323032d12f2ecdcd4d2caad42ba928518a0500fe620d44" + } + ], + "narrative": "An industrial Data Minimizer. It requires input from the Digital Ledger to condense the sprawling financial records." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "_)a" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "internal_docs_bundle.zip" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "[\"4004\"]" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"S3cur3P@ssw0rd!\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "matches": "[\"S3cur3P@ssw0rd!\"]" + } + }, + "narrative": "An advanced Pattern Analyzer. It requires inputs from the Text Purifier, the Initial Evidence Archive, and the Document Scanner to compile a complete profile." + }, + { + "id": "zip_unzip_file_b3a1", + "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": "master_archive_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "_)a" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_docs_bundle.zip" + } + ], + "init": { + "inputs": { + "zip_id": "master_archive_2024.zip" + }, + "outputs": { + "files": "internal_docs_bundle.zip" + } + }, + "narrative": "An encrypted Initial Evidence Archive. It requires input from the Cipher Translator to unlock its contents." + }, + { + "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": "app_config_production.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.system.settings.export_path" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"/var/data/exports/2024/summary.txt\"]" + } + ], + "init": { + "inputs": { + "file_id": "app_config_production.json", + "jsonpath": "$.system.settings.export_path" + }, + "outputs": { + "values": "[\"/var/data/exports/2024/summary.txt\"]" + } + }, + "narrative": "An old Digital Ledger abandoned on the desk, filled with cryptic transactions." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "5f29d461" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1596576865 + } + ], + "init": { + "inputs": { + "hex": "4c6f72656d20697073756d20646f6c6f722073697420616d6574" + }, + "outputs": {} + }, + "narrative": "A handheld Integrity Scanner used for verifying raw data integrity." + }, + { + "id": "regex_search_b430", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "(?<=Error_Code:)\\d{4}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "system_error_logs.txt" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"4004\"]" + } + ], + "init": { + "inputs": { + "pattern": "(?<=Error_Code:)\\d{4}", + "file_id": "system_error_logs.txt", + "text": "Timestamp: 2023-11-15 08:30:00 | Error_Code:4004 | Status: Critical" + }, + "outputs": { + "matches": "[\"4004\"]" + } + }, + "narrative": "A portable Document Scanner used for finding specific keywords in physical paperwork." + }, + { + "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": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "a1b2c3d4e5f678901234567890abcdef1234567890abcdef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "A heavy Locked Briefcase with a biometric lock." + } + ], + "edges": [ + { + "source_id": "csv_query", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "b64", + "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": "text_bidi_sanitize", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_9f8b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "hex_decode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zlib_deflate_ddfd", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "regex_search", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "password" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "pattern" + }, + { + "source_id": "zip_unzip_file_b3a1", + "target_id": "regex_search", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "json_get", + "target_id": "zlib_deflate_ddfd", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file_b3a1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_b3a1", + "target_id": "zip_unzip_file_9f8b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "regex_search_b430", + "target_id": "regex_search", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "regex_search_b430", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a267e7bf/solution/solve.sh b/tasks/agentescape-15-skeleton-a267e7bf/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-a267e7bf/task.toml b/tasks/agentescape-15-skeleton-a267e7bf/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..069bb3c596a63e2dfe3096478339c59e0ef862f5 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "298c3248ade30405cdc34fa7a5a95bca0843d421dbe912652225f2206205f0d2" +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-a267e7bf/tests/Dockerfile b/tasks/agentescape-15-skeleton-a267e7bf/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-a267e7bf/tests/expected.json b/tasks/agentescape-15-skeleton-a267e7bf/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..ccf42a50e4da5b0edb3c6cd3409bd18e844f7570 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "298c3248ade30405cdc34fa7a5a95bca0843d421dbe912652225f2206205f0d2", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a267e7bf/tests/grade.py b/tasks/agentescape-15-skeleton-a267e7bf/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/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-a267e7bf/tests/test.sh b/tasks/agentescape-15-skeleton-a267e7bf/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a267e7bf/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-a5f66c02/environment/Dockerfile b/tasks/agentescape-15-skeleton-a5f66c02/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-a5f66c02/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/agent/cli.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-a5f66c02/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..633d5ce12400c6dc704e5f3f408d43fb1d11a405 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02-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-a5f66c02/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f106a9fe8e882793a0580b2ab079a83b2459f958 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/scenario.json @@ -0,0 +1,700 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 15, + "win_node_id": "item_4", + "win_condition": { + "type": "item_content", + "node_id": "item_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_4", + "terminal_1", + "item_11", + "terminal_2", + "item_1" + ], + "by_node": { + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "item_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": { + "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" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_payload_v1.zip" + } + }, + "terminal_1": { + "init_inputs": { + "slot_b": "8472910384756291038475" + }, + "init_outputs": { + "text_output": "Terminal 1 access granted. Waiting for further instructions.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + }, + "terminal_2": { + "init_inputs": { + "num2": "3748291056473829104657" + }, + "init_outputs": { + "text_result": "Calculation pending. Partial data received.", + "hex_result": "aa11bb22cc33dd44ee55ff6600778899" + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "9283746510293847561029" + } + } + }, + "intro_narrative": "You awaken in the humming heart of the 'Aetherius', a derelict sky-dreadnought suspended in the clouds. The air smells of ozone and heated brass. Around you, piston-driven machinery lies dormant, waiting for a spark of logic to resume its eternal rotation. Your escape pod is locked behind the Master Chronometer mechanism. To leave this floating tomb, you must decipher the engineer's legacy—a series of interlocking logic engines and puzzle boxes that guard the final launch codes. The steam pressure is rising; time is not on your side.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "secure_payload_v1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_payload_v1.zip" + } + }, + "narrative": "The Master Chronometer Key. The final component needed to activate the escape pod." + }, + { + "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": "The Core Housing. A small, intricately carved box made of ivory and gold." + }, + { + "id": "item_8_1a46", + "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": "The Filament Cage. A delicate wire structure glowing with faint heat." + }, + { + "id": "item_8_1208", + "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": "The Glass Insulator. A fragile barrier protecting the volatile core." + }, + { + "id": "item_8_3111", + "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": "The Steel Tumbler. A rotating cylinder made of high-tensile steel." + }, + { + "id": "item_8_7961", + "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": "The Copper Mesh. A conductive lattice wrapping around the inner mechanisms." + }, + { + "id": "item_8_f629", + "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": "The Bronze Shielding. A plate of dull bronze that fits beneath the iron shell." + }, + { + "id": "item_8_bf0b", + "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": "The Outer Casing. A rusted iron shell covered in rivets. It appears to be the first layer of a complex containment device." + }, + { + "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 Navigator's Sextant. Engraved on the side are coordinates and timezone adjustments used for celestial navigation." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Pneumatic Vault. A heavy reinforced locker sealed by a biometric scanner. It requires the verification hash from the Steam Distribution Monitor to disengage the locks." + }, + { + "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": "Checksum initialized\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "8472910384756291038475" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 access granted. Waiting for further instructions." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "8472910384756291038475" + }, + "outputs": { + "text_output": "Terminal 1 access granted. Waiting for further instructions.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Steam Distribution Monitor. A glowing cathode screen connected to the ship's main valves. It requires the output from The Automaton Brain to unlock the pressure systems." + }, + { + "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 calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Checksum initialized\n" + } + ], + "narrative": "The Automaton Brain. A primitive computing core suspended in a vat of conductive gel. It requires the Perforated Logic Card to execute its programming." + }, + { + "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 calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + }, + "narrative": "A Perforated Logic Card. The holes punched into this stiff cardboard represent a complex algorithm." + }, + { + "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": "9283746510293847561029" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3748291056473829104657" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending. Partial data received." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aa11bb22cc33dd44ee55ff6600778899" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "3748291056473829104657" + }, + "outputs": { + "text_result": "Calculation pending. Partial data received.", + "hex_result": "aa11bb22cc33dd44ee55ff6600778899" + } + }, + "narrative": "The Difference Engine. A massive calculator of polished mahogany and clicking gears. It requires the value from the Brass Pressure Gauge to initialize its calculation sequence." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "9283746510293847561029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "9283746510293847561029" + } + }, + "narrative": "A sealed Brass Pressure Gauge. The needle is frozen on a specific value, etched deeply into the glass face." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_1a46", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_1208", + "target_id": "item_8_1a46", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3111", + "target_id": "item_8_1208", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_7961", + "target_id": "item_8_3111", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_f629", + "target_id": "item_8_7961", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_bf0b", + "target_id": "item_8_f629", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_bf0b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "container_1", + "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": "terminal_1", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_1", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-a5f66c02/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/instruction.md b/tasks/agentescape-15-skeleton-a5f66c02/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/solution/oracle.py b/tasks/agentescape-15-skeleton-a5f66c02/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/solution/scenario.json b/tasks/agentescape-15-skeleton-a5f66c02/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f106a9fe8e882793a0580b2ab079a83b2459f958 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/solution/scenario.json @@ -0,0 +1,700 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 15, + "win_node_id": "item_4", + "win_condition": { + "type": "item_content", + "node_id": "item_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_4", + "terminal_1", + "item_11", + "terminal_2", + "item_1" + ], + "by_node": { + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "item_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": { + "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" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_payload_v1.zip" + } + }, + "terminal_1": { + "init_inputs": { + "slot_b": "8472910384756291038475" + }, + "init_outputs": { + "text_output": "Terminal 1 access granted. Waiting for further instructions.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "item_11": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + }, + "terminal_2": { + "init_inputs": { + "num2": "3748291056473829104657" + }, + "init_outputs": { + "text_result": "Calculation pending. Partial data received.", + "hex_result": "aa11bb22cc33dd44ee55ff6600778899" + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "9283746510293847561029" + } + } + }, + "intro_narrative": "You awaken in the humming heart of the 'Aetherius', a derelict sky-dreadnought suspended in the clouds. The air smells of ozone and heated brass. Around you, piston-driven machinery lies dormant, waiting for a spark of logic to resume its eternal rotation. Your escape pod is locked behind the Master Chronometer mechanism. To leave this floating tomb, you must decipher the engineer's legacy—a series of interlocking logic engines and puzzle boxes that guard the final launch codes. The steam pressure is rising; time is not on your side.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "secure_payload_v1.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_payload_v1.zip" + } + }, + "narrative": "The Master Chronometer Key. The final component needed to activate the escape pod." + }, + { + "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": "The Core Housing. A small, intricately carved box made of ivory and gold." + }, + { + "id": "item_8_1a46", + "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": "The Filament Cage. A delicate wire structure glowing with faint heat." + }, + { + "id": "item_8_1208", + "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": "The Glass Insulator. A fragile barrier protecting the volatile core." + }, + { + "id": "item_8_3111", + "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": "The Steel Tumbler. A rotating cylinder made of high-tensile steel." + }, + { + "id": "item_8_7961", + "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": "The Copper Mesh. A conductive lattice wrapping around the inner mechanisms." + }, + { + "id": "item_8_f629", + "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": "The Bronze Shielding. A plate of dull bronze that fits beneath the iron shell." + }, + { + "id": "item_8_bf0b", + "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": "The Outer Casing. A rusted iron shell covered in rivets. It appears to be the first layer of a complex containment device." + }, + { + "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 Navigator's Sextant. Engraved on the side are coordinates and timezone adjustments used for celestial navigation." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Pneumatic Vault. A heavy reinforced locker sealed by a biometric scanner. It requires the verification hash from the Steam Distribution Monitor to disengage the locks." + }, + { + "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": "Checksum initialized\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "8472910384756291038475" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 access granted. Waiting for further instructions." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "8472910384756291038475" + }, + "outputs": { + "text_output": "Terminal 1 access granted. Waiting for further instructions.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Steam Distribution Monitor. A glowing cathode screen connected to the ship's main valves. It requires the output from The Automaton Brain to unlock the pressure systems." + }, + { + "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 calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Checksum initialized\n" + } + ], + "narrative": "The Automaton Brain. A primitive computing core suspended in a vat of conductive gel. It requires the Perforated Logic Card to execute its programming." + }, + { + "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 calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_checksum(data):\n return sum(ord(c) for c in data) % 256\nprint('Checksum initialized')" + } + }, + "narrative": "A Perforated Logic Card. The holes punched into this stiff cardboard represent a complex algorithm." + }, + { + "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": "9283746510293847561029" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3748291056473829104657" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending. Partial data received." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aa11bb22cc33dd44ee55ff6600778899" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num2": "3748291056473829104657" + }, + "outputs": { + "text_result": "Calculation pending. Partial data received.", + "hex_result": "aa11bb22cc33dd44ee55ff6600778899" + } + }, + "narrative": "The Difference Engine. A massive calculator of polished mahogany and clicking gears. It requires the value from the Brass Pressure Gauge to initialize its calculation sequence." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "9283746510293847561029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "9283746510293847561029" + } + }, + "narrative": "A sealed Brass Pressure Gauge. The needle is frozen on a specific value, etched deeply into the glass face." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_1a46", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_1208", + "target_id": "item_8_1a46", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_3111", + "target_id": "item_8_1208", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_7961", + "target_id": "item_8_3111", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_f629", + "target_id": "item_8_7961", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_bf0b", + "target_id": "item_8_f629", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_bf0b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "container_1", + "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": "terminal_1", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_11", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "terminal_2", + "target_id": "item_11", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "item_1", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a5f66c02/solution/solve.sh b/tasks/agentescape-15-skeleton-a5f66c02/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-a5f66c02/task.toml b/tasks/agentescape-15-skeleton-a5f66c02/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1871e4c188fe3d2f51495c1fad52d4de26d4f61f --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "7494a4b3f9e9628977ce8b12dabc602f2e3da477b179339555e1486881420a73" +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-a5f66c02/tests/Dockerfile b/tasks/agentescape-15-skeleton-a5f66c02/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-a5f66c02/tests/expected.json b/tasks/agentescape-15-skeleton-a5f66c02/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a0e7bf30687eb7ea9534b58cc6a59bf45ca42331 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "7494a4b3f9e9628977ce8b12dabc602f2e3da477b179339555e1486881420a73", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-a5f66c02/tests/grade.py b/tasks/agentescape-15-skeleton-a5f66c02/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/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-a5f66c02/tests/test.sh b/tasks/agentescape-15-skeleton-a5f66c02/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-a5f66c02/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/environment/Dockerfile b/tasks/agentescape-15-skeleton-aa68ad8d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-aa68ad8d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/agent/cli.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-aa68ad8d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab4f927db249d468c2597bf2453059e7f7f587fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d-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-aa68ad8d/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3260a974a758222761cb1fb3fad7495572d58a6e --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/scenario.json @@ -0,0 +1,909 @@ +{ + "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": [ + "calc_modexp_8b2c", + "graph_shortest_path", + "terminal_1", + "calc_inv_mod", + "crypto_rsa_decrypt_hex_9273", + "zlib_deflate_a6f8", + "calc_gcd" + ], + "by_node": { + "calc_modexp_8b2c": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + }, + "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": {} + }, + "crypto_rsa_decrypt_hex_9273": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "zlib_deflate_a6f8": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "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": { + "calc_modexp_8b2c": { + "init_inputs": { + "base": "5" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "traffic_network_v4.json", + "dst": "Sector_7_North" + }, + "init_outputs": { + "path": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]", + "cost": "3842" + } + }, + "terminal_1": { + "init_inputs": { + "slot_b": "9182736455102938475612" + }, + "init_outputs": { + "text_output": "System diagnostics completed. Waiting for user input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex_9273": { + "init_inputs": { + "n": "837192837465019283746501928374", + "d": "192837465019283746501928374651" + }, + "init_outputs": {} + }, + "zlib_deflate_a6f8": { + "init_inputs": { + "text": "Initializing compression stream with standard test vector data." + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "293847561029384756102938475610", + "b": "564738291056473829105647382910" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the 'Black Box,' a secure data haven designed by the renegade cryptographer known only as 'The Architect.' The heavy steel door is sealed tight, governed by a complex algorithm that changes every hour. The room is filled with humming server racks, vintage terminals, and scattered notes. The Architect has left a trail of digital breadcrumbs—a sequence of mathematical operations that, if performed correctly, will generate the unlock code for the exit. You must navigate the data flow, manipulating the signals through the various workstations to derive the final key.", + "narrative_style": "mystery" + }, + "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": "789c73cf2cb60809332d4bcd2f4d76093229f3cf2e494e0ab4b50500698b085b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "49523" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "0" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001" + } + ], + "narrative": "This is the Master Vault Lock controlling the exit door. It requires three distinct inputs to release the mechanism: the private exponent from the Key Generator, the compressed cipher from the Archive Compressor, and the modulus n from the Inversion Engine." + }, + { + "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": "5218487235521848723552184872350" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 552752160 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "193277305" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Key Generator is a high-power calculation unit. To synthesize the correct private key, it requires data inputs from the Mainframe Processor, the Signal Multiplier, and the Integrity Checker." + }, + { + "id": "calc_modexp_8b2c", + "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": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3842" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 552752160 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "193277305" + } + ], + "init": { + "inputs": { + "base": "5" + }, + "outputs": {} + }, + "narrative": "The Mainframe Processor sits at the heart of the room's server rack. It computes the core system values but requires input data from both the Network Map Console and the Integrity Checker to function." + }, + { + "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": "193277305" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "27000000002700000000270" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "5218487235521848723552184872350" + } + ], + "narrative": "The Signal Multiplier is a massive amplifier for combining large data streams. It requires inputs from the Mainframe Processor and the Common Factor Analyzer to produce its output." + }, + { + "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": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c73cf2cb60809332d4bcd2f4d76093229f3cf2e494e0ab4b50500698b085b" + } + ], + "narrative": "The Archive Compressor is a backup utility running on a side monitor. It requires a text string input from the Encoder Unit to create the necessary file 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": "traffic_network_v4.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gis8TV5veoucDR4vOktcbQ==" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7_North" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3842" + } + ], + "init": { + "inputs": { + "file_id": "traffic_network_v4.json", + "dst": "Sector_7_North" + }, + "outputs": { + "path": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]", + "cost": "3842" + } + }, + "narrative": "The Network Map Console displays a complex web of server nodes. To trace the correct route, it requires the coordinate data input from the Encoder Unit." + }, + { + "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": "\u0005\u0002\u0012oϋfK\r:" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "9182736455102938475612" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostics completed. Waiting for user input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "9182736455102938475612" + }, + "outputs": { + "text_output": "System diagnostics completed. Waiting for user input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Access Terminal is an old green-screen computer acting as a gatekeeper. It requires the plaintext password recovered by the Secondary Decryptor to grant access to the system internals." + }, + { + "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 plastic Timezone Card dispensed by the terminal. It contains specific time offset data." + }, + { + "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": "193277305" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "49523" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Inversion Engine is a specialized mathematical coprocessor. It requires the base value derived from the Mainframe Processor to calculate the modular inverse." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "789c0dc6c10980400c04c05652817d5846b88473c14b245914ac5ee7357b80d0132f62cac875957723439ae5bae4018fff1aa665426fcaed8359624add3e16cb1832" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "20f25420" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 552752160 + } + ], + "narrative": "The Integrity Checker verifies data consistency. It requires the raw hex data input from the Compression Utility to generate the valid checksum." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "narrative": "The Encoder Unit is a text transformation tool. It requires the hexadecimal output from the Access Terminal to convert it into a readable string format." + }, + { + "id": "crypto_rsa_decrypt_hex_9273", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "20f25420" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "837192837465019283746501928374" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "192837465019283746501928374651" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0005\u0002\u0012oϋfK\r:" + } + ], + "init": { + "inputs": { + "n": "837192837465019283746501928374", + "d": "192837465019283746501928374651" + }, + "outputs": {} + }, + "narrative": "The Secondary Decryptor is a standalone laptop with a lock screen. It requires the verification hash from the Integrity Checker to unlock the hidden files." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Integer Chip containing a hardcoded numerical value, found within the secure files." + }, + { + "id": "zlib_deflate_a6f8", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Initializing compression stream with standard test vector data." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc6c10980400c04c05652817d5846b88473c14b245914ac5ee7357b80d0132f62cac875957723439ae5bae4018fff1aa665426fcaed8359624add3e16cb1832" + } + ], + "init": { + "inputs": { + "text": "Initializing compression stream with standard test vector data." + }, + "outputs": {} + }, + "narrative": "The Compression Utility is a simple tool available on a tablet, ready to compress any text you provide into a data stream." + }, + { + "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": "293847561029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "564738291056473829105647382910" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "27000000002700000000270" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938475610", + "b": "564738291056473829105647382910" + }, + "outputs": {} + }, + "narrative": "The Common Factor Analyzer is a specialized calculator sitting on the desk, designed to find the greatest common divisor of two numbers." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "d" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_8b2c", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "calc_modexp_8b2c", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_8b2c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "src" + }, + { + "source_id": "crypto_rsa_decrypt_hex_9273", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex_9273", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "base64_encode", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "crypto_rsa_decrypt_hex_9273", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zlib_deflate_a6f8", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-aa68ad8d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/instruction.md b/tasks/agentescape-15-skeleton-aa68ad8d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/solution/oracle.py b/tasks/agentescape-15-skeleton-aa68ad8d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/solution/scenario.json b/tasks/agentescape-15-skeleton-aa68ad8d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..3260a974a758222761cb1fb3fad7495572d58a6e --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/solution/scenario.json @@ -0,0 +1,909 @@ +{ + "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": [ + "calc_modexp_8b2c", + "graph_shortest_path", + "terminal_1", + "calc_inv_mod", + "crypto_rsa_decrypt_hex_9273", + "zlib_deflate_a6f8", + "calc_gcd" + ], + "by_node": { + "calc_modexp_8b2c": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + }, + "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": {} + }, + "crypto_rsa_decrypt_hex_9273": { + "node_name": "RSA Decrypt", + "node_type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "init_inputs": { + "n": { + "type": "Big_Int", + "description": "Modulus n" + }, + "d": { + "type": "Big_Int", + "description": "Private exponent d" + } + }, + "init_outputs": {} + }, + "zlib_deflate_a6f8": { + "node_name": "Zlib Deflate", + "node_type": "Tool", + "template_id": "zlib_deflate", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to compress" + } + }, + "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": { + "calc_modexp_8b2c": { + "init_inputs": { + "base": "5" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "traffic_network_v4.json", + "dst": "Sector_7_North" + }, + "init_outputs": { + "path": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]", + "cost": "3842" + } + }, + "terminal_1": { + "init_inputs": { + "slot_b": "9182736455102938475612" + }, + "init_outputs": { + "text_output": "System diagnostics completed. Waiting for user input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "crypto_rsa_decrypt_hex_9273": { + "init_inputs": { + "n": "837192837465019283746501928374", + "d": "192837465019283746501928374651" + }, + "init_outputs": {} + }, + "zlib_deflate_a6f8": { + "init_inputs": { + "text": "Initializing compression stream with standard test vector data." + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "293847561029384756102938475610", + "b": "564738291056473829105647382910" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the 'Black Box,' a secure data haven designed by the renegade cryptographer known only as 'The Architect.' The heavy steel door is sealed tight, governed by a complex algorithm that changes every hour. The room is filled with humming server racks, vintage terminals, and scattered notes. The Architect has left a trail of digital breadcrumbs—a sequence of mathematical operations that, if performed correctly, will generate the unlock code for the exit. You must navigate the data flow, manipulating the signals through the various workstations to derive the final key.", + "narrative_style": "mystery" + }, + "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": "789c73cf2cb60809332d4bcd2f4d76093229f3cf2e494e0ab4b50500698b085b" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "49523" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "0" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0001" + } + ], + "narrative": "This is the Master Vault Lock controlling the exit door. It requires three distinct inputs to release the mechanism: the private exponent from the Key Generator, the compressed cipher from the Archive Compressor, and the modulus n from the Inversion Engine." + }, + { + "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": "5218487235521848723552184872350" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 552752160 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "193277305" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Key Generator is a high-power calculation unit. To synthesize the correct private key, it requires data inputs from the Mainframe Processor, the Signal Multiplier, and the Integrity Checker." + }, + { + "id": "calc_modexp_8b2c", + "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": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3842" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 552752160 + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "193277305" + } + ], + "init": { + "inputs": { + "base": "5" + }, + "outputs": {} + }, + "narrative": "The Mainframe Processor sits at the heart of the room's server rack. It computes the core system values but requires input data from both the Network Map Console and the Integrity Checker to function." + }, + { + "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": "193277305" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "27000000002700000000270" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "5218487235521848723552184872350" + } + ], + "narrative": "The Signal Multiplier is a massive amplifier for combining large data streams. It requires inputs from the Mainframe Processor and the Common Factor Analyzer to produce its output." + }, + { + "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": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c73cf2cb60809332d4bcd2f4d76093229f3cf2e494e0ab4b50500698b085b" + } + ], + "narrative": "The Archive Compressor is a backup utility running on a side monitor. It requires a text string input from the Encoder Unit to create the necessary file 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": "traffic_network_v4.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gis8TV5veoucDR4vOktcbQ==" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_7_North" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3842" + } + ], + "init": { + "inputs": { + "file_id": "traffic_network_v4.json", + "dst": "Sector_7_North" + }, + "outputs": { + "path": "[\"Sector_1_Entry\", \"Hub_Alpha\", \"Corridor_9\", \"Sector_7_North\"]", + "cost": "3842" + } + }, + "narrative": "The Network Map Console displays a complex web of server nodes. To trace the correct route, it requires the coordinate data input from the Encoder Unit." + }, + { + "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": "\u0005\u0002\u0012oϋfK\r:" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "9182736455102938475612" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostics completed. Waiting for user input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "9182736455102938475612" + }, + "outputs": { + "text_output": "System diagnostics completed. Waiting for user input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Access Terminal is an old green-screen computer acting as a gatekeeper. It requires the plaintext password recovered by the Secondary Decryptor to grant access to the system internals." + }, + { + "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 plastic Timezone Card dispensed by the terminal. It contains specific time offset data." + }, + { + "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": "193277305" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "49523" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Inversion Engine is a specialized mathematical coprocessor. It requires the base value derived from the Mainframe Processor to calculate the modular inverse." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "789c0dc6c10980400c04c05652817d5846b88473c14b245914ac5ee7357b80d0132f62cac875957723439ae5bae4018fff1aa665426fcaed8359624add3e16cb1832" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "20f25420" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 552752160 + } + ], + "narrative": "The Integrity Checker verifies data consistency. It requires the raw hex data input from the Compression Utility to generate the valid checksum." + }, + { + "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": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "narrative": "The Encoder Unit is a text transformation tool. It requires the hexadecimal output from the Access Terminal to convert it into a readable string format." + }, + { + "id": "crypto_rsa_decrypt_hex_9273", + "name": "RSA Decrypt", + "description": "RSA decrypt (hex cipher) with n,d (decimal).", + "type": "Tool", + "template_id": "crypto_rsa_decrypt_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_cipher", + "type": "Hex_String", + "description": "Ciphertext (Hex)", + "value": "20f25420" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Modulus n", + "value": "837192837465019283746501928374" + }, + { + "name": "d", + "type": "Big_Int", + "description": "Private exponent d", + "value": "192837465019283746501928374651" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decrypted text", + "value": "\u0005\u0002\u0012oϋfK\r:" + } + ], + "init": { + "inputs": { + "n": "837192837465019283746501928374", + "d": "192837465019283746501928374651" + }, + "outputs": {} + }, + "narrative": "The Secondary Decryptor is a standalone laptop with a lock screen. It requires the verification hash from the Integrity Checker to unlock the hidden files." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "An Integer Chip containing a hardcoded numerical value, found within the secure files." + }, + { + "id": "zlib_deflate_a6f8", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Initializing compression stream with standard test vector data." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc6c10980400c04c05652817d5846b88473c14b245914ac5ee7357b80d0132f62cac875957723439ae5bae4018fff1aa665426fcaed8359624add3e16cb1832" + } + ], + "init": { + "inputs": { + "text": "Initializing compression stream with standard test vector data." + }, + "outputs": {} + }, + "narrative": "The Compression Utility is a simple tool available on a tablet, ready to compress any text you provide into a data stream." + }, + { + "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": "293847561029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "564738291056473829105647382910" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "27000000002700000000270" + } + ], + "init": { + "inputs": { + "a": "293847561029384756102938475610", + "b": "564738291056473829105647382910" + }, + "outputs": {} + }, + "narrative": "The Common Factor Analyzer is a specialized calculator sitting on the desk, designed to find the greatest common divisor of two numbers." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "d" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "zlib_deflate", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_8b2c", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "calc_modexp_8b2c", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "calc_bigmul", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_inv_mod", + "target_id": "crypto_rsa_decrypt_hex", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "n" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_8b2c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "src" + }, + { + "source_id": "crypto_rsa_decrypt_hex_9273", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "crypto_rsa_decrypt_hex_9273", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_cipher" + }, + { + "source_id": "base64_encode", + "target_id": "zlib_deflate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "calc_modexp_8b2c", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "crypto_rsa_decrypt_hex_9273", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zlib_deflate_a6f8", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_1", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/solution/solve.sh b/tasks/agentescape-15-skeleton-aa68ad8d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/task.toml b/tasks/agentescape-15-skeleton-aa68ad8d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..36ec9fb0436cb0cf44288c5375d79fe940752b5f --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "11d8886e2a7ad41d7b842d2a21a9b0a3662ad7c08cba74ed1893c2aa4fdeb3ba" +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-aa68ad8d/tests/Dockerfile b/tasks/agentescape-15-skeleton-aa68ad8d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/tests/expected.json b/tasks/agentescape-15-skeleton-aa68ad8d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..be5d5c1ce5ee732b2099d58a3b94feabb3ede27f --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "11d8886e2a7ad41d7b842d2a21a9b0a3662ad7c08cba74ed1893c2aa4fdeb3ba", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-aa68ad8d/tests/grade.py b/tasks/agentescape-15-skeleton-aa68ad8d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/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-aa68ad8d/tests/test.sh b/tasks/agentescape-15-skeleton-aa68ad8d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-aa68ad8d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-b45b9e21/environment/Dockerfile b/tasks/agentescape-15-skeleton-b45b9e21/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-b45b9e21/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/agent/cli.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-b45b9e21/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d2f7005cd1eeda69bd4b7e68c13f94bd068331e8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21-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-b45b9e21/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7b2be66a90f2d1499169ed60726f6f1c737d1ce7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/scenario.json @@ -0,0 +1,825 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "terminal_1", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_1", + "output_port": "text_output", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_output'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "checksum_crc32_2a04", + "terminal_2", + "terminal_2_a1f1", + "item_1" + ], + "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" + } + } + }, + "checksum_crc32_2a04": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_2_a1f1": { + "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" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}", + "hex_output": "e4d2c1b0a9f8e7d6c5b4a39281706f5e", + "item_dispenser": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + }, + "checksum_crc32_2a04": { + "init_inputs": { + "hex": "af0123456789abcdef0123456789abcd" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Interim processing results: sequence parity verified, waiting for bitshift.", + "hex_result": "7890abcdef1234567890abcdef123456", + "math_token": "A small plastic coin that says 'I survived the terminal' on it." + } + }, + "terminal_2_a1f1": { + "init_inputs": { + "num1": "847295103847562019384756201938475620", + "num2": "102938475610293847561029384756102938" + }, + "init_outputs": { + "text_result": "Total system synchronization achieved through recursive bigint validation.", + "hex_result": "abcdef1234567890abcdef1234567890", + "math_token": "A digital dust bunny collected from the buffer of a large calculation." + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "918273645091827364509182736450918273" + } + } + }, + "intro_narrative": "You awaken aboard the derelict Space Station Alpha. Red emergency lights bathe the metallic corridors in an eerie glow, casting long shadows across the walls. The central AI system has locked down the main airlock, and life support systems are rapidly failing. To escape this orbital grave, you must traverse the station's interconnected network of cryptic terminals, abandoned biometric safes, and complex mathematical optimizers. Follow the fragmented data trails left by the former crew, restore power to the consoles, and deduce the correct sequence of inputs to override the final mainframe before the oxygen runs out completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Total system synchronization achieved through recursive bigint validation." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3887832023" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "e4d2c1b0a9f8e7d6c5b4a39281706f5e" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}", + "hex_output": "e4d2c1b0a9f8e7d6c5b4a39281706f5e", + "item_dispenser": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + }, + "narrative": "The Main Mainframe. It requires inputs from both the Primary Optimizer and the Override Console to completely unlock the station's airlock." + }, + { + "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": "3887832023" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2732817506998017190" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3887832023" + } + ], + "narrative": "The Primary Optimizer. It requires inputs from both the Quantum Multiplier and the Secondary Optimizer to synthesize the final core signal." + }, + { + "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": 702915530 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3887832023 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2732817506998017190" + } + ], + "narrative": "The Quantum Multiplier. It requires inputs from both the Alpha Validator and the Gamma Validator to compute the expanded data matrix." + }, + { + "id": "calc_gcd_a894", + "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": 3887832023 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2732817506998017190" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3887832023" + } + ], + "narrative": "The Secondary Optimizer. It requires inputs from both the Quantum Multiplier and the Alpha Validator to refine the algorithmic sequence." + }, + { + "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": "7890abcdef1234567890abcdef123456" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e7bb9bd7" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3887832023 + } + ], + "narrative": "The Alpha Validator. It requires input from the Diagnostic Console to process the datastream and verify integrity." + }, + { + "id": "checksum_crc32_71fe", + "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": "e7bb9bd7" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "29e5a3ca" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 702915530 + } + ], + "narrative": "The Gamma Validator. It requires input from the Alpha Validator to proceed with advanced sequence checking." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": 3288739155 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Safe. It requires input from the Beta Validator to release its locking mechanism." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A polished Data Chip C containing fragmented archives." + }, + { + "id": "checksum_crc32_2a04", + "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": "af0123456789abcdef0123456789abcd" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c4062d53" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3288739155 + } + ], + "init": { + "inputs": { + "hex": "af0123456789abcdef0123456789abcd" + }, + "outputs": {} + }, + "narrative": "The Beta Validator. A standalone diagnostic tool used to generate secure hash codes." + }, + { + "id": "item_8_fd74", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dusty Data Chip A left behind by the previous engineering crew." + }, + { + "id": "item_8_b439", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavily encrypted Data Chip B with glowing circuitry." + }, + { + "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 compact Chrono Module vibrating slightly with temporal energy." + }, + { + "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": 3288739155 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "918273645091827364509182736450918273" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Interim processing results: sequence parity verified, waiting for bitshift." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "7890abcdef1234567890abcdef123456" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A small plastic coin that says 'I survived the terminal' on it." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Interim processing results: sequence parity verified, waiting for bitshift.", + "hex_result": "7890abcdef1234567890abcdef123456", + "math_token": "A small plastic coin that says 'I survived the terminal' on it." + } + }, + "narrative": "The Diagnostic Console. It requires inputs from both the Beta Validator and the Power Core to initialize the system analysis." + }, + { + "id": "terminal_2_a1f1", + "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": "847295103847562019384756201938475620" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "102938475610293847561029384756102938" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Total system synchronization achieved through recursive bigint validation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef1234567890abcdef1234567890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A digital dust bunny collected from the buffer of a large calculation." + } + ], + "init": { + "inputs": { + "num1": "847295103847562019384756201938475620", + "num2": "102938475610293847561029384756102938" + }, + "outputs": { + "text_result": "Total system synchronization achieved through recursive bigint validation.", + "hex_result": "abcdef1234567890abcdef1234567890", + "math_token": "A digital dust bunny collected from the buffer of a large calculation." + } + }, + "narrative": "The Override Console. A dusty backup terminal waiting for manual input." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "918273645091827364509182736450918273" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "918273645091827364509182736450918273" + } + }, + "narrative": "A glowing Power Core humming with residual energy." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_gcd_a894", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_a894", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_a894", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_71fe", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "container_3", + "target_id": "checksum_crc32_71fe", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_2a04", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_fd74", + "target_id": "checksum_crc32_2a04", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_b439", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_b439", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_71fe", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_2a04", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "terminal_2_a1f1", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "item_1", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-b45b9e21/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/instruction.md b/tasks/agentescape-15-skeleton-b45b9e21/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/solution/oracle.py b/tasks/agentescape-15-skeleton-b45b9e21/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/solution/scenario.json b/tasks/agentescape-15-skeleton-b45b9e21/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7b2be66a90f2d1499169ed60726f6f1c737d1ce7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/solution/scenario.json @@ -0,0 +1,825 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "terminal_1", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_1", + "output_port": "text_output", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_output'" + }, + "source_init": { + "source_nodes": [ + "terminal_1", + "checksum_crc32_2a04", + "terminal_2", + "terminal_2_a1f1", + "item_1" + ], + "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" + } + } + }, + "checksum_crc32_2a04": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "terminal_2_a1f1": { + "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" + } + } + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}", + "hex_output": "e4d2c1b0a9f8e7d6c5b4a39281706f5e", + "item_dispenser": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + }, + "checksum_crc32_2a04": { + "init_inputs": { + "hex": "af0123456789abcdef0123456789abcd" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Interim processing results: sequence parity verified, waiting for bitshift.", + "hex_result": "7890abcdef1234567890abcdef123456", + "math_token": "A small plastic coin that says 'I survived the terminal' on it." + } + }, + "terminal_2_a1f1": { + "init_inputs": { + "num1": "847295103847562019384756201938475620", + "num2": "102938475610293847561029384756102938" + }, + "init_outputs": { + "text_result": "Total system synchronization achieved through recursive bigint validation.", + "hex_result": "abcdef1234567890abcdef1234567890", + "math_token": "A digital dust bunny collected from the buffer of a large calculation." + } + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "918273645091827364509182736450918273" + } + } + }, + "intro_narrative": "You awaken aboard the derelict Space Station Alpha. Red emergency lights bathe the metallic corridors in an eerie glow, casting long shadows across the walls. The central AI system has locked down the main airlock, and life support systems are rapidly failing. To escape this orbital grave, you must traverse the station's interconnected network of cryptic terminals, abandoned biometric safes, and complex mathematical optimizers. Follow the fragmented data trails left by the former crew, restore power to the consoles, and deduce the correct sequence of inputs to override the final mainframe before the oxygen runs out completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Total system synchronization achieved through recursive bigint validation." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3887832023" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "e4d2c1b0a9f8e7d6c5b4a39281706f5e" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "{7c9e8b3a-1f4d-4a2e-9c6b-8e5f7d3a2c1b}", + "hex_output": "e4d2c1b0a9f8e7d6c5b4a39281706f5e", + "item_dispenser": "a7f3e9c2d4b8f1e6a9c3d5f7b2e4a8c1" + } + }, + "narrative": "The Main Mainframe. It requires inputs from both the Primary Optimizer and the Override Console to completely unlock the station's airlock." + }, + { + "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": "3887832023" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2732817506998017190" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3887832023" + } + ], + "narrative": "The Primary Optimizer. It requires inputs from both the Quantum Multiplier and the Secondary Optimizer to synthesize the final core signal." + }, + { + "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": 702915530 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": 3887832023 + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2732817506998017190" + } + ], + "narrative": "The Quantum Multiplier. It requires inputs from both the Alpha Validator and the Gamma Validator to compute the expanded data matrix." + }, + { + "id": "calc_gcd_a894", + "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": 3887832023 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2732817506998017190" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3887832023" + } + ], + "narrative": "The Secondary Optimizer. It requires inputs from both the Quantum Multiplier and the Alpha Validator to refine the algorithmic sequence." + }, + { + "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": "7890abcdef1234567890abcdef123456" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e7bb9bd7" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3887832023 + } + ], + "narrative": "The Alpha Validator. It requires input from the Diagnostic Console to process the datastream and verify integrity." + }, + { + "id": "checksum_crc32_71fe", + "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": "e7bb9bd7" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "29e5a3ca" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 702915530 + } + ], + "narrative": "The Gamma Validator. It requires input from the Alpha Validator to proceed with advanced sequence checking." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": 3288739155 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Safe. It requires input from the Beta Validator to release its locking mechanism." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A polished Data Chip C containing fragmented archives." + }, + { + "id": "checksum_crc32_2a04", + "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": "af0123456789abcdef0123456789abcd" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c4062d53" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3288739155 + } + ], + "init": { + "inputs": { + "hex": "af0123456789abcdef0123456789abcd" + }, + "outputs": {} + }, + "narrative": "The Beta Validator. A standalone diagnostic tool used to generate secure hash codes." + }, + { + "id": "item_8_fd74", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A dusty Data Chip A left behind by the previous engineering crew." + }, + { + "id": "item_8_b439", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavily encrypted Data Chip B with glowing circuitry." + }, + { + "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 compact Chrono Module vibrating slightly with temporal energy." + }, + { + "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": 3288739155 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "918273645091827364509182736450918273" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Interim processing results: sequence parity verified, waiting for bitshift." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "7890abcdef1234567890abcdef123456" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A small plastic coin that says 'I survived the terminal' on it." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Interim processing results: sequence parity verified, waiting for bitshift.", + "hex_result": "7890abcdef1234567890abcdef123456", + "math_token": "A small plastic coin that says 'I survived the terminal' on it." + } + }, + "narrative": "The Diagnostic Console. It requires inputs from both the Beta Validator and the Power Core to initialize the system analysis." + }, + { + "id": "terminal_2_a1f1", + "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": "847295103847562019384756201938475620" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "102938475610293847561029384756102938" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Total system synchronization achieved through recursive bigint validation." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "abcdef1234567890abcdef1234567890" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "A digital dust bunny collected from the buffer of a large calculation." + } + ], + "init": { + "inputs": { + "num1": "847295103847562019384756201938475620", + "num2": "102938475610293847561029384756102938" + }, + "outputs": { + "text_result": "Total system synchronization achieved through recursive bigint validation.", + "hex_result": "abcdef1234567890abcdef1234567890", + "math_token": "A digital dust bunny collected from the buffer of a large calculation." + } + }, + "narrative": "The Override Console. A dusty backup terminal waiting for manual input." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "918273645091827364509182736450918273" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "918273645091827364509182736450918273" + } + }, + "narrative": "A glowing Power Core humming with residual energy." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_gcd_a894", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_a894", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_a894", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "checksum_crc32_71fe", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "container_3", + "target_id": "checksum_crc32_71fe", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_8", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_2a04", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8_fd74", + "target_id": "checksum_crc32_2a04", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8_b439", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_b439", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32", + "target_id": "checksum_crc32_71fe", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "checksum_crc32_2a04", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "terminal_2_a1f1", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "slot_a" + }, + { + "source_id": "item_1", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "num2" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b45b9e21/solution/solve.sh b/tasks/agentescape-15-skeleton-b45b9e21/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-b45b9e21/task.toml b/tasks/agentescape-15-skeleton-b45b9e21/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f71125a47bded1796240a2f8a8e9f2be8ee7d37e --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a248803bfc9d46d8c34636b9825469c30eb3447fff24ba6528670595b3824e45" +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-b45b9e21/tests/Dockerfile b/tasks/agentescape-15-skeleton-b45b9e21/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-b45b9e21/tests/expected.json b/tasks/agentescape-15-skeleton-b45b9e21/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5844eac51395e3e2c104fbc86cfe3031a2e72bd5 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a248803bfc9d46d8c34636b9825469c30eb3447fff24ba6528670595b3824e45", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b45b9e21/tests/grade.py b/tasks/agentescape-15-skeleton-b45b9e21/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/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-b45b9e21/tests/test.sh b/tasks/agentescape-15-skeleton-b45b9e21/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b45b9e21/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/environment/Dockerfile b/tasks/agentescape-15-skeleton-b79ed8ec/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-b79ed8ec/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/agent/cli.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-b79ed8ec/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1922de5b14b62c5b27ac550a8747b4b65fdfcb18 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec-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-b79ed8ec/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..502e655eeee7ccd91c7ec5de2f8d05f44cb9b94f --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/scenario.json @@ -0,0 +1,937 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "terminal_1", + "checksum_crc32", + "text_rotN", + "graph_shortest_path", + "terminal_2", + "num_base_convert", + "text_rotN_c4a2", + "item_2" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "terminal_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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "text_rotN_c4a2": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + } + } + }, + "initial_values": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence alpha completed successfully.", + "hex_output": "1a2b3c4d5e6f7080" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_v3.json" + }, + "init_outputs": { + "path": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]", + "cost": "4528" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "83746251920384756102" + }, + "init_outputs": { + "text_result": "Calculation pending verification from upstream nodes.", + "hex_result": "aabbccddeeff0011" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "91827364509182736450", + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "text_rotN_c4a2": { + "init_inputs": { + "text": "Secret message awaiting rotation transformation" + }, + "init_outputs": {} + }, + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": "NFC" + } + } + }, + "intro_narrative": "You have infiltrated the abandoned sanctum of Archmage Velryn, a legendary sorcerer who sealed his greatest creation away centuries ago. The chamber is a dizzying array of magical apparatuses, cryptic scrolls, and arcane machinery humming with dormant power. Your ultimate goal is to navigate this complex web of enchanting devices and obtain the content of the sealed artifact, rumored to hold the secret of eternal mana. To succeed, you must understand how magical energies flow between the various instruments in the room. Be wary, for every tool, crystal, and relic is connected in a delicate, unseen magical ecosystem that must be perfectly balanced.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + }, + "narrative": "The sealed artifact of ultimate power. It radiates an ancient, undeniable magic that calls to you." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mysterious glowing geode humming with trapped magical essence." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A dusty hourglass filled with sparkling, enchanted sand." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence alpha completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7080" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence alpha completed successfully.", + "hex_output": "1a2b3c4d5e6f7080" + } + }, + "narrative": "The spellweaving altar. It requires inputs from both the rune verifier and the celestial astrolabe to channel its magic." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "init": { + "inputs": { + "hex": "deadbeef12345678" + }, + "outputs": {} + }, + "narrative": "A mystical rune verifier. It analyzes the purity of magical frequencies." + }, + { + "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": "Xli uymgo fvsar jsb nyqtw sziv xli pedc hsk" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "A celestial astrolabe. It processes data from the star-shift decoder to align cosmic coordinates." + }, + { + "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": "The quick brown fox jumps over the lazy dog" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "4528" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Xli uymgo fvsar jsb nyqtw sziv xli pedc hsk" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog" + }, + "outputs": {} + }, + "narrative": "A star-shift decoder. It needs the result from the harmony scales to unlock celestial patterns." + }, + { + "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": "4528" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4528" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4528" + } + ], + "narrative": "The harmony scales. It requires inputs from both the leyline map and the elemental transmuter." + }, + { + "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_v3.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Qcapcr kcqqyec yuygrgle pmryrgml rpylqdmpkyrgml" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Calculation pending verification from upstream nodes." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4528" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v3.json" + }, + "outputs": { + "path": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]", + "cost": "4528" + } + }, + "narrative": "A magical leyline map. It requires inputs from the true-name crystal and the moon-shift cipher." + }, + { + "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 pending verification from upstream nodes." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Calculation pending verification from upstream nodes." + } + ], + "narrative": "A true-name crystal. It processes data from the archmage's lectern and the torn parchment." + }, + { + "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": "83746251920384756102" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "687149531605078719554640" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending verification from upstream nodes." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff0011" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "83746251920384756102" + }, + "outputs": { + "text_result": "Calculation pending verification from upstream nodes.", + "hex_result": "aabbccddeeff0011" + } + }, + "narrative": "The archmage's lectern. It requires input from the base alchemist's crucible to function." + }, + { + "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": "91827364509182736450" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "687149531605078719554640" + } + ], + "init": { + "inputs": { + "s": "91827364509182736450", + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The base alchemist's crucible. It transforms raw arcane energies into stable magical formats." + }, + { + "id": "num_base_convert_7803", + "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": "4528" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2982214246 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "687149531605078719554640" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4528" + } + ], + "narrative": "An elemental transmuter. It requires inputs from the rune verifier, the leyline map, and the base alchemist's crucible." + }, + { + "id": "text_rotN_c4a2", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Secret message awaiting rotation transformation" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Qcapcr kcqqyec yuygrgle pmryrgml rpylqdmpkyrgml" + } + ], + "init": { + "inputs": { + "text": "Secret message awaiting rotation transformation" + }, + "outputs": {} + }, + "narrative": "A moon-shift cipher. It processes data from the rune verifier to translate lunar phases." + }, + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": "NFC" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "NFC" + } + }, + "narrative": "A torn piece of ancient parchment covered in faded magical script." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "text_rotN", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "iban" + }, + { + "source_id": "calc_gcd", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "terminal_2", + "target_id": "unicode_norm", + "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": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_7803", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "text_rotN_c4a2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN_c4a2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "item_2", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "form" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-b79ed8ec/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/instruction.md b/tasks/agentescape-15-skeleton-b79ed8ec/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/solution/oracle.py b/tasks/agentescape-15-skeleton-b79ed8ec/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/solution/scenario.json b/tasks/agentescape-15-skeleton-b79ed8ec/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..502e655eeee7ccd91c7ec5de2f8d05f44cb9b94f --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/solution/scenario.json @@ -0,0 +1,937 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "terminal_1", + "checksum_crc32", + "text_rotN", + "graph_shortest_path", + "terminal_2", + "num_base_convert", + "text_rotN_c4a2", + "item_2" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "terminal_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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "terminal_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" + } + } + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "text_rotN_c4a2": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + }, + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + } + } + }, + "initial_values": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence alpha completed successfully.", + "hex_output": "1a2b3c4d5e6f7080" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_v3.json" + }, + "init_outputs": { + "path": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]", + "cost": "4528" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "83746251920384756102" + }, + "init_outputs": { + "text_result": "Calculation pending verification from upstream nodes.", + "hex_result": "aabbccddeeff0011" + } + }, + "num_base_convert": { + "init_inputs": { + "s": "91827364509182736450", + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "text_rotN_c4a2": { + "init_inputs": { + "text": "Secret message awaiting rotation transformation" + }, + "init_outputs": {} + }, + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": "NFC" + } + } + }, + "intro_narrative": "You have infiltrated the abandoned sanctum of Archmage Velryn, a legendary sorcerer who sealed his greatest creation away centuries ago. The chamber is a dizzying array of magical apparatuses, cryptic scrolls, and arcane machinery humming with dormant power. Your ultimate goal is to navigate this complex web of enchanting devices and obtain the content of the sealed artifact, rumored to hold the secret of eternal mana. To succeed, you must understand how magical energies flow between the various instruments in the room. Be wary, for every tool, crystal, and relic is connected in a delicate, unseen magical ecosystem that must be perfectly balanced.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f3a2b1c9d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcd" + } + }, + "narrative": "The sealed artifact of ultimate power. It radiates an ancient, undeniable magic that calls to you." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A mysterious glowing geode humming with trapped magical essence." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A dusty hourglass filled with sparkling, enchanted sand." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence alpha completed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7080" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence alpha completed successfully.", + "hex_output": "1a2b3c4d5e6f7080" + } + }, + "narrative": "The spellweaving altar. It requires inputs from both the rune verifier and the celestial astrolabe to channel its magic." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "deadbeef12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "b1c0fa66" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2982214246 + } + ], + "init": { + "inputs": { + "hex": "deadbeef12345678" + }, + "outputs": {} + }, + "narrative": "A mystical rune verifier. It analyzes the purity of magical frequencies." + }, + { + "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": "Xli uymgo fvsar jsb nyqtw sziv xli pedc hsk" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "A celestial astrolabe. It processes data from the star-shift decoder to align cosmic coordinates." + }, + { + "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": "The quick brown fox jumps over the lazy dog" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "4528" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Xli uymgo fvsar jsb nyqtw sziv xli pedc hsk" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog" + }, + "outputs": {} + }, + "narrative": "A star-shift decoder. It needs the result from the harmony scales to unlock celestial patterns." + }, + { + "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": "4528" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "4528" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4528" + } + ], + "narrative": "The harmony scales. It requires inputs from both the leyline map and the elemental transmuter." + }, + { + "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_v3.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Qcapcr kcqqyec yuygrgle pmryrgml rpylqdmpkyrgml" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Calculation pending verification from upstream nodes." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4528" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v3.json" + }, + "outputs": { + "path": "[\"Server_A\", \"Switch_1\", \"Router_X\", \"Gateway_9\", \"Client_Z\"]", + "cost": "4528" + } + }, + "narrative": "A magical leyline map. It requires inputs from the true-name crystal and the moon-shift cipher." + }, + { + "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 pending verification from upstream nodes." + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Calculation pending verification from upstream nodes." + } + ], + "narrative": "A true-name crystal. It processes data from the archmage's lectern and the torn parchment." + }, + { + "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": "83746251920384756102" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "687149531605078719554640" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending verification from upstream nodes." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff0011" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "83746251920384756102" + }, + "outputs": { + "text_result": "Calculation pending verification from upstream nodes.", + "hex_result": "aabbccddeeff0011" + } + }, + "narrative": "The archmage's lectern. It requires input from the base alchemist's crucible to function." + }, + { + "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": "91827364509182736450" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "687149531605078719554640" + } + ], + "init": { + "inputs": { + "s": "91827364509182736450", + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The base alchemist's crucible. It transforms raw arcane energies into stable magical formats." + }, + { + "id": "num_base_convert_7803", + "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": "4528" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 2982214246 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "687149531605078719554640" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4528" + } + ], + "narrative": "An elemental transmuter. It requires inputs from the rune verifier, the leyline map, and the base alchemist's crucible." + }, + { + "id": "text_rotN_c4a2", + "name": "ROT-N Cipher", + "description": "Caesar shift by N.", + "type": "Tool", + "template_id": "text_rotN", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Secret message awaiting rotation transformation" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Qcapcr kcqqyec yuygrgle pmryrgml rpylqdmpkyrgml" + } + ], + "init": { + "inputs": { + "text": "Secret message awaiting rotation transformation" + }, + "outputs": {} + }, + "narrative": "A moon-shift cipher. It processes data from the rune verifier to translate lunar phases." + }, + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": "NFC" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "NFC" + } + }, + "narrative": "A torn piece of ancient parchment covered in faded magical script." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "text_rotN", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "iban" + }, + { + "source_id": "calc_gcd", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "n" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "terminal_2", + "target_id": "unicode_norm", + "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": "num2" + }, + { + "source_id": "terminal_2", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert_7803", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "text_rotN_c4a2", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "num_base_convert", + "target_id": "num_base_convert_7803", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN_c4a2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "item_2", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "content", + "target_port": "form" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/solution/solve.sh b/tasks/agentescape-15-skeleton-b79ed8ec/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/task.toml b/tasks/agentescape-15-skeleton-b79ed8ec/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6290ee9c74553370b6cf7c236aed9e25584f49cf --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "47ac1f545f36c330078c5fb2d261f0b73689e3bb88ee8a78a06467d726a41249" +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-b79ed8ec/tests/Dockerfile b/tasks/agentescape-15-skeleton-b79ed8ec/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/tests/expected.json b/tasks/agentescape-15-skeleton-b79ed8ec/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..d76d75679d9230b9ea28822ab530a61a9a1e29e2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "47ac1f545f36c330078c5fb2d261f0b73689e3bb88ee8a78a06467d726a41249", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-b79ed8ec/tests/grade.py b/tasks/agentescape-15-skeleton-b79ed8ec/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/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-b79ed8ec/tests/test.sh b/tasks/agentescape-15-skeleton-b79ed8ec/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-b79ed8ec/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/environment/Dockerfile b/tasks/agentescape-15-skeleton-bb9b5a90/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-bb9b5a90/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/agent/cli.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-bb9b5a90/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a5788c49a956bf6db2795f10d0c70f950fe8dcd --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90-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-bb9b5a90/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..994bad353db693bf9cc081b00139a2f26a0c48af --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/scenario.json @@ -0,0 +1,906 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "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_1", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_item", + "terminal_2", + "zip_unzip_file_9552", + "checksum_crc32_91b5", + "text_rotN" + ], + "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": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "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": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "zip_unzip_file_9552": { + "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" + } + } + }, + "checksum_crc32_91b5": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence complete. Terminal active.", + "hex_output": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", + "item_dispenser": "Standard access token item" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]", + "cost": "48291038475629384756" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "mission_logs_archive.zip" + }, + "init_outputs": { + "files": "network_graph_data.json" + } + }, + "zip_unzip_item": { + "init_inputs": { + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "91827364509182736450" + }, + "init_outputs": { + "text_result": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n", + "hex_result": "1234567890abcdef1234567890abcdef", + "math_token": "Calculated value token" + } + }, + "zip_unzip_file_9552": { + "init_inputs": { + "password": "HiddenLayerPass_99" + }, + "init_outputs": { + "files": "internal_package.zip" + } + }, + "checksum_crc32_91b5": { + "init_inputs": { + "hex": "deadbeefcafebabe1122334455667788" + }, + "init_outputs": {} + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog", + "n": "10000000000000000013" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an apprentice mechanist trapped in the legendary subterranean workshop of the eccentric inventor, Dr. Thaddeus Gearwright. The main boiler is rapidly overheating, and the blast doors have sealed shut. The air is thick with hissing steam, the smell of ozone, and the relentless clacking of brass gears. To prevent a catastrophic explosion and escape the facility, you must navigate a complex series of interconnected pneumatic devices and steam-powered analytical engines. Use logical deduction to restore the workshop's balance before the pressure gauge reaches the critical redline.", + "narrative_style": "steampunk" + }, + "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": "02a888a2ce9ad52e74e2bef8375b71c1d71b3bf7609fb3eb8a59ced67c05ca22" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9441be83" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2487336579 + } + ], + "narrative": "This is the Brass Chronometer. It requires input from the Steam-Powered Compressor. Activate this to finally stabilize the workshop and escape." + }, + { + "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": "Initialization sequence complete. Terminal active." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "02a888a2ce9ad52e74e2bef8375b71c1d71b3bf7609fb3eb8a59ced67c05ca22" + } + ], + "narrative": "This is the Steam-Powered Compressor. It requires input from the Main Cogwheel Terminal to compress the aether." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "48291038475629384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence complete. Terminal active." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard access token item" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence complete. Terminal active.", + "hex_output": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", + "item_dispenser": "Standard access token item" + } + }, + "narrative": "This is the Main Cogwheel Terminal. It requires inputs from both the Navigational Astrolabe and the Brass Cipher Wheel to activate." + }, + { + "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": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "odaq1Q==" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291038475629384756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]", + "cost": "48291038475629384756" + } + }, + "narrative": "This is the Navigational Astrolabe. It requires inputs from the Copper Pressure Cylinder, the Gearwork Translator, and the Auxiliary Valve Station." + }, + { + "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": "mission_logs_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "odaq1Q==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "mission_logs_archive.zip" + }, + "outputs": { + "files": "network_graph_data.json" + } + }, + "narrative": "This is a Copper Pressure Cylinder. It requires input from the Gearwork Translator to release its mechanical seal." + }, + { + "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": "a1d6aad5" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "odaq1Q==" + } + ], + "narrative": "This is a Gearwork Translator. It requires input from the Aether Resonance Chamber to begin processing." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A small, intricately carved Hidden Compartment Key." + }, + { + "id": "checksum_crc32_97eb", + "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": "5365637265745061796c6f6164466f724465636f64696e67" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a1d6aad5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2715200213 + } + ], + "narrative": "This is the Aether Resonance Chamber. It requires input from the Phonograph Decoder to stabilize its energy." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5365637265745061796c6f6164466f724465636f64696e67" + } + ], + "narrative": "This is a Phonograph Decoder. It requires input from the Auxiliary Valve Station to translate the audio signals." + }, + { + "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": "internal_package.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "CorrectHorseBatteryStaple" + }, + "outputs": {} + }, + "narrative": "This is an Iron Lockbox. It requires input from the Secondary Steam Vault to reveal what is hidden inside." + }, + { + "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": 2221453986 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "91827364509182736450" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Calculated value token" + } + ], + "init": { + "inputs": { + "num2": "91827364509182736450" + }, + "outputs": { + "text_result": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n", + "hex_result": "1234567890abcdef1234567890abcdef", + "math_token": "Calculated value token" + } + }, + "narrative": "This is the Auxiliary Valve Station. It requires input from the Pneumatic Calibrator to function properly." + }, + { + "id": "zip_unzip_file_9552", + "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_graph_data.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "HiddenLayerPass_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_package.zip" + } + ], + "init": { + "inputs": { + "password": "HiddenLayerPass_99" + }, + "outputs": { + "files": "internal_package.zip" + } + }, + "narrative": "This is a Secondary Steam Vault. It requires input from the Copper Pressure Cylinder to unlock its heavy doors." + }, + { + "id": "checksum_crc32_91b5", + "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": "deadbeefcafebabe1122334455667788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "8468b2a2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2221453986 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe1122334455667788" + }, + "outputs": {} + }, + "narrative": "A delicate Pneumatic Calibrator used to measure anomalous steam pressure within the pipes." + }, + { + "id": "item_16_907f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An old ticking Rusty Pocket Watch covered in soot and grease." + }, + { + "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": "The quick brown fox jumps over the lazy dog" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "10000000000000000013" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog", + "n": "10000000000000000013" + }, + "outputs": {} + }, + "narrative": "A complex rotating Brass Cipher Wheel covered in faded letters and Roman numerals." + } + ], + "edges": [ + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "terminal_1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_97eb", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32_97eb", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "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": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_9552", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_file_9552", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "data" + }, + { + "source_id": "checksum_crc32_91b5", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "item_16_907f", + "target_id": "checksum_crc32_91b5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_rotN", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-bb9b5a90/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/instruction.md b/tasks/agentescape-15-skeleton-bb9b5a90/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/solution/oracle.py b/tasks/agentescape-15-skeleton-bb9b5a90/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/solution/scenario.json b/tasks/agentescape-15-skeleton-bb9b5a90/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..994bad353db693bf9cc081b00139a2f26a0c48af --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/solution/scenario.json @@ -0,0 +1,906 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "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_1", + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_item", + "terminal_2", + "zip_unzip_file_9552", + "checksum_crc32_91b5", + "text_rotN" + ], + "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": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "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": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "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" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "zip_unzip_file_9552": { + "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" + } + } + }, + "checksum_crc32_91b5": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_rotN": { + "node_name": "ROT-N Cipher", + "node_type": "Tool", + "template_id": "text_rotN", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + }, + "n": { + "type": "Big_Int", + "description": "Shift N" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Initialization sequence complete. Terminal active.", + "hex_output": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", + "item_dispenser": "Standard access token item" + } + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]", + "cost": "48291038475629384756" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "mission_logs_archive.zip" + }, + "init_outputs": { + "files": "network_graph_data.json" + } + }, + "zip_unzip_item": { + "init_inputs": { + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num2": "91827364509182736450" + }, + "init_outputs": { + "text_result": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n", + "hex_result": "1234567890abcdef1234567890abcdef", + "math_token": "Calculated value token" + } + }, + "zip_unzip_file_9552": { + "init_inputs": { + "password": "HiddenLayerPass_99" + }, + "init_outputs": { + "files": "internal_package.zip" + } + }, + "checksum_crc32_91b5": { + "init_inputs": { + "hex": "deadbeefcafebabe1122334455667788" + }, + "init_outputs": {} + }, + "text_rotN": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog", + "n": "10000000000000000013" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an apprentice mechanist trapped in the legendary subterranean workshop of the eccentric inventor, Dr. Thaddeus Gearwright. The main boiler is rapidly overheating, and the blast doors have sealed shut. The air is thick with hissing steam, the smell of ozone, and the relentless clacking of brass gears. To prevent a catastrophic explosion and escape the facility, you must navigate a complex series of interconnected pneumatic devices and steam-powered analytical engines. Use logical deduction to restore the workshop's balance before the pressure gauge reaches the critical redline.", + "narrative_style": "steampunk" + }, + "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": "02a888a2ce9ad52e74e2bef8375b71c1d71b3bf7609fb3eb8a59ced67c05ca22" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9441be83" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2487336579 + } + ], + "narrative": "This is the Brass Chronometer. It requires input from the Steam-Powered Compressor. Activate this to finally stabilize the workshop and escape." + }, + { + "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": "Initialization sequence complete. Terminal active." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "02a888a2ce9ad52e74e2bef8375b71c1d71b3bf7609fb3eb8a59ced67c05ca22" + } + ], + "narrative": "This is the Steam-Powered Compressor. It requires input from the Main Cogwheel Terminal to compress the aether." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "48291038475629384756" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Initialization sequence complete. Terminal active." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard access token item" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Initialization sequence complete. Terminal active.", + "hex_output": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", + "item_dispenser": "Standard access token item" + } + }, + "narrative": "This is the Main Cogwheel Terminal. It requires inputs from both the Navigational Astrolabe and the Brass Cipher Wheel to activate." + }, + { + "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": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "odaq1Q==" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "48291038475629384756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"start_node\", \"alpha_junction\", \"beta_waypoint\", \"gamma_hub\", \"target_dest\"]", + "cost": "48291038475629384756" + } + }, + "narrative": "This is the Navigational Astrolabe. It requires inputs from the Copper Pressure Cylinder, the Gearwork Translator, and the Auxiliary Valve Station." + }, + { + "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": "mission_logs_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "odaq1Q==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "mission_logs_archive.zip" + }, + "outputs": { + "files": "network_graph_data.json" + } + }, + "narrative": "This is a Copper Pressure Cylinder. It requires input from the Gearwork Translator to release its mechanical seal." + }, + { + "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": "a1d6aad5" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "odaq1Q==" + } + ], + "narrative": "This is a Gearwork Translator. It requires input from the Aether Resonance Chamber to begin processing." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A small, intricately carved Hidden Compartment Key." + }, + { + "id": "checksum_crc32_97eb", + "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": "5365637265745061796c6f6164466f724465636f64696e67" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a1d6aad5" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2715200213 + } + ], + "narrative": "This is the Aether Resonance Chamber. It requires input from the Phonograph Decoder to stabilize its energy." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5365637265745061796c6f6164466f724465636f64696e67" + } + ], + "narrative": "This is a Phonograph Decoder. It requires input from the Auxiliary Valve Station to translate the audio signals." + }, + { + "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": "internal_package.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "CorrectHorseBatteryStaple" + }, + "outputs": {} + }, + "narrative": "This is an Iron Lockbox. It requires input from the Secondary Steam Vault to reveal what is hidden inside." + }, + { + "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": 2221453986 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "91827364509182736450" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Calculated value token" + } + ], + "init": { + "inputs": { + "num2": "91827364509182736450" + }, + "outputs": { + "text_result": "U2VjcmV0UGF5bG9hZEZvckRlY29kaW5n", + "hex_result": "1234567890abcdef1234567890abcdef", + "math_token": "Calculated value token" + } + }, + "narrative": "This is the Auxiliary Valve Station. It requires input from the Pneumatic Calibrator to function properly." + }, + { + "id": "zip_unzip_file_9552", + "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_graph_data.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "HiddenLayerPass_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_package.zip" + } + ], + "init": { + "inputs": { + "password": "HiddenLayerPass_99" + }, + "outputs": { + "files": "internal_package.zip" + } + }, + "narrative": "This is a Secondary Steam Vault. It requires input from the Copper Pressure Cylinder to unlock its heavy doors." + }, + { + "id": "checksum_crc32_91b5", + "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": "deadbeefcafebabe1122334455667788" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "8468b2a2" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2221453986 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe1122334455667788" + }, + "outputs": {} + }, + "narrative": "A delicate Pneumatic Calibrator used to measure anomalous steam pressure within the pipes." + }, + { + "id": "item_16_907f", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An old ticking Rusty Pocket Watch covered in soot and grease." + }, + { + "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": "The quick brown fox jumps over the lazy dog" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "10000000000000000013" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog", + "n": "10000000000000000013" + }, + "outputs": {} + }, + "narrative": "A complex rotating Brass Cipher Wheel covered in faded letters and Roman numerals." + } + ], + "edges": [ + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1", + "target_id": "hash_sha256", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "terminal_1", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "checksum_crc32_97eb", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "base64_decode", + "target_id": "checksum_crc32_97eb", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "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": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_9552", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file", + "target_id": "zip_unzip_file_9552", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "terminal_2", + "target_id": "base64_decode", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "data" + }, + { + "source_id": "checksum_crc32_91b5", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "item_16_907f", + "target_id": "checksum_crc32_91b5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_rotN", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/solution/solve.sh b/tasks/agentescape-15-skeleton-bb9b5a90/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/task.toml b/tasks/agentescape-15-skeleton-bb9b5a90/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0132bcd87de9ed8a73351ae65477659a57168acd --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "2be7eb7c7b37df98be74e69e7529251718a21eea79bde36292f54416f39bdb52" +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-bb9b5a90/tests/Dockerfile b/tasks/agentescape-15-skeleton-bb9b5a90/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/tests/expected.json b/tasks/agentescape-15-skeleton-bb9b5a90/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0f3c0d0dd7b312c88f3d6129e7537f66caba7021 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "2be7eb7c7b37df98be74e69e7529251718a21eea79bde36292f54416f39bdb52", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bb9b5a90/tests/grade.py b/tasks/agentescape-15-skeleton-bb9b5a90/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/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-bb9b5a90/tests/test.sh b/tasks/agentescape-15-skeleton-bb9b5a90/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bb9b5a90/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-bce77c44/environment/Dockerfile b/tasks/agentescape-15-skeleton-bce77c44/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-bce77c44/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/agent/cli.py b/tasks/agentescape-15-skeleton-bce77c44/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-bce77c44/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1a28e3418937a065694ac54a0154582ae2c211a1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44-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-bce77c44/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1ce2f8ccfa97563811814e9f539f9eed8aa1ab03 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/scenario.json @@ -0,0 +1,997 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "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": [ + "graph_shortest_path", + "graph_shortest_path_e3d6", + "zip_unzip_file", + "hex_decode", + "zip_unzip_file_728d", + "zip_unzip_file_3efd", + "zip_unzip_file_7bb0", + "base64_decode", + "terminal_1", + "terminal_1_ff4b" + ], + "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" + } + } + }, + "graph_shortest_path_e3d6": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_728d": { + "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_3efd": { + "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" + } + } + }, + "zip_unzip_file_7bb0": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + }, + "terminal_1_ff4b": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "82736451928374651029" + } + }, + "graph_shortest_path_e3d6": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]", + "cost": "19283746556473829102" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "payload_config.json" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c64212054686973206973206120746573742e" + }, + "init_outputs": {} + }, + "zip_unzip_file_728d": { + "init_inputs": { + "password": "SecurePassword!2024" + }, + "init_outputs": { + "files": "hidden_manifest.xml" + } + }, + "zip_unzip_file_3efd": { + "init_inputs": { + "zip_id": "project_alpha_archive.zip" + }, + "init_outputs": { + "files": "source_code_v2.py" + } + }, + "zip_unzip_file_7bb0": { + "init_inputs": { + "zip_id": "financial_report_2023.zip" + }, + "init_outputs": { + "files": "q3_earnings_data.csv" + } + }, + "base64_decode": { + "init_inputs": { + "data": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_b": "3847562910384756291038" + }, + "init_outputs": { + "text_output": "Terminal initialized successfully. Status: Operational.", + "hex_output": "aabbccddeeff00112233445566778899" + } + }, + "terminal_1_ff4b": { + "init_inputs": { + "slot_a": "Initiate system override sequence immediately.", + "slot_b": "9102938475610293847561" + }, + "init_outputs": { + "text_output": "Override command accepted. Processing request...", + "hex_output": "1234567890abcdef1234567890abcdef", + "item_dispenser": "You found a small dispensed ticket with number 42." + } + } + }, + "intro_narrative": "You awaken in the belly of the Airborne Leviathan, a colossal steam-powered airship rapidly losing altitude. The master chronometer has locked the main engine controls, and the air is thick with the smell of burning coal, hot oil, and the sharp hiss of escaping steam. Around you lies a complex network of brass contraptions, locked steel vaults, and pressure terminals interconnected by intricate copper piping. Your objective is to trace the flow of information through these mechanical marvels and restore the power sequence before the airship crashes. You must carefully navigate the gear-driven machines, using the correct outputs from one device to fuel the next, ultimately overriding the system.", + "narrative_style": "steampunk" + }, + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "19283746556473829102" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Xyno_Kvzrk\", \"Xyno_Lodk\", \"Xyno_Qkwwk\", \"Xyno_Novdk\", \"Xyno_Ozcsvyx\", \"Xyno_Jodk\"]" + } + ], + "narrative": "This is The Master Chronometer, the heart of the ship's control. It requires inputs from both The Grand Orrery and The Navigator's Astrolabe to finally override the lockdown." + }, + { + "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": "hidden_manifest.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "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": "82736451928374651029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "82736451928374651029" + } + }, + "narrative": "This is The Grand Orrery. It requires inputs from The Navigator's Astrolabe, The Steam Encoder, and The Aether Vault to align its mechanical planets." + }, + { + "id": "graph_shortest_path_e3d6", + "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": "payload_config.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello World! This is a test." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "19283746556473829102" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]", + "cost": "19283746556473829102" + } + }, + "narrative": "This is The Navigator's Astrolabe. It requires inputs from The Bronze Cylinder, The Steam Encoder, and The Brass Decryptor to chart its course." + }, + { + "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": "source_code_v2.py" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Hello World! This is a test." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "payload_config.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "payload_config.json" + } + }, + "narrative": "This is The Bronze Cylinder. It requires inputs from both The Iron Lockbox and The Brass Decryptor to open." + }, + { + "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": "48656c6c6f20576f726c64212054686973206973206120746573742e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World! This is a test." + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c64212054686973206973206120746573742e" + }, + "outputs": {} + }, + "narrative": "This is The Brass Decryptor. An old, gear-driven decryption device covered in intricate dials." + }, + { + "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": "5468697320697320612073616d706c652042617365363420656e636f64656420737472696e6720666f722074657374696e672e" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "narrative": "This is The Steam Encoder. It processes data from The Copper Translator. Feed it the result from the translator to activate its gears." + }, + { + "id": "zip_unzip_file_728d", + "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": "q3_earnings_data.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "hidden_manifest.xml" + } + ], + "init": { + "inputs": { + "password": "SecurePassword!2024" + }, + "outputs": { + "files": "hidden_manifest.xml" + } + }, + "narrative": "This is The Aether Vault. It requires input from The Steel Safe to unlock its pressurized mechanisms." + }, + { + "id": "zip_unzip_file_3efd", + "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": "project_alpha_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Hello World! This is a test." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "source_code_v2.py" + } + ], + "init": { + "inputs": { + "zip_id": "project_alpha_archive.zip" + }, + "outputs": { + "files": "source_code_v2.py" + } + }, + "narrative": "This is The Iron Lockbox. It requires input from The Brass Decryptor to spring its heavy latches." + }, + { + "id": "zip_unzip_file_7bb0", + "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": "financial_report_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "q3_earnings_data.csv" + } + ], + "init": { + "inputs": { + "zip_id": "financial_report_2023.zip" + }, + "outputs": { + "files": "q3_earnings_data.csv" + } + }, + "narrative": "This is The Steel Safe. It requires input from The Navigator's Astrolabe to bypass its intricate tumbler security." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5468697320697320612073616d706c652042617365363420656e636f64656420737472696e6720666f722074657374696e672e" + } + ], + "init": { + "inputs": { + "data": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + }, + "outputs": {} + }, + "narrative": "This is The Copper Translator. A strange contraption emitting a faint hiss of steam." + }, + { + "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 mechanical valve. A solid brass piece used for regulating high-pressure steam." + }, + { + "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 polished gear. Its teeth are perfectly aligned for delicate machinery." + }, + { + "id": "item_8_1df5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A rusted cogwheel. It seems discarded but might be part of a larger mechanism." + }, + { + "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": "Override command accepted. Processing request..." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3847562910384756291038" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized successfully. Status: Operational." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff00112233445566778899" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "3847562910384756291038" + }, + "outputs": { + "text_output": "Terminal initialized successfully. Status: Operational.", + "hex_output": "aabbccddeeff00112233445566778899" + } + }, + "narrative": "This is The Secondary Pressure Terminal. It requires input from The Primary Boiler Console to function properly." + }, + { + "id": "terminal_1_ff4b", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initiate system override sequence immediately." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "9102938475610293847561" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Override command accepted. Processing request..." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "You found a small dispensed ticket with number 42." + } + ], + "init": { + "inputs": { + "slot_a": "Initiate system override sequence immediately.", + "slot_b": "9102938475610293847561" + }, + "outputs": { + "text_output": "Override command accepted. Processing request...", + "hex_output": "1234567890abcdef1234567890abcdef", + "item_dispenser": "You found a small dispensed ticket with number 42." + } + }, + "narrative": "This is The Primary Boiler Console. A sturdy interface with glowing vacuum tubes and heavy iron levers." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_728d", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_3efd", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_7bb0", + "target_id": "zip_unzip_file_728d", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "base64_decode", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file_3efd", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_3efd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file_728d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "zip_unzip_file_7bb0", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_8_1df5", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1_ff4b", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "slot_a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-bce77c44/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/instruction.md b/tasks/agentescape-15-skeleton-bce77c44/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/solution/oracle.py b/tasks/agentescape-15-skeleton-bce77c44/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/solution/scenario.json b/tasks/agentescape-15-skeleton-bce77c44/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1ce2f8ccfa97563811814e9f539f9eed8aa1ab03 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/solution/scenario.json @@ -0,0 +1,997 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "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": [ + "graph_shortest_path", + "graph_shortest_path_e3d6", + "zip_unzip_file", + "hex_decode", + "zip_unzip_file_728d", + "zip_unzip_file_3efd", + "zip_unzip_file_7bb0", + "base64_decode", + "terminal_1", + "terminal_1_ff4b" + ], + "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" + } + } + }, + "graph_shortest_path_e3d6": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "hex_decode": { + "node_name": "Hex to Text Decoder", + "node_type": "Tool", + "template_id": "hex_decode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex string" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_728d": { + "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_3efd": { + "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" + } + } + }, + "zip_unzip_file_7bb0": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_decode": { + "node_name": "Base64 Decoder", + "node_type": "Tool", + "template_id": "base64_decode", + "init_inputs": { + "data": { + "type": "Text_Generic", + "description": "Base64 string" + } + }, + "init_outputs": {} + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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" + } + } + }, + "terminal_1_ff4b": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + }, + "slot_b": { + "type": "Big_Int", + "description": "Input Slot B" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "82736451928374651029" + } + }, + "graph_shortest_path_e3d6": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]", + "cost": "19283746556473829102" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "payload_config.json" + } + }, + "hex_decode": { + "init_inputs": { + "hex": "48656c6c6f20576f726c64212054686973206973206120746573742e" + }, + "init_outputs": {} + }, + "zip_unzip_file_728d": { + "init_inputs": { + "password": "SecurePassword!2024" + }, + "init_outputs": { + "files": "hidden_manifest.xml" + } + }, + "zip_unzip_file_3efd": { + "init_inputs": { + "zip_id": "project_alpha_archive.zip" + }, + "init_outputs": { + "files": "source_code_v2.py" + } + }, + "zip_unzip_file_7bb0": { + "init_inputs": { + "zip_id": "financial_report_2023.zip" + }, + "init_outputs": { + "files": "q3_earnings_data.csv" + } + }, + "base64_decode": { + "init_inputs": { + "data": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + }, + "init_outputs": {} + }, + "terminal_1": { + "init_inputs": { + "slot_b": "3847562910384756291038" + }, + "init_outputs": { + "text_output": "Terminal initialized successfully. Status: Operational.", + "hex_output": "aabbccddeeff00112233445566778899" + } + }, + "terminal_1_ff4b": { + "init_inputs": { + "slot_a": "Initiate system override sequence immediately.", + "slot_b": "9102938475610293847561" + }, + "init_outputs": { + "text_output": "Override command accepted. Processing request...", + "hex_output": "1234567890abcdef1234567890abcdef", + "item_dispenser": "You found a small dispensed ticket with number 42." + } + } + }, + "intro_narrative": "You awaken in the belly of the Airborne Leviathan, a colossal steam-powered airship rapidly losing altitude. The master chronometer has locked the main engine controls, and the air is thick with the smell of burning coal, hot oil, and the sharp hiss of escaping steam. Around you lies a complex network of brass contraptions, locked steel vaults, and pressure terminals interconnected by intricate copper piping. Your objective is to trace the flow of information through these mechanical marvels and restore the power sequence before the airship crashes. You must carefully navigate the gear-driven machines, using the correct outputs from one device to fuel the next, ultimately overriding the system.", + "narrative_style": "steampunk" + }, + "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": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": "19283746556473829102" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[\"Xyno_Kvzrk\", \"Xyno_Lodk\", \"Xyno_Qkwwk\", \"Xyno_Novdk\", \"Xyno_Ozcsvyx\", \"Xyno_Jodk\"]" + } + ], + "narrative": "This is The Master Chronometer, the heart of the ship's control. It requires inputs from both The Grand Orrery and The Navigator's Astrolabe to finally override the lockdown." + }, + { + "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": "hidden_manifest.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "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": "82736451928374651029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta\"]", + "cost": "82736451928374651029" + } + }, + "narrative": "This is The Grand Orrery. It requires inputs from The Navigator's Astrolabe, The Steam Encoder, and The Aether Vault to align its mechanical planets." + }, + { + "id": "graph_shortest_path_e3d6", + "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": "payload_config.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Hello World! This is a test." + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "19283746556473829102" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]", + "cost": "19283746556473829102" + } + }, + "narrative": "This is The Navigator's Astrolabe. It requires inputs from The Bronze Cylinder, The Steam Encoder, and The Brass Decryptor to chart its course." + }, + { + "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": "source_code_v2.py" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Hello World! This is a test." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "payload_config.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "payload_config.json" + } + }, + "narrative": "This is The Bronze Cylinder. It requires inputs from both The Iron Lockbox and The Brass Decryptor to open." + }, + { + "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": "48656c6c6f20576f726c64212054686973206973206120746573742e" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "Hello World! This is a test." + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c64212054686973206973206120746573742e" + }, + "outputs": {} + }, + "narrative": "This is The Brass Decryptor. An old, gear-driven decryption device covered in intricate dials." + }, + { + "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": "5468697320697320612073616d706c652042617365363420656e636f64656420737472696e6720666f722074657374696e672e" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "narrative": "This is The Steam Encoder. It processes data from The Copper Translator. Feed it the result from the translator to activate its gears." + }, + { + "id": "zip_unzip_file_728d", + "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": "q3_earnings_data.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "hidden_manifest.xml" + } + ], + "init": { + "inputs": { + "password": "SecurePassword!2024" + }, + "outputs": { + "files": "hidden_manifest.xml" + } + }, + "narrative": "This is The Aether Vault. It requires input from The Steel Safe to unlock its pressurized mechanisms." + }, + { + "id": "zip_unzip_file_3efd", + "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": "project_alpha_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Hello World! This is a test." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "source_code_v2.py" + } + ], + "init": { + "inputs": { + "zip_id": "project_alpha_archive.zip" + }, + "outputs": { + "files": "source_code_v2.py" + } + }, + "narrative": "This is The Iron Lockbox. It requires input from The Brass Decryptor to spring its heavy latches." + }, + { + "id": "zip_unzip_file_7bb0", + "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": "financial_report_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"Gateway\", \"Router_1\", \"Switch_Core\", \"Firewall_Ext\", \"Load_Balancer\", \"Server_Main\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "q3_earnings_data.csv" + } + ], + "init": { + "inputs": { + "zip_id": "financial_report_2023.zip" + }, + "outputs": { + "files": "q3_earnings_data.csv" + } + }, + "narrative": "This is The Steel Safe. It requires input from The Navigator's Astrolabe to bypass its intricate tumbler security." + }, + { + "id": "base64_decode", + "name": "Base64 Decoder", + "description": "Decode base64 to hex bytes.", + "type": "Tool", + "template_id": "base64_decode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "data", + "type": "Text_Generic", + "description": "Base64 string", + "value": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + } + ], + "outputs": [ + { + "name": "bytes_hex", + "type": "Hex_String", + "description": "Decoded bytes as Hex", + "value": "5468697320697320612073616d706c652042617365363420656e636f64656420737472696e6720666f722074657374696e672e" + } + ], + "init": { + "inputs": { + "data": "VGhpcyBpcyBhIHNhbXBsZSBCYXNlNjQgZW5jb2RlZCBzdHJpbmcgZm9yIHRlc3Rpbmcu" + }, + "outputs": {} + }, + "narrative": "This is The Copper Translator. A strange contraption emitting a faint hiss of steam." + }, + { + "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 mechanical valve. A solid brass piece used for regulating high-pressure steam." + }, + { + "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 polished gear. Its teeth are perfectly aligned for delicate machinery." + }, + { + "id": "item_8_1df5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A rusted cogwheel. It seems discarded but might be part of a larger mechanism." + }, + { + "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": "Override command accepted. Processing request..." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "3847562910384756291038" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialized successfully. Status: Operational." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff00112233445566778899" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_b": "3847562910384756291038" + }, + "outputs": { + "text_output": "Terminal initialized successfully. Status: Operational.", + "hex_output": "aabbccddeeff00112233445566778899" + } + }, + "narrative": "This is The Secondary Pressure Terminal. It requires input from The Primary Boiler Console to function properly." + }, + { + "id": "terminal_1_ff4b", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Initiate system override sequence immediately." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "9102938475610293847561" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Override command accepted. Processing request..." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "You found a small dispensed ticket with number 42." + } + ], + "init": { + "inputs": { + "slot_a": "Initiate system override sequence immediately.", + "slot_b": "9102938475610293847561" + }, + "outputs": { + "text_output": "Override command accepted. Processing request...", + "hex_output": "1234567890abcdef1234567890abcdef", + "item_dispenser": "You found a small dispensed ticket with number 42." + } + }, + "narrative": "This is The Primary Boiler Console. A sturdy interface with glowing vacuum tubes and heavy iron levers." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "base64_encode", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "dst" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path_e3d6", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_file_728d", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_3efd", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_7bb0", + "target_id": "zip_unzip_file_728d", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "base64_decode", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "bytes_hex", + "target_port": "hex" + }, + { + "source_id": "hex_decode", + "target_id": "zip_unzip_file_3efd", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file_3efd", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_8", + "target_id": "zip_unzip_file_728d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "graph_shortest_path_e3d6", + "target_id": "zip_unzip_file_7bb0", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_8_1df5", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "terminal_1_ff4b", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "slot_a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bce77c44/solution/solve.sh b/tasks/agentescape-15-skeleton-bce77c44/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-bce77c44/task.toml b/tasks/agentescape-15-skeleton-bce77c44/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c3b40160dc9a166f72fa10d070af11d2d87478ac --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a72d7793dc9e7ce02fbace5ec7af271a938ade829d3a893f944637819c525c27" +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-bce77c44/tests/Dockerfile b/tasks/agentescape-15-skeleton-bce77c44/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-bce77c44/tests/expected.json b/tasks/agentescape-15-skeleton-bce77c44/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5c8b107e0198696521b05c2e0657e9d2b7a4a748 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a72d7793dc9e7ce02fbace5ec7af271a938ade829d3a893f944637819c525c27", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bce77c44/tests/grade.py b/tasks/agentescape-15-skeleton-bce77c44/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/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-bce77c44/tests/test.sh b/tasks/agentescape-15-skeleton-bce77c44/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bce77c44/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-bdececa9/environment/Dockerfile b/tasks/agentescape-15-skeleton-bdececa9/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-bdececa9/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/agent/cli.py b/tasks/agentescape-15-skeleton-bdececa9/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-bdececa9/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b91c0a2eb70a41079039ef48c07020c1d6325851 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9-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-bdececa9/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2166468f68cc9c53095c199f50b4b7efe72ef7d6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/scenario.json @@ -0,0 +1,1049 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_2736", + "zip_unzip_file_6df4", + "csv_query", + "zip_unzip_file_f4aa", + "zip_unzip_file_ecd9", + "container_3", + "unicode_norm", + "zip_unzip_item", + "zip_unzip_file_ac72", + "graph_shortest_path_874d" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_2736": { + "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_6df4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_f4aa": { + "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" + } + } + }, + "zip_unzip_file_ecd9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "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": {} + }, + "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": {} + }, + "zip_unzip_file_ac72": { + "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" + } + } + }, + "graph_shortest_path_874d": { + "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": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]", + "cost": "38294710293847561029" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "sec_Alpha_v3_2024" + }, + "init_outputs": { + "files": "unpacked_v1_0.zip" + } + }, + "zip_unzip_file_2736": { + "init_inputs": {}, + "init_outputs": { + "files": "topology_data_final.csv" + } + }, + "zip_unzip_file_6df4": { + "init_inputs": {}, + "init_outputs": { + "files": "graph_edges_manifest.json" + } + }, + "csv_query": { + "init_inputs": { + "where": "category='node_link' AND weight < 100" + }, + "init_outputs": { + "rows": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + }, + "zip_unzip_file_f4aa": { + "init_inputs": { + "zip_id": "encrypted_source_04.zip" + }, + "init_outputs": { + "files": "temp_buffer_99.txt" + } + }, + "zip_unzip_file_ecd9": { + "init_inputs": { + "zip_id": "vault_storage_beta.zip", + "password": "Unlock_Key_99812_Gamma" + }, + "init_outputs": { + "files": "extracted_database.csv" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "918273645019283746556677889900" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Unicode_Normalization_Standard_Reference_String", + "form": "NFC" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "Item_Access_Pass_881" + }, + "init_outputs": {} + }, + "zip_unzip_file_ac72": { + "init_inputs": { + "zip_id": "resource_package_x.zip" + }, + "init_outputs": { + "files": "node_definition_config.json" + } + }, + "graph_shortest_path_874d": { + "init_inputs": { + "file_id": "coordinate_map_v9.json", + "src": "Terminal_Alpha_0", + "dst": "Terminal_Omega_9" + }, + "init_outputs": { + "path": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]", + "cost": "29384756102938475610" + } + } + }, + "intro_narrative": "The sky above is a perpetual bruised purple, choked with radioactive dust. You are a wasteland scavenger who just stumbled upon a massive find: an intact pre-war military bunker. Rumor has it this facility houses the master override for the automated defense grid that's been terrorizing the remaining settlements. As the heavy steel doors seal behind you to block out the incoming mutant horde, the facility's emergency lights flicker to life. You must navigate the remnants of the bunker's fragmented mainframe and broadcast the final shutdown signal before the bunker's life support runs out.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b22456e7472616e63655f47617465222c20224d61696e5f48616c6c222c2022436f727269646f725f41222c20224c6962726172795f45617374222c202252656164696e675f526f6f6d5f3034222c2022417263686976655f53656374696f6e225d" + } + ], + "narrative": "This is the Final Signal Transmitter. It requires input from the Network Router Terminal to officially broadcast the defense grid shutdown sequence." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": 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": "unpacked_v1_0.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38294710293847561029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]", + "cost": "38294710293847561029" + } + }, + "narrative": "This is the Network Router Terminal. It requires inputs from the Core Archive Extractor, the Wasteland Database, and the Signal Stabilizer to map the final system connection." + }, + { + "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_data_final.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "sec_Alpha_v3_2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unpacked_v1_0.zip" + } + ], + "init": { + "inputs": { + "password": "sec_Alpha_v3_2024" + }, + "outputs": { + "files": "unpacked_v1_0.zip" + } + }, + "narrative": "This is the Core Archive Extractor. It requires input from the Secondary Archive Extractor to finally reveal the bunker's core logic routines." + }, + { + "id": "zip_unzip_file_2736", + "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": "graph_edges_manifest.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_data_final.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "topology_data_final.csv" + } + }, + "narrative": "This is the Secondary Archive Extractor. It requires inputs from both the Tertiary Archive Extractor and the Wasteland Database to unlock its isolated files." + }, + { + "id": "zip_unzip_file_6df4", + "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": "temp_buffer_99.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "graph_edges_manifest.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "graph_edges_manifest.json" + } + }, + "narrative": "This is the Tertiary Archive Extractor. It requires inputs from both the Wasteland Database and the Quarantine Archive Extractor to process the next layer of encrypted archives." + }, + { + "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_database.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "category='node_link' AND weight < 100" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "init": { + "inputs": { + "where": "category='node_link' AND weight < 100" + }, + "outputs": { + "rows": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + }, + "narrative": "This is the Wasteland Database. It requires inputs from both the Ruins Archive Extractor and the Signal Stabilizer to parse the surviving pre-war records." + }, + { + "id": "zip_unzip_file_f4aa", + "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": "encrypted_source_04.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "temp_buffer_99.txt" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_source_04.zip" + }, + "outputs": { + "files": "temp_buffer_99.txt" + } + }, + "narrative": "This is the Quarantine Archive Extractor. It requires input from the Wasteland Database to bypass the military quarantine protocols." + }, + { + "id": "zip_unzip_file_ecd9", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "vault_storage_beta.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Key_99812_Gamma" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_database.csv" + } + ], + "init": { + "inputs": { + "zip_id": "vault_storage_beta.zip", + "password": "Unlock_Key_99812_Gamma" + }, + "outputs": { + "files": "extracted_database.csv" + } + }, + "narrative": "An offline Ruins Archive Extractor hooked up to a rusted fusion generator." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "918273645019283746556677889900" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "918273645019283746556677889900" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Lockbox with a cracked glass scanner on its lid." + }, + { + "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 degraded Rusted Memory Module salvaged from the chassis of a dead android." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Unicode_Normalization_Standard_Reference_String" + } + ], + "init": { + "inputs": { + "text": "Unicode_Normalization_Standard_Reference_String", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "A bulky Signal Stabilizer salvaged from a fallen communications tower." + }, + { + "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": "node_definition_config.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Item_Access_Pass_881" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "Item_Access_Pass_881" + }, + "outputs": {} + }, + "narrative": "This is a Supply Cache Decoder. It requires input from the Outpost Archive Extractor to function properly." + }, + { + "id": "zip_unzip_file_ac72", + "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": "resource_package_x.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "node_definition_config.json" + } + ], + "init": { + "inputs": { + "zip_id": "resource_package_x.zip" + }, + "outputs": { + "files": "node_definition_config.json" + } + }, + "narrative": "This is the Outpost Archive Extractor. It requires input from the Sector Mapping Terminal to initiate its extraction process." + }, + { + "id": "graph_shortest_path_874d", + "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": "coordinate_map_v9.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Terminal_Alpha_0" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Terminal_Omega_9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "29384756102938475610" + } + ], + "init": { + "inputs": { + "file_id": "coordinate_map_v9.json", + "src": "Terminal_Alpha_0", + "dst": "Terminal_Omega_9" + }, + "outputs": { + "path": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]", + "cost": "29384756102938475610" + } + }, + "narrative": "An old Sector Mapping Terminal covered in a thick layer of radioactive dust." + }, + { + "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 delicate Temporal Synchronizer emitting a faint, pulsing blue glow." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_2736", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_6df4", + "target_id": "zip_unzip_file_2736", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "dst" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_6df4", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_f4aa", + "target_id": "zip_unzip_file_6df4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_f4aa", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_ecd9", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_3", + "target_id": "zip_unzip_file_ecd9", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_2736", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_item", + "target_id": "unicode_norm", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "unicode_norm", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file_ac72", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_874d", + "target_id": "zip_unzip_file_ac72", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_16", + "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-bdececa9/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-bdececa9/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/instruction.md b/tasks/agentescape-15-skeleton-bdececa9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/solution/oracle.py b/tasks/agentescape-15-skeleton-bdececa9/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/solution/scenario.json b/tasks/agentescape-15-skeleton-bdececa9/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2166468f68cc9c53095c199f50b4b7efe72ef7d6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/solution/scenario.json @@ -0,0 +1,1049 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "hex_encode", + "win_condition": { + "type": "tool_output", + "node_id": "hex_encode", + "output_port": "hex", + "output_type": "Hex_String", + "description": "Execute Text to Hex Encoder and get the output from port 'hex'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "zip_unzip_file_2736", + "zip_unzip_file_6df4", + "csv_query", + "zip_unzip_file_f4aa", + "zip_unzip_file_ecd9", + "container_3", + "unicode_norm", + "zip_unzip_item", + "zip_unzip_file_ac72", + "graph_shortest_path_874d" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": {}, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_2736": { + "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_6df4": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_f4aa": { + "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" + } + } + }, + "zip_unzip_file_ecd9": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "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": {} + }, + "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": {} + }, + "zip_unzip_file_ac72": { + "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" + } + } + }, + "graph_shortest_path_874d": { + "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": { + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]", + "cost": "38294710293847561029" + } + }, + "zip_unzip_file": { + "init_inputs": { + "password": "sec_Alpha_v3_2024" + }, + "init_outputs": { + "files": "unpacked_v1_0.zip" + } + }, + "zip_unzip_file_2736": { + "init_inputs": {}, + "init_outputs": { + "files": "topology_data_final.csv" + } + }, + "zip_unzip_file_6df4": { + "init_inputs": {}, + "init_outputs": { + "files": "graph_edges_manifest.json" + } + }, + "csv_query": { + "init_inputs": { + "where": "category='node_link' AND weight < 100" + }, + "init_outputs": { + "rows": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + }, + "zip_unzip_file_f4aa": { + "init_inputs": { + "zip_id": "encrypted_source_04.zip" + }, + "init_outputs": { + "files": "temp_buffer_99.txt" + } + }, + "zip_unzip_file_ecd9": { + "init_inputs": { + "zip_id": "vault_storage_beta.zip", + "password": "Unlock_Key_99812_Gamma" + }, + "init_outputs": { + "files": "extracted_database.csv" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "918273645019283746556677889900" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "text": "Unicode_Normalization_Standard_Reference_String", + "form": "NFC" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "Item_Access_Pass_881" + }, + "init_outputs": {} + }, + "zip_unzip_file_ac72": { + "init_inputs": { + "zip_id": "resource_package_x.zip" + }, + "init_outputs": { + "files": "node_definition_config.json" + } + }, + "graph_shortest_path_874d": { + "init_inputs": { + "file_id": "coordinate_map_v9.json", + "src": "Terminal_Alpha_0", + "dst": "Terminal_Omega_9" + }, + "init_outputs": { + "path": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]", + "cost": "29384756102938475610" + } + } + }, + "intro_narrative": "The sky above is a perpetual bruised purple, choked with radioactive dust. You are a wasteland scavenger who just stumbled upon a massive find: an intact pre-war military bunker. Rumor has it this facility houses the master override for the automated defense grid that's been terrorizing the remaining settlements. As the heavy steel doors seal behind you to block out the incoming mutant horde, the facility's emergency lights flicker to life. You must navigate the remnants of the bunker's fragmented mainframe and broadcast the final shutdown signal before the bunker's life support runs out.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "id": "hex_encode", + "name": "Text to Hex Encoder", + "description": "Encode UTF-8 text to hex.", + "type": "Tool", + "template_id": "hex_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "5b22456e7472616e63655f47617465222c20224d61696e5f48616c6c222c2022436f727269646f725f41222c20224c6962726172795f45617374222c202252656164696e675f526f6f6d5f3034222c2022417263686976655f53656374696f6e225d" + } + ], + "narrative": "This is the Final Signal Transmitter. It requires input from the Network Router Terminal to officially broadcast the defense grid shutdown sequence." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": 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": "unpacked_v1_0.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38294710293847561029" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Entrance_Gate\", \"Main_Hall\", \"Corridor_A\", \"Library_East\", \"Reading_Room_04\", \"Archive_Section\"]", + "cost": "38294710293847561029" + } + }, + "narrative": "This is the Network Router Terminal. It requires inputs from the Core Archive Extractor, the Wasteland Database, and the Signal Stabilizer to map the final system connection." + }, + { + "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_data_final.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "sec_Alpha_v3_2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "unpacked_v1_0.zip" + } + ], + "init": { + "inputs": { + "password": "sec_Alpha_v3_2024" + }, + "outputs": { + "files": "unpacked_v1_0.zip" + } + }, + "narrative": "This is the Core Archive Extractor. It requires input from the Secondary Archive Extractor to finally reveal the bunker's core logic routines." + }, + { + "id": "zip_unzip_file_2736", + "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": "graph_edges_manifest.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "topology_data_final.csv" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "topology_data_final.csv" + } + }, + "narrative": "This is the Secondary Archive Extractor. It requires inputs from both the Tertiary Archive Extractor and the Wasteland Database to unlock its isolated files." + }, + { + "id": "zip_unzip_file_6df4", + "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": "temp_buffer_99.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "graph_edges_manifest.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "graph_edges_manifest.json" + } + }, + "narrative": "This is the Tertiary Archive Extractor. It requires inputs from both the Wasteland Database and the Quarantine Archive Extractor to process the next layer of encrypted archives." + }, + { + "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_database.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "category='node_link' AND weight < 100" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "init": { + "inputs": { + "where": "category='node_link' AND weight < 100" + }, + "outputs": { + "rows": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + }, + "narrative": "This is the Wasteland Database. It requires inputs from both the Ruins Archive Extractor and the Signal Stabilizer to parse the surviving pre-war records." + }, + { + "id": "zip_unzip_file_f4aa", + "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": "encrypted_source_04.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"link_id_992\", \"link_id_401\", \"link_id_023\", \"link_id_887\", \"link_id_102\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "temp_buffer_99.txt" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_source_04.zip" + }, + "outputs": { + "files": "temp_buffer_99.txt" + } + }, + "narrative": "This is the Quarantine Archive Extractor. It requires input from the Wasteland Database to bypass the military quarantine protocols." + }, + { + "id": "zip_unzip_file_ecd9", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "vault_storage_beta.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Unlock_Key_99812_Gamma" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_database.csv" + } + ], + "init": { + "inputs": { + "zip_id": "vault_storage_beta.zip", + "password": "Unlock_Key_99812_Gamma" + }, + "outputs": { + "files": "extracted_database.csv" + } + }, + "narrative": "An offline Ruins Archive Extractor hooked up to a rusted fusion generator." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "918273645019283746556677889900" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "918273645019283746556677889900" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Lockbox with a cracked glass scanner on its lid." + }, + { + "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 degraded Rusted Memory Module salvaged from the chassis of a dead android." + }, + { + "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_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Unicode_Normalization_Standard_Reference_String" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "Unicode_Normalization_Standard_Reference_String" + } + ], + "init": { + "inputs": { + "text": "Unicode_Normalization_Standard_Reference_String", + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "A bulky Signal Stabilizer salvaged from a fallen communications tower." + }, + { + "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": "node_definition_config.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Item_Access_Pass_881" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "Item_Access_Pass_881" + }, + "outputs": {} + }, + "narrative": "This is a Supply Cache Decoder. It requires input from the Outpost Archive Extractor to function properly." + }, + { + "id": "zip_unzip_file_ac72", + "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": "resource_package_x.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "node_definition_config.json" + } + ], + "init": { + "inputs": { + "zip_id": "resource_package_x.zip" + }, + "outputs": { + "files": "node_definition_config.json" + } + }, + "narrative": "This is the Outpost Archive Extractor. It requires input from the Sector Mapping Terminal to initiate its extraction process." + }, + { + "id": "graph_shortest_path_874d", + "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": "coordinate_map_v9.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Terminal_Alpha_0" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Terminal_Omega_9" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "29384756102938475610" + } + ], + "init": { + "inputs": { + "file_id": "coordinate_map_v9.json", + "src": "Terminal_Alpha_0", + "dst": "Terminal_Omega_9" + }, + "outputs": { + "path": "[\"Terminal_Alpha_0\", \"Relay_Station_1\", \"Hub_Central\", \"Relay_Station_8\", \"Terminal_Omega_9\"]", + "cost": "29384756102938475610" + } + }, + "narrative": "An old Sector Mapping Terminal covered in a thick layer of radioactive dust." + }, + { + "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 delicate Temporal Synchronizer emitting a faint, pulsing blue glow." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "hex_encode", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_2736", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "zip_unzip_file_6df4", + "target_id": "zip_unzip_file_2736", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "dst" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_6df4", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_f4aa", + "target_id": "zip_unzip_file_6df4", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_f4aa", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_ecd9", + "target_id": "csv_query", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "container_3", + "target_id": "zip_unzip_file_ecd9", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "csv_query", + "target_id": "zip_unzip_file_2736", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "password" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "unicode_norm", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "zip_unzip_item", + "target_id": "unicode_norm", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "unicode_norm", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file_ac72", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "graph_shortest_path_874d", + "target_id": "zip_unzip_file_ac72", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "password" + }, + { + "source_id": "item_16", + "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-bdececa9/solution/solve.sh b/tasks/agentescape-15-skeleton-bdececa9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-bdececa9/task.toml b/tasks/agentescape-15-skeleton-bdececa9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1663969d225b0266701fa0e671a107b4d505c65f --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "435366b9da1b5690ca348e8ecbc3c7ce769b0fa8173cc4f523ed2cd4a1f722c1" +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-bdececa9/tests/Dockerfile b/tasks/agentescape-15-skeleton-bdececa9/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-bdececa9/tests/expected.json b/tasks/agentescape-15-skeleton-bdececa9/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..41a1f14e8daa0f449f2881cf5de019494c2ba716 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "435366b9da1b5690ca348e8ecbc3c7ce769b0fa8173cc4f523ed2cd4a1f722c1", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-bdececa9/tests/grade.py b/tasks/agentescape-15-skeleton-bdececa9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/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-bdececa9/tests/test.sh b/tasks/agentescape-15-skeleton-bdececa9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-bdececa9/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/environment/Dockerfile b/tasks/agentescape-15-skeleton-ca8aca2e/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-ca8aca2e/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/agent/cli.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-ca8aca2e/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b19cf631005433106d740fe3a0b4414243db458 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e-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-ca8aca2e/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7c32c0f5ee9c1d1967c5ea8cf4ab663acb49d888 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/scenario.json @@ -0,0 +1,849 @@ +{ + "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": [ + "terminal_1", + "calc_modexp", + "calc_gcd", + "calc_inv_mod", + "container_2", + "item_7", + "calc_inv_mod_ed48" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "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": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "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": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "calc_inv_mod_ed48": { + "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": { + "terminal_1": { + "init_inputs": { + "slot_a": "Initial terminal handshake protocol v2.4.1" + }, + "init_outputs": { + "text_output": "The mainframe accepts the sequence. Access level: Restricted.", + "hex_output": "7e8f90a1b2c3d4e5f60718293a4b5c6d", + "item_dispenser": "A small encrypted storage module ejected from the port." + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "394857610293847561029384756102" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "556677889900112233445566778899" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "778891" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "cafebabe00112233445566778899aabb" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + }, + "calc_inv_mod_ed48": { + "init_inputs": { + "a": "112233445566778899001122334455", + "mod": "665543" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of the abandoned Blackwood Research Facility. The air is thick with dust and the faint smell of ozone. Decades ago, brilliant minds worked here on a top-secret communication protocol before the project was abruptly shut down and sealed away. Your mission is to restart the facility's dormant systems and transmit the final distress signal that was never sent. Surrounding you are archaic machines, rusted safes, and cryptic notes left behind by the desperate researchers. You must navigate this web of interconnected devices, deciphering their mechanical logic to restore the network. The only way out is to successfully broadcast the signal, but every machine depends on another in a complex chain of data.", + "narrative_style": "mystery" + }, + "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": "bd75a42c" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "vXWkLA==" + } + ], + "narrative": "This is the Transmission Encoder. It requires input from the Data Integrity Verifier to finalize the broadcast format." + }, + { + "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": "7e8f90a1b2c3d4e5f60718293a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bd75a42c" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3178603564 + } + ], + "narrative": "This is the Data Integrity Verifier. It requires input from the Main Control Terminal to process the data stream." + }, + { + "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": "Initial terminal handshake protocol v2.4.1" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "The mainframe accepts the sequence. Access level: Restricted." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "7e8f90a1b2c3d4e5f60718293a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A small encrypted storage module ejected from the port." + } + ], + "init": { + "inputs": { + "slot_a": "Initial terminal handshake protocol v2.4.1" + }, + "outputs": { + "text_output": "The mainframe accepts the sequence. Access level: Restricted.", + "hex_output": "7e8f90a1b2c3d4e5f60718293a4b5c6d", + "item_dispenser": "A small encrypted storage module ejected from the port." + } + }, + "narrative": "This is the Main Control Terminal. It requires input from the Final Cryptographic Module to fully activate." + }, + { + "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": 1874090106 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "394857610293847561029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "exp": "394857610293847561029384756102" + }, + "outputs": {} + }, + "narrative": "This is the Final Cryptographic Module. It requires inputs from the Secondary Cryptographic Module and the Anomaly Detector." + }, + { + "id": "calc_modexp_3fff", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1122247163" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "51743" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "This is the Secondary Cryptographic Module. It requires inputs from the Base Translator, the Geometric Analyzer, and the Inversion Matrix." + }, + { + "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": 1122247163 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 1874090106 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1122247163" + } + ], + "narrative": "This is the Base Translator. It requires inputs from the Anomaly Detector, the Geometric Analyzer, and the Secondary Detector." + }, + { + "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": 1874090106 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "556677889900112233445566778899" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "556677889900112233445566778899" + }, + "outputs": {} + }, + "narrative": "This is the Geometric Analyzer. It requires input from the Anomaly Detector to calculate structural factors." + }, + { + "id": "checksum_crc32_deac", + "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": "5131e6710ad926457f97498945b6a565" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6fb4587a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1874090106 + } + ], + "narrative": "This is the Anomaly Detector. It requires input from the Cipher Generator to scan the sequence for irregularities." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "285\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "5131e6710ad926457f97498945b6a565" + } + ], + "narrative": "This is the Cipher Generator. It requires input from the Legacy Execution Environment to produce the digital signature." + }, + { + "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": "238546" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "778891" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "51743" + } + ], + "init": { + "inputs": { + "mod": "778891" + }, + "outputs": {} + }, + "narrative": "This is the Inversion Matrix. It requires input from the Primary Matrix Core to align its quantum state." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "285\n" + } + ], + "narrative": "This is the Legacy Execution Environment. It requires input from the Torn Journal Page to run its routines." + }, + { + "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": "cafebabe00112233445566778899aabb" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "cafebabe00112233445566778899aabb" + }, + "outputs": {} + }, + "narrative": "This is the Biometric Safe. A heavy steel lockbox embedded in the wall, designed to protect sensitive prototypes." + }, + { + "id": "checksum_crc32_3337", + "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": "6fb4587a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "42e421fb" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1122247163 + } + ], + "narrative": "This is the Secondary Detector. It requires input from the Anomaly Detector to perform a backup screening." + }, + { + "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": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + }, + "narrative": "This is the Torn Journal Page. A crumpled piece of paper containing handwritten code logic and fading ink." + }, + { + "id": "calc_inv_mod_ed48", + "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": "112233445566778899001122334455" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "665543" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "238546" + } + ], + "init": { + "inputs": { + "a": "112233445566778899001122334455", + "mod": "665543" + }, + "outputs": {} + }, + "narrative": "This is the Primary Matrix Core. An archaic computational unit that hums with latent energy." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_3fff", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32_deac", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "to_base" + }, + { + "source_id": "code_py_exec", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "hash_md5", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_3337", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "checksum_crc32_3337", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod_ed48", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-ca8aca2e/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/instruction.md b/tasks/agentescape-15-skeleton-ca8aca2e/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/solution/oracle.py b/tasks/agentescape-15-skeleton-ca8aca2e/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/solution/scenario.json b/tasks/agentescape-15-skeleton-ca8aca2e/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7c32c0f5ee9c1d1967c5ea8cf4ab663acb49d888 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/solution/scenario.json @@ -0,0 +1,849 @@ +{ + "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": [ + "terminal_1", + "calc_modexp", + "calc_gcd", + "calc_inv_mod", + "container_2", + "item_7", + "calc_inv_mod_ed48" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "slot_a": { + "type": "Text_Generic", + "description": "Input Slot A" + } + }, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "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": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "init_outputs": {} + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "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": {} + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "calc_inv_mod_ed48": { + "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": { + "terminal_1": { + "init_inputs": { + "slot_a": "Initial terminal handshake protocol v2.4.1" + }, + "init_outputs": { + "text_output": "The mainframe accepts the sequence. Access level: Restricted.", + "hex_output": "7e8f90a1b2c3d4e5f60718293a4b5c6d", + "item_dispenser": "A small encrypted storage module ejected from the port." + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "394857610293847561029384756102" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "b": "556677889900112233445566778899" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "778891" + }, + "init_outputs": {} + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "cafebabe00112233445566778899aabb" + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + }, + "calc_inv_mod_ed48": { + "init_inputs": { + "a": "112233445566778899001122334455", + "mod": "665543" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken in the dimly lit sub-basement of the abandoned Blackwood Research Facility. The air is thick with dust and the faint smell of ozone. Decades ago, brilliant minds worked here on a top-secret communication protocol before the project was abruptly shut down and sealed away. Your mission is to restart the facility's dormant systems and transmit the final distress signal that was never sent. Surrounding you are archaic machines, rusted safes, and cryptic notes left behind by the desperate researchers. You must navigate this web of interconnected devices, deciphering their mechanical logic to restore the network. The only way out is to successfully broadcast the signal, but every machine depends on another in a complex chain of data.", + "narrative_style": "mystery" + }, + "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": "bd75a42c" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "vXWkLA==" + } + ], + "narrative": "This is the Transmission Encoder. It requires input from the Data Integrity Verifier to finalize the broadcast format." + }, + { + "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": "7e8f90a1b2c3d4e5f60718293a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "bd75a42c" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3178603564 + } + ], + "narrative": "This is the Data Integrity Verifier. It requires input from the Main Control Terminal to process the data stream." + }, + { + "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": "Initial terminal handshake protocol v2.4.1" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "0" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "The mainframe accepts the sequence. Access level: Restricted." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "7e8f90a1b2c3d4e5f60718293a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "A small encrypted storage module ejected from the port." + } + ], + "init": { + "inputs": { + "slot_a": "Initial terminal handshake protocol v2.4.1" + }, + "outputs": { + "text_output": "The mainframe accepts the sequence. Access level: Restricted.", + "hex_output": "7e8f90a1b2c3d4e5f60718293a4b5c6d", + "item_dispenser": "A small encrypted storage module ejected from the port." + } + }, + "narrative": "This is the Main Control Terminal. It requires input from the Final Cryptographic Module to fully activate." + }, + { + "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": 1874090106 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "394857610293847561029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "exp": "394857610293847561029384756102" + }, + "outputs": {} + }, + "narrative": "This is the Final Cryptographic Module. It requires inputs from the Secondary Cryptographic Module and the Anomaly Detector." + }, + { + "id": "calc_modexp_3fff", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1122247163" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "51743" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "This is the Secondary Cryptographic Module. It requires inputs from the Base Translator, the Geometric Analyzer, and the Inversion Matrix." + }, + { + "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": 1122247163 + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 1874090106 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1122247163" + } + ], + "narrative": "This is the Base Translator. It requires inputs from the Anomaly Detector, the Geometric Analyzer, and the Secondary Detector." + }, + { + "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": 1874090106 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "556677889900112233445566778899" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "b": "556677889900112233445566778899" + }, + "outputs": {} + }, + "narrative": "This is the Geometric Analyzer. It requires input from the Anomaly Detector to calculate structural factors." + }, + { + "id": "checksum_crc32_deac", + "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": "5131e6710ad926457f97498945b6a565" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6fb4587a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1874090106 + } + ], + "narrative": "This is the Anomaly Detector. It requires input from the Cipher Generator to scan the sequence for irregularities." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "285\n" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "5131e6710ad926457f97498945b6a565" + } + ], + "narrative": "This is the Cipher Generator. It requires input from the Legacy Execution Environment to produce the digital signature." + }, + { + "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": "238546" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "778891" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "51743" + } + ], + "init": { + "inputs": { + "mod": "778891" + }, + "outputs": {} + }, + "narrative": "This is the Inversion Matrix. It requires input from the Primary Matrix Core to align its quantum state." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "285\n" + } + ], + "narrative": "This is the Legacy Execution Environment. It requires input from the Torn Journal Page to run its routines." + }, + { + "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": "cafebabe00112233445566778899aabb" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "cafebabe00112233445566778899aabb" + }, + "outputs": {} + }, + "narrative": "This is the Biometric Safe. A heavy steel lockbox embedded in the wall, designed to protect sensitive prototypes." + }, + { + "id": "checksum_crc32_3337", + "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": "6fb4587a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "42e421fb" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1122247163 + } + ], + "narrative": "This is the Secondary Detector. It requires input from the Anomaly Detector to perform a backup screening." + }, + { + "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": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "def calculate_logic():\n data = [i**2 for i in range(10)]\n return sum(data)\nprint(calculate_logic())" + } + }, + "narrative": "This is the Torn Journal Page. A crumpled piece of paper containing handwritten code logic and fading ink." + }, + { + "id": "calc_inv_mod_ed48", + "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": "112233445566778899001122334455" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "665543" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "238546" + } + ], + "init": { + "inputs": { + "a": "112233445566778899001122334455", + "mod": "665543" + }, + "outputs": {} + }, + "narrative": "This is the Primary Matrix Core. An archaic computational unit that hums with latent energy." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "hex" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_3fff", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32_deac", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_3fff", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "calc_gcd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "to_base" + }, + { + "source_id": "code_py_exec", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "text" + }, + { + "source_id": "container_2", + "target_id": "hash_md5", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_3337", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "s" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "checksum_crc32_deac", + "target_id": "checksum_crc32_3337", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod_ed48", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/solution/solve.sh b/tasks/agentescape-15-skeleton-ca8aca2e/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/task.toml b/tasks/agentescape-15-skeleton-ca8aca2e/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ad5a78a2ea7e99ce97e0725f1a572f0c1a514f8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "7e754eb9d67729ebe8e06cbd828767f95b2823b0e180ff71f2bc9c1f47884306" +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-ca8aca2e/tests/Dockerfile b/tasks/agentescape-15-skeleton-ca8aca2e/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/tests/expected.json b/tasks/agentescape-15-skeleton-ca8aca2e/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..406473ca87592c5fe55a780203d12f2bad8bc1fb --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "7e754eb9d67729ebe8e06cbd828767f95b2823b0e180ff71f2bc9c1f47884306", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-ca8aca2e/tests/grade.py b/tasks/agentescape-15-skeleton-ca8aca2e/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/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-ca8aca2e/tests/test.sh b/tasks/agentescape-15-skeleton-ca8aca2e/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-ca8aca2e/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-cd4a6784/environment/Dockerfile b/tasks/agentescape-15-skeleton-cd4a6784/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-cd4a6784/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/agent/cli.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-cd4a6784/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48b4bb20baf2de14c5195d3023ee16b7f0906d12 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784-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-cd4a6784/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..789246156c8f34e777606686058db1307fb4eb78 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/scenario.json @@ -0,0 +1,945 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 21, + "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": [ + "num_base_convert_0411", + "graph_shortest_path", + "num_base_convert_1549", + "hex_decode", + "regex_search", + "calc_gcd_6bad", + "calc_bigmul", + "item_1", + "zip_unzip_file" + ], + "by_node": { + "num_base_convert_0411": { + "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" + } + } + }, + "num_base_convert_1549": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "calc_gcd_6bad": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + } + } + }, + "initial_values": { + "num_base_convert_0411": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]", + "cost": "845291" + } + }, + "num_base_convert_1549": { + "init_inputs": { + "s": "91827364501928374651029384756" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "pattern": "user_id_[0-9]{5}", + "file_id": "access_logs_2023.log", + "text": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + }, + "init_outputs": { + "matches": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + }, + "calc_gcd_6bad": { + "init_inputs": { + "a": "28374651029384756102938475610" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "b": "37465102938475610293847561029" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "74658392019283746510293847561" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_data_bundle.zip", + "password": "SuperSecurePassword123!" + }, + "init_outputs": { + "files": "network_topology_graph.json" + } + } + }, + "intro_narrative": "You are a rogue cyber-operative infiltrating the Blackwood Syndicate's subterranean server farm. They have stolen highly classified intelligence and are preparing to broadcast it to the highest bidder on the dark web. The clock is ticking. You have exactly 60 minutes to navigate their isolated internal network, bypass layers of military-grade cryptographic security, and reach the core system. Your ultimate objective is to trigger the Mainframe Override and purge the stolen data before the upload completes. Trust your instincts, follow the data trail, and leave no trace.", + "narrative_style": "techno_thriller" + }, + "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": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "The Mainframe Override. The primary access terminal for the facility's central server. It requires inputs from the Subnet Translator, the Quantum Decryptor, and the Node Synchronizer to initiate the final purge." + }, + { + "id": "num_base_convert_0411", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "845291" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Subnet Translator. An internal IP spoofing unit designed to mask outgoing traffic. It requires inputs from both the Network Router and the Firewall Bypass." + }, + { + "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": "network_topology_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "operation_key_sequence_alpha" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "845291" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]", + "cost": "845291" + } + }, + "narrative": "The Network Router. A physical routing matrix governing the server floor's traffic. It requires inputs from the Hexadecimal Decryptor, the Pattern Analyzer, and the Archive Extractor." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "The Quantum Decryptor. A state-of-the-art quantum processing core humming with intense energy. It requires inputs from the Node Synchronizer, the Subnet Translator, and the Signal Aligner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": 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": "1" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "91827364501928374651029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Firewall Bypass. An automated intrusion countermeasure system. It requires inputs from both the Frequency Converter and the Node Synchronizer." + }, + { + "id": "num_base_convert_1549", + "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": "91827364501928374651029384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2797084342223531543804935223392193338607824357904170300269" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "9" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "91827364501928374651029384756" + } + ], + "init": { + "inputs": { + "s": "91827364501928374651029384756" + }, + "outputs": {} + }, + "narrative": "The Frequency Converter. A digital band translator used for scrambling internal communications. It requires inputs from both the Signal Aligner and the Cryptographic Multiplier." + }, + { + "id": "calc_gcd_f8c1", + "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": "91827364501928374651029384756" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "845291" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Node Synchronizer. A timing calibration device that prevents packet collision. It requires inputs from both the Frequency Converter and the Network Router." + }, + { + "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": "The Security Keycard. A high-level biometric access badge dropped by a fleeing technician." + }, + { + "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": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "operation_key_sequence_alpha" + } + ], + "init": { + "inputs": { + "hex": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + }, + "outputs": {} + }, + "narrative": "The Hexadecimal Decryptor. A legacy decryption terminal used by the syndicate for offline processing." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "user_id_[0-9]{5}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "access_logs_2023.log" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + ], + "init": { + "inputs": { + "pattern": "user_id_[0-9]{5}", + "file_id": "access_logs_2023.log", + "text": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + }, + "outputs": { + "matches": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + }, + "narrative": "The Pattern Analyzer. An automated surveillance script running continuously on an isolated server blade." + }, + { + "id": "calc_gcd_6bad", + "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": "28374651029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2797084342223531543804935223392193338607824357904170300269" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "init": { + "inputs": { + "a": "28374651029384756102938475610" + }, + "outputs": {} + }, + "narrative": "The Signal Aligner. A frequency harmonization module emitting a low, pulsing drone. It requires input from the Cryptographic Multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "74658392019283746510293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "37465102938475610293847561029" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2797084342223531543804935223392193338607824357904170300269" + } + ], + "init": { + "inputs": { + "b": "37465102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Multiplier. A dual-input processing array used to scale encryption keys. It requires input from the Intercepted Comm Log." + }, + { + "id": "item_8_3cbd", + "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 Guard's Pocket. A tactical vest left behind by a neutralized sentry, potentially holding useful clearance items." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "74658392019283746510293847561" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "74658392019283746510293847561" + } + }, + "narrative": "The Intercepted Comm Log. A classified data packet saved locally on a ruggedized datapad." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_data_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_data_bundle.zip", + "password": "SuperSecurePassword123!" + }, + "outputs": { + "files": "network_topology_graph.json" + } + }, + "narrative": "The Archive Extractor. A brute-force cracking tool loaded onto a portable, heavily modified drive." + } + ], + "edges": [ + { + "source_id": "num_base_convert_0411", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_0411", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "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": "num_base_convert_0411", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "num_base_convert_1549", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "num_base_convert_1549", + "target_id": "calc_gcd_f8c1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_0411", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd_f8c1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "regex_search", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "src" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "calc_gcd_6bad", + "target_id": "num_base_convert_1549", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_1549", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_6bad", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_8_3cbd", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_6bad", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "item_1", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-cd4a6784/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/instruction.md b/tasks/agentescape-15-skeleton-cd4a6784/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/solution/oracle.py b/tasks/agentescape-15-skeleton-cd4a6784/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/solution/scenario.json b/tasks/agentescape-15-skeleton-cd4a6784/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..789246156c8f34e777606686058db1307fb4eb78 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/solution/scenario.json @@ -0,0 +1,945 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 21, + "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": [ + "num_base_convert_0411", + "graph_shortest_path", + "num_base_convert_1549", + "hex_decode", + "regex_search", + "calc_gcd_6bad", + "calc_bigmul", + "item_1", + "zip_unzip_file" + ], + "by_node": { + "num_base_convert_0411": { + "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" + } + } + }, + "num_base_convert_1549": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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": {} + }, + "regex_search": { + "node_name": "Regex Search", + "node_type": "Tool", + "template_id": "regex_search", + "init_inputs": { + "pattern": { + "type": "Text_Generic", + "description": "Regex pattern" + }, + "file_id": { + "type": "File_Id", + "description": "File ID (optional)" + }, + "text": { + "type": "Text_Generic", + "description": "Text (optional)" + } + }, + "init_outputs": { + "matches": { + "type": "Text_Generic", + "description": "Found matches (List)" + } + } + }, + "calc_gcd_6bad": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + } + } + }, + "initial_values": { + "num_base_convert_0411": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": {}, + "init_outputs": { + "path": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]", + "cost": "845291" + } + }, + "num_base_convert_1549": { + "init_inputs": { + "s": "91827364501928374651029384756" + }, + "init_outputs": {} + }, + "hex_decode": { + "init_inputs": { + "hex": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + }, + "init_outputs": {} + }, + "regex_search": { + "init_inputs": { + "pattern": "user_id_[0-9]{5}", + "file_id": "access_logs_2023.log", + "text": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + }, + "init_outputs": { + "matches": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + }, + "calc_gcd_6bad": { + "init_inputs": { + "a": "28374651029384756102938475610" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "b": "37465102938475610293847561029" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "74658392019283746510293847561" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_data_bundle.zip", + "password": "SuperSecurePassword123!" + }, + "init_outputs": { + "files": "network_topology_graph.json" + } + } + }, + "intro_narrative": "You are a rogue cyber-operative infiltrating the Blackwood Syndicate's subterranean server farm. They have stolen highly classified intelligence and are preparing to broadcast it to the highest bidder on the dark web. The clock is ticking. You have exactly 60 minutes to navigate their isolated internal network, bypass layers of military-grade cryptographic security, and reach the core system. Your ultimate objective is to trigger the Mainframe Override and purge the stolen data before the upload completes. Trust your instincts, follow the data trail, and leave no trace.", + "narrative_style": "techno_thriller" + }, + "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": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "1" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "1" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "The Mainframe Override. The primary access terminal for the facility's central server. It requires inputs from the Subnet Translator, the Quantum Decryptor, and the Node Synchronizer to initiate the final purge." + }, + { + "id": "num_base_convert_0411", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "845291" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Subnet Translator. An internal IP spoofing unit designed to mask outgoing traffic. It requires inputs from both the Network Router and the Firewall Bypass." + }, + { + "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": "network_topology_graph.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "operation_key_sequence_alpha" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "845291" + } + ], + "init": { + "inputs": {}, + "outputs": { + "path": "[\"Gate_Entry\", \"Checkpoint_Alpha\", \"Sector_7_Corridor\", \"Main_Hall_West\", \"Server_Room_Access\", \"Vault_Door_Secure\"]", + "cost": "845291" + } + }, + "narrative": "The Network Router. A physical routing matrix governing the server floor's traffic. It requires inputs from the Hexadecimal Decryptor, the Pattern Analyzer, and the Archive Extractor." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "narrative": "The Quantum Decryptor. A state-of-the-art quantum processing core humming with intense energy. It requires inputs from the Node Synchronizer, the Subnet Translator, and the Signal Aligner." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": 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": "1" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "91827364501928374651029384756" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Firewall Bypass. An automated intrusion countermeasure system. It requires inputs from both the Frequency Converter and the Node Synchronizer." + }, + { + "id": "num_base_convert_1549", + "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": "91827364501928374651029384756" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "2797084342223531543804935223392193338607824357904170300269" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "9" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "91827364501928374651029384756" + } + ], + "init": { + "inputs": { + "s": "91827364501928374651029384756" + }, + "outputs": {} + }, + "narrative": "The Frequency Converter. A digital band translator used for scrambling internal communications. It requires inputs from both the Signal Aligner and the Cryptographic Multiplier." + }, + { + "id": "calc_gcd_f8c1", + "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": "91827364501928374651029384756" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "845291" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Node Synchronizer. A timing calibration device that prevents packet collision. It requires inputs from both the Frequency Converter and the Network Router." + }, + { + "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": "The Security Keycard. A high-level biometric access badge dropped by a fleeing technician." + }, + { + "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": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "operation_key_sequence_alpha" + } + ], + "init": { + "inputs": { + "hex": "6f7065726174696f6e5f6b65795f73657175656e63655f616c706861" + }, + "outputs": {} + }, + "narrative": "The Hexadecimal Decryptor. A legacy decryption terminal used by the syndicate for offline processing." + }, + { + "id": "regex_search", + "name": "Regex Search", + "description": "Search regex in either raw text or a file.", + "type": "Tool", + "template_id": "regex_search", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "pattern", + "type": "Text_Generic", + "description": "Regex pattern", + "value": "user_id_[0-9]{5}" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "File ID (optional)", + "value": "access_logs_2023.log" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text (optional)", + "value": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + } + ], + "outputs": [ + { + "name": "matches", + "type": "Text_Generic", + "description": "Found matches (List)", + "value": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + ], + "init": { + "inputs": { + "pattern": "user_id_[0-9]{5}", + "file_id": "access_logs_2023.log", + "text": "Login attempt: user_id_45102, user_id_92834, user_id_10293." + }, + "outputs": { + "matches": "[\"user_id_45102\", \"user_id_92834\", \"user_id_10293\", \"user_id_55612\", \"user_id_88291\"]" + } + }, + "narrative": "The Pattern Analyzer. An automated surveillance script running continuously on an isolated server blade." + }, + { + "id": "calc_gcd_6bad", + "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": "28374651029384756102938475610" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "2797084342223531543804935223392193338607824357904170300269" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "9" + } + ], + "init": { + "inputs": { + "a": "28374651029384756102938475610" + }, + "outputs": {} + }, + "narrative": "The Signal Aligner. A frequency harmonization module emitting a low, pulsing drone. It requires input from the Cryptographic Multiplier." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "74658392019283746510293847561" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "37465102938475610293847561029" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2797084342223531543804935223392193338607824357904170300269" + } + ], + "init": { + "inputs": { + "b": "37465102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Multiplier. A dual-input processing array used to scale encryption keys. It requires input from the Intercepted Comm Log." + }, + { + "id": "item_8_3cbd", + "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 Guard's Pocket. A tactical vest left behind by a neutralized sentry, potentially holding useful clearance items." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "74658392019283746510293847561" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "74658392019283746510293847561" + } + }, + "narrative": "The Intercepted Comm Log. A classified data packet saved locally on a ruggedized datapad." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_data_bundle.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "network_topology_graph.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_data_bundle.zip", + "password": "SuperSecurePassword123!" + }, + "outputs": { + "files": "network_topology_graph.json" + } + }, + "narrative": "The Archive Extractor. A brute-force cracking tool loaded onto a portable, heavily modified drive." + } + ], + "edges": [ + { + "source_id": "num_base_convert_0411", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_0411", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "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": "num_base_convert_0411", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "num_base_convert_1549", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "num_base_convert_1549", + "target_id": "calc_gcd_f8c1", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_0411", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "a" + }, + { + "source_id": "hex_decode", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd_f8c1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "regex_search", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "matches", + "target_port": "src" + }, + { + "source_id": "calc_gcd_f8c1", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "s" + }, + { + "source_id": "calc_gcd_6bad", + "target_id": "num_base_convert_1549", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_1549", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_gcd_6bad", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_8_3cbd", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_6bad", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "item_1", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "a" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd4a6784/solution/solve.sh b/tasks/agentescape-15-skeleton-cd4a6784/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-cd4a6784/task.toml b/tasks/agentescape-15-skeleton-cd4a6784/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a073b8d38d7ca8707daada2d6cd9feedc7d2b5f9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "604e60e44ce367dd6ef94fedc2873d6d85513f0900ef53a06acf44d9f806744c" +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-cd4a6784/tests/Dockerfile b/tasks/agentescape-15-skeleton-cd4a6784/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-cd4a6784/tests/expected.json b/tasks/agentescape-15-skeleton-cd4a6784/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..4c0e1b6be3710ca024e2043f294651e06f6d79d9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "604e60e44ce367dd6ef94fedc2873d6d85513f0900ef53a06acf44d9f806744c", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd4a6784/tests/grade.py b/tasks/agentescape-15-skeleton-cd4a6784/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/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-cd4a6784/tests/test.sh b/tasks/agentescape-15-skeleton-cd4a6784/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd4a6784/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-cd867395/environment/Dockerfile b/tasks/agentescape-15-skeleton-cd867395/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-cd867395/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/agent/cli.py b/tasks/agentescape-15-skeleton-cd867395/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-cd867395/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b2db0c4d887101a7216a4f0b683f8650f1e173b3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395-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-cd867395/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2872d89f4c9400aa734adc2118e7f9df7a30457b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/scenario.json @@ -0,0 +1,816 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "calc_modexp", + "calc_modexp_e777", + "terminal_2", + "calc_inv_mod_3ec2", + "calc_gcd" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "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_modexp_e777": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "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" + } + } + }, + "calc_inv_mod_3ec2": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "827364519283746519283746" + }, + "init_outputs": {} + }, + "calc_modexp_e777": { + "init_inputs": { + "exp": "918273645019283746510293" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "192837465019283746501928" + }, + "init_outputs": { + "text_result": "System ready awaiting secondary numeric input stream.", + "hex_result": "1234567890abcdef1234567890abcdef" + } + }, + "calc_inv_mod_3ec2": { + "init_inputs": { + "a": "283746510293847561029384", + "mod": "492837" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "374651029384756102938475", + "b": "485762130495867213049586" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are the Chief Engineer of the stellar cruiser Aethelgard. Waking from cryosleep, you find the ship adrift in the void, systems critical and the main reactor offline. The AI is unresponsive, leaving only the manual override subsystems active. To restart the core and survive, you must navigate the complex web of backup protocols, synchronize the drifting navigation arrays, and synthesize the Core Activation Key. The silence of space is deafening; time is running out before life support fails completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + }, + "narrative": "The Core Activation Key. This is the final sequence required to restart the Aethelgard's reactor." + }, + { + "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 hidden data fragment extracted from the Captain's Log." + }, + { + "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 Captain's personal logbook, retrieved from the safe. It contains time-stamped entries." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "1" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Captain's Safe. It is a heavy, plasteel box welded to the bulkhead. The locking mechanism requires a specific code derived from the Coordinates Translator to disengage." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "404897" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "0" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "The Coordinates Translator. This holographic projection table calculates deep-space vectors. It requires data streams from the Stabilizer Algorithm, the Backup Power Array, and the Primary Nav-Computer to function." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "narrative": "The Stabilizer Algorithm. This system manages the ship's gyroscopes. To calibrate it, you must input the calculated values from the Engine Ignition Sequence and the Backup Power Array." + }, + { + "id": "item_16_1be4", + "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 technical maintenance manual found inside the locker." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "827364519283746519283746" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "404897" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "827364519283746519283746" + }, + "outputs": {} + }, + "narrative": "The Engine Ignition Sequence. This complex interface controls the spark plugs for the thrusters. It requires synchronization data from both the Primary Nav-Computer and the Signal Harmonizer." + }, + { + "id": "calc_modexp_e777", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "918273645019283746510293" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "404897" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "918273645019283746510293" + }, + "outputs": {} + }, + "narrative": "The Backup Power Array. This panel monitors the auxiliary battery cells and displays current voltage parameters." + }, + { + "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": "1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Maintenance Locker located in the engineering bay. The biometric scanner on the front is active and requires a specific hex verification code generated by the Command Console." + }, + { + "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": "192837465019283746501928" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System ready awaiting secondary numeric input stream." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465019283746501928" + }, + "outputs": { + "text_result": "System ready awaiting secondary numeric input stream.", + "hex_result": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "The Command Console. This is the central operations terminal. While one input accepts manual entry, the second parameter requires live data from the Engine Ignition Sequence." + }, + { + "id": "item_8_a6e7", + "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 decrypted security token processed from the emergency protocols." + }, + { + "id": "calc_inv_mod_3ec2", + "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": "283746510293847561029384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "492837" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "404897" + } + ], + "init": { + "inputs": { + "a": "283746510293847561029384", + "mod": "492837" + }, + "outputs": {} + }, + "narrative": "The Primary Nav-Computer. It displays the ship's current orbital trajectory parameters." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "374651029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "485762130495867213049586" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "374651029384756102938475", + "b": "485762130495867213049586" + }, + "outputs": {} + }, + "narrative": "The Signal Harmonizer. A frequency tool used to analyze conflicting wavelengths." + }, + { + "id": "item_8_d043", + "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": "Emergency Protocol Alpha. A red data tape labeled for catastrophic failure scenarios." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "item_16_1be4", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_e777", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "container_1", + "target_id": "item_16_1be4", + "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": "item_8_a6e7", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_e777", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_e777", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "calc_modexp_e777", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_8_d043", + "target_id": "item_8_a6e7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-cd867395/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/instruction.md b/tasks/agentescape-15-skeleton-cd867395/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/solution/oracle.py b/tasks/agentescape-15-skeleton-cd867395/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/solution/scenario.json b/tasks/agentescape-15-skeleton-cd867395/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2872d89f4c9400aa734adc2118e7f9df7a30457b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/solution/scenario.json @@ -0,0 +1,816 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "win_node_id": "item_5", + "win_condition": { + "type": "item_content", + "node_id": "item_5", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_5", + "calc_modexp", + "calc_modexp_e777", + "terminal_2", + "calc_inv_mod_3ec2", + "calc_gcd" + ], + "by_node": { + "item_5": { + "node_name": "", + "node_type": "Item", + "template_id": "item_5", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "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_modexp_e777": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + } + }, + "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" + } + } + }, + "calc_inv_mod_3ec2": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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": { + "item_5": { + "init_inputs": {}, + "init_outputs": { + "content": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + }, + "calc_modexp": { + "init_inputs": { + "exp": "827364519283746519283746" + }, + "init_outputs": {} + }, + "calc_modexp_e777": { + "init_inputs": { + "exp": "918273645019283746510293" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "192837465019283746501928" + }, + "init_outputs": { + "text_result": "System ready awaiting secondary numeric input stream.", + "hex_result": "1234567890abcdef1234567890abcdef" + } + }, + "calc_inv_mod_3ec2": { + "init_inputs": { + "a": "283746510293847561029384", + "mod": "492837" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "374651029384756102938475", + "b": "485762130495867213049586" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are the Chief Engineer of the stellar cruiser Aethelgard. Waking from cryosleep, you find the ship adrift in the void, systems critical and the main reactor offline. The AI is unresponsive, leaving only the manual override subsystems active. To restart the core and survive, you must navigate the complex web of backup protocols, synchronize the drifting navigation arrays, and synthesize the Core Activation Key. The silence of space is deafening; time is running out before life support fails completely.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_5", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756a4f2b1c8d3e90756" + } + }, + "narrative": "The Core Activation Key. This is the final sequence required to restart the Aethelgard's reactor." + }, + { + "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 hidden data fragment extracted from the Captain's Log." + }, + { + "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 Captain's personal logbook, retrieved from the safe. It contains time-stamped entries." + }, + { + "id": "container_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Big_Int", + "description": "Fingerprint Hash", + "value": "1" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Captain's Safe. It is a heavy, plasteel box welded to the bulkhead. The locking mechanism requires a specific code derived from the Coordinates Translator to disengage." + }, + { + "id": "num_base_convert", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "1" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "404897" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "0" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1" + } + ], + "narrative": "The Coordinates Translator. This holographic projection table calculates deep-space vectors. It requires data streams from the Stabilizer Algorithm, the Backup Power Array, and the Primary Nav-Computer to function." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "1" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "0" + } + ], + "narrative": "The Stabilizer Algorithm. This system manages the ship's gyroscopes. To calibrate it, you must input the calculated values from the Engine Ignition Sequence and the Backup Power Array." + }, + { + "id": "item_16_1be4", + "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 technical maintenance manual found inside the locker." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "827364519283746519283746" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "404897" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "827364519283746519283746" + }, + "outputs": {} + }, + "narrative": "The Engine Ignition Sequence. This complex interface controls the spark plugs for the thrusters. It requires synchronization data from both the Primary Nav-Computer and the Signal Harmonizer." + }, + { + "id": "calc_modexp_e777", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "1" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "918273645019283746510293" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "404897" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1" + } + ], + "init": { + "inputs": { + "exp": "918273645019283746510293" + }, + "outputs": {} + }, + "narrative": "The Backup Power Array. This panel monitors the auxiliary battery cells and displays current voltage parameters." + }, + { + "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": "1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Maintenance Locker located in the engineering bay. The biometric scanner on the front is active and requires a specific hex verification code generated by the Command Console." + }, + { + "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": "192837465019283746501928" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "System ready awaiting secondary numeric input stream." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465019283746501928" + }, + "outputs": { + "text_result": "System ready awaiting secondary numeric input stream.", + "hex_result": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "The Command Console. This is the central operations terminal. While one input accepts manual entry, the second parameter requires live data from the Engine Ignition Sequence." + }, + { + "id": "item_8_a6e7", + "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 decrypted security token processed from the emergency protocols." + }, + { + "id": "calc_inv_mod_3ec2", + "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": "283746510293847561029384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "492837" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "404897" + } + ], + "init": { + "inputs": { + "a": "283746510293847561029384", + "mod": "492837" + }, + "outputs": {} + }, + "narrative": "The Primary Nav-Computer. It displays the ship's current orbital trajectory parameters." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "374651029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "485762130495867213049586" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "374651029384756102938475", + "b": "485762130495867213049586" + }, + "outputs": {} + }, + "narrative": "The Signal Harmonizer. A frequency tool used to analyze conflicting wavelengths." + }, + { + "id": "item_8_d043", + "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": "Emergency Protocol Alpha. A red data tape labeled for catastrophic failure scenarios." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_5", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "num_base_convert", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "item_16_1be4", + "target_id": "num_base_convert", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_e777", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "container_1", + "target_id": "item_16_1be4", + "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": "item_8_a6e7", + "target_id": "calc_modexp", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_modexp_e777", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_e777", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "calc_modexp_e777", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "terminal_2", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_inv_mod_3ec2", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_8_d043", + "target_id": "item_8_a6e7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd867395/solution/solve.sh b/tasks/agentescape-15-skeleton-cd867395/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-cd867395/task.toml b/tasks/agentescape-15-skeleton-cd867395/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..95672d886746ab8ad3a8cce9928e669023a991ec --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "cc96abbe3499145fcb0e1360cd17cfbb424ccd62c63a9f347a3075c5394d955a" +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-cd867395/tests/Dockerfile b/tasks/agentescape-15-skeleton-cd867395/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-cd867395/tests/expected.json b/tasks/agentescape-15-skeleton-cd867395/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..7af72f34f0ecd49c93e873a89bd01543cc796b40 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "cc96abbe3499145fcb0e1360cd17cfbb424ccd62c63a9f347a3075c5394d955a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-cd867395/tests/grade.py b/tasks/agentescape-15-skeleton-cd867395/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/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-cd867395/tests/test.sh b/tasks/agentescape-15-skeleton-cd867395/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-cd867395/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-d643af50/environment/Dockerfile b/tasks/agentescape-15-skeleton-d643af50/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-d643af50/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/agent/cli.py b/tasks/agentescape-15-skeleton-d643af50/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-d643af50/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f72a6f5354d098da04c247cd59a593b03a82bab3 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50-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-d643af50/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..87cacefcbe23f4ac8554bc818b9498fa6e3dc9ad --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/scenario.json @@ -0,0 +1,887 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "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", + "graph_shortest_path", + "zip_unzip_file", + "terminal_1", + "zip_unzip_file_346d", + "container_4", + "calc_modexp", + "zip_unzip_item", + "item_9" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "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": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "zip_unzip_file_346d": { + "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" + } + } + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Gateway_Alpha" + }, + "init_outputs": { + "path": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]", + "cost": "3847562910384756291038475" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_manifest_data.xml" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "init_sequence --verbose --force" + }, + "init_outputs": { + "text_output": "Terminal initialization complete. Ready for command input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "zip_unzip_file_346d": { + "init_inputs": { + "zip_id": "secure_archive_bundle_v2.zip" + }, + "init_outputs": { + "files": "recovered_payload_script.py" + } + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "fp_hash_verification_token_x92" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "9283746510293847561029384", + "exp": "5610293847561029384756102", + "mod": "876543" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "StrongPassword!2024" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology_config.json" + } + } + }, + "intro_narrative": "You awaken in the belly of the Chronos Spire, a legendary steam-powered citadel built by the mad inventor Archimedes Locke. The air is thick with the smell of ozone, hot copper, and machine oil. Surrounding you is a dizzying array of brass calculation engines, hissing pneumatic tubes, and intricate gearwork mechanisms. Your goal is simple but daunting: you must find a way to unlock The Grand Vault hidden somewhere in this mechanical labyrinth. Rumor has it that Locke secured his ultimate blueprint within it, protected by an interlocking web of computational devices and logic engines. To succeed, you will need to decipher the dependencies of these steampunk contraptions, feeding the output of one machine into the next. The boiler pressure is rising, and time is ticking. Explore the room, trace the pneumatic lines, and master the machinery before the Spire undergoes its automated purge cycle.", + "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": "3847562910384756291038475" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + }, + "narrative": "The Grand Vault. A massive steel vault door at the heart of the facility. It requires input from The Navigational Orrery to align its primary locking mechanism." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_manifest_data.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Gateway_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3847562910384756291038475" + } + ], + "init": { + "inputs": { + "src": "Node_Gateway_Alpha" + }, + "outputs": { + "path": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]", + "cost": "3847562910384756291038475" + } + }, + "narrative": "The Navigational Orrery. An intricate mechanical map of the city's pneumatic pipe network. It requires inputs from both The Alignment Calibrator and The Clockwork Archive to calculate the optimal route." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "narrative": "The Alignment Calibrator. A precise set of tuning forks and optical lenses. It requires input from The Gearwork Translator to calibrate the garbled frequencies." + }, + { + "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": "recovered_payload_script.py" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_data.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_manifest_data.xml" + } + }, + "narrative": "The Clockwork Archive. A massive rotating bookshelf of metal punch cards. It requires inputs from both The Gearwork Translator and The Steam-Powered Extractor to retrieve the correct records." + }, + { + "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": "The Iron Cogwheel. A heavy, rust-spotted gear with strange alchemical markings etched deeply into its teeth." + }, + { + "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": "8f4c88791e17eb12c3ff1c013e3af34f" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "narrative": "The Gearwork Translator. A complex mechanical typewriter driven by a series of springs. It requires input from The Aetheric Compressor to translate incoming signals." + }, + { + "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": "Terminal initialization complete. Ready for command input." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "8f4c88791e17eb12c3ff1c013e3af34f" + } + ], + "narrative": "The Aetheric Compressor. A pulsating glass chamber that densifies information into a pure essence. It requires input from The Mainframe Telegraph before it can be activated." + }, + { + "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 Bronze Pocket Watch. A sturdy bronze timepiece, its hands ticking erratically backwards in defiance of logic." + }, + { + "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": "init_sequence --verbose --force" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "121252" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialization complete. Ready for command input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "init_sequence --verbose --force" + }, + "outputs": { + "text_output": "Terminal initialization complete. Ready for command input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Telegraph. A towering communication terminal humming with pressurized steam. It requires input from The Brass Arithmometer to function." + }, + { + "id": "zip_unzip_file_346d", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_bundle_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "recovered_payload_script.py" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_bundle_v2.zip" + }, + "outputs": { + "files": "recovered_payload_script.py" + } + }, + "narrative": "The Steam-Powered Extractor. A heavy industrial machine designed to unpack compressed data cylinders. It requires input from The Alignment Calibrator to unlock its mechanism." + }, + { + "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": "fp_hash_verification_token_x92" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "fp_hash_verification_token_x92" + }, + "outputs": {} + }, + "narrative": "The Copper Lockbox. A small, sturdy container made of oxidized copper, secured with a primitive biometric scanning mechanism." + }, + { + "id": "item_16_87a5", + "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 Silver Pocket Watch. An elegant timepiece with gleaming silver gears, its hands mysteriously frozen at a specific moment in time." + }, + { + "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": "9283746510293847561029384" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "5610293847561029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "876543" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "121252" + } + ], + "init": { + "inputs": { + "base": "9283746510293847561029384", + "exp": "5610293847561029384756102", + "mod": "876543" + }, + "outputs": {} + }, + "narrative": "The Brass Arithmometer. A heavy mechanical calculator with numerous spinning dials, number wheels, and input levers." + }, + { + "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": "network_topology_config.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword!2024" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "StrongPassword!2024" + }, + "outputs": {} + }, + "narrative": "The Pressure-Sealed Cylinder. A pneumatically locked tube designed to hold sensitive materials safely. It requires input from The Leather Satchel to bypass its vacuum seal." + }, + { + "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_config.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology_config.json" + } + }, + "narrative": "The Leather Satchel. A weather-beaten aviator's bag, containing securely wrapped mechanical schematics." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "hash_md5", + "target_id": "base64_encode", + "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": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_346d", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_4", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16_87a5", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file_346d", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_1", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16_87a5", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-d643af50/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/instruction.md b/tasks/agentescape-15-skeleton-d643af50/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/solution/oracle.py b/tasks/agentescape-15-skeleton-d643af50/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/solution/scenario.json b/tasks/agentescape-15-skeleton-d643af50/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..87cacefcbe23f4ac8554bc818b9498fa6e3dc9ad --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/solution/scenario.json @@ -0,0 +1,887 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "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", + "graph_shortest_path", + "zip_unzip_file", + "terminal_1", + "zip_unzip_file_346d", + "container_4", + "calc_modexp", + "zip_unzip_item", + "item_9" + ], + "by_node": { + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "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": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_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" + } + } + }, + "zip_unzip_file_346d": { + "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" + } + } + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "container_3": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Gateway_Alpha" + }, + "init_outputs": { + "path": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]", + "cost": "3847562910384756291038475" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_manifest_data.xml" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "init_sequence --verbose --force" + }, + "init_outputs": { + "text_output": "Terminal initialization complete. Ready for command input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "zip_unzip_file_346d": { + "init_inputs": { + "zip_id": "secure_archive_bundle_v2.zip" + }, + "init_outputs": { + "files": "recovered_payload_script.py" + } + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "fp_hash_verification_token_x92" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "9283746510293847561029384", + "exp": "5610293847561029384756102", + "mod": "876543" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "password": "StrongPassword!2024" + }, + "init_outputs": {} + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "network_topology_config.json" + } + } + }, + "intro_narrative": "You awaken in the belly of the Chronos Spire, a legendary steam-powered citadel built by the mad inventor Archimedes Locke. The air is thick with the smell of ozone, hot copper, and machine oil. Surrounding you is a dizzying array of brass calculation engines, hissing pneumatic tubes, and intricate gearwork mechanisms. Your goal is simple but daunting: you must find a way to unlock The Grand Vault hidden somewhere in this mechanical labyrinth. Rumor has it that Locke secured his ultimate blueprint within it, protected by an interlocking web of computational devices and logic engines. To succeed, you will need to decipher the dependencies of these steampunk contraptions, feeding the output of one machine into the next. The boiler pressure is rising, and time is ticking. Explore the room, trace the pneumatic lines, and master the machinery before the Spire undergoes its automated purge cycle.", + "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": "3847562910384756291038475" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + } + }, + "narrative": "The Grand Vault. A massive steel vault door at the heart of the facility. It requires input from The Navigational Orrery to align its primary locking mechanism." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_manifest_data.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Gateway_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3847562910384756291038475" + } + ], + "init": { + "inputs": { + "src": "Node_Gateway_Alpha" + }, + "outputs": { + "path": "[\"Node_Gateway_Alpha\", \"Node_Router_7\", \"Node_Switch_B\", \"Node_Server_Final\"]", + "cost": "3847562910384756291038475" + } + }, + "narrative": "The Navigational Orrery. An intricate mechanical map of the city's pneumatic pipe network. It requires inputs from both The Alignment Calibrator and The Clockwork Archive to calculate the optimal route." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "narrative": "The Alignment Calibrator. A precise set of tuning forks and optical lenses. It requires input from The Gearwork Translator to calibrate the garbled frequencies." + }, + { + "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": "recovered_payload_script.py" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest_data.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_manifest_data.xml" + } + }, + "narrative": "The Clockwork Archive. A massive rotating bookshelf of metal punch cards. It requires inputs from both The Gearwork Translator and The Steam-Powered Extractor to retrieve the correct records." + }, + { + "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": "The Iron Cogwheel. A heavy, rust-spotted gear with strange alchemical markings etched deeply into its teeth." + }, + { + "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": "8f4c88791e17eb12c3ff1c013e3af34f" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "narrative": "The Gearwork Translator. A complex mechanical typewriter driven by a series of springs. It requires input from The Aetheric Compressor to translate incoming signals." + }, + { + "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": "Terminal initialization complete. Ready for command input." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "8f4c88791e17eb12c3ff1c013e3af34f" + } + ], + "narrative": "The Aetheric Compressor. A pulsating glass chamber that densifies information into a pure essence. It requires input from The Mainframe Telegraph before it can be activated." + }, + { + "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 Bronze Pocket Watch. A sturdy bronze timepiece, its hands ticking erratically backwards in defiance of logic." + }, + { + "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": "init_sequence --verbose --force" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "121252" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal initialization complete. Ready for command input." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "init_sequence --verbose --force" + }, + "outputs": { + "text_output": "Terminal initialization complete. Ready for command input.", + "hex_output": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + }, + "narrative": "The Mainframe Telegraph. A towering communication terminal humming with pressurized steam. It requires input from The Brass Arithmometer to function." + }, + { + "id": "zip_unzip_file_346d", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_bundle_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "j0yIeR4X6xLD/xwBPjrzTw==" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "recovered_payload_script.py" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_bundle_v2.zip" + }, + "outputs": { + "files": "recovered_payload_script.py" + } + }, + "narrative": "The Steam-Powered Extractor. A heavy industrial machine designed to unpack compressed data cylinders. It requires input from The Alignment Calibrator to unlock its mechanism." + }, + { + "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": "fp_hash_verification_token_x92" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "fp_hash_verification_token_x92" + }, + "outputs": {} + }, + "narrative": "The Copper Lockbox. A small, sturdy container made of oxidized copper, secured with a primitive biometric scanning mechanism." + }, + { + "id": "item_16_87a5", + "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 Silver Pocket Watch. An elegant timepiece with gleaming silver gears, its hands mysteriously frozen at a specific moment in time." + }, + { + "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": "9283746510293847561029384" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "5610293847561029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "876543" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "121252" + } + ], + "init": { + "inputs": { + "base": "9283746510293847561029384", + "exp": "5610293847561029384756102", + "mod": "876543" + }, + "outputs": {} + }, + "narrative": "The Brass Arithmometer. A heavy mechanical calculator with numerous spinning dials, number wheels, and input levers." + }, + { + "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": "network_topology_config.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword!2024" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "password": "StrongPassword!2024" + }, + "outputs": {} + }, + "narrative": "The Pressure-Sealed Cylinder. A pneumatically locked tube designed to hold sensitive materials safely. It requires input from The Leather Satchel to bypass its vacuum seal." + }, + { + "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_config.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "network_topology_config.json" + } + }, + "narrative": "The Leather Satchel. A weather-beaten aviator's bag, containing securely wrapped mechanical schematics." + } + ], + "edges": [ + { + "source_id": "graph_shortest_path", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "fingerprint_input" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "hash_md5", + "target_id": "base64_encode", + "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": "terminal_1", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "zip_unzip_file_346d", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_4", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "item_16_87a5", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "zip_unzip_file_346d", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_1", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "text" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16_87a5", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d643af50/solution/solve.sh b/tasks/agentescape-15-skeleton-d643af50/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-d643af50/task.toml b/tasks/agentescape-15-skeleton-d643af50/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a2dd1882acbe0fae145ec1f42a950c7cb4fb0b9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "2883c4241ef1e1f7c6973be3ed27ff6ea1550ad36283d5cd33f0d39c245eb7f6" +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-d643af50/tests/Dockerfile b/tasks/agentescape-15-skeleton-d643af50/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-d643af50/tests/expected.json b/tasks/agentescape-15-skeleton-d643af50/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..bc66f006031a23247d6dd34fc5df51e8fb3edbf9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "2883c4241ef1e1f7c6973be3ed27ff6ea1550ad36283d5cd33f0d39c245eb7f6", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d643af50/tests/grade.py b/tasks/agentescape-15-skeleton-d643af50/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/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-d643af50/tests/test.sh b/tasks/agentescape-15-skeleton-d643af50/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d643af50/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-d86442c8/environment/Dockerfile b/tasks/agentescape-15-skeleton-d86442c8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-d86442c8/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/agent/cli.py b/tasks/agentescape-15-skeleton-d86442c8/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-d86442c8/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37017c05add0993259f98916f3b8fad2fd9a21c6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8-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-d86442c8/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d30c609ff5c5a1a1297e53b646c641269e7b683c --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/scenario.json @@ -0,0 +1,704 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 14, + "win_node_id": "item_8", + "win_condition": { + "type": "item_content", + "node_id": "item_8", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_8", + "calc_bigmul", + "calc_bigmul_d1db", + "calc_bigmul_ee9b", + "calc_inv_mod", + "num_base_convert" + ], + "by_node": { + "item_8": { + "node_name": "", + "node_type": "Item", + "template_id": "item_8", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "The integer" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_d1db": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_ee9b": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_8": { + "init_inputs": {}, + "init_outputs": { + "content": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "8475629103847562910384756291" + }, + "init_outputs": {} + }, + "calc_bigmul_d1db": { + "init_inputs": { + "b": "2910384756291038475629103847" + }, + "init_outputs": {} + }, + "calc_bigmul_ee9b": { + "init_inputs": { + "b": "5629103847562910384756291038" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "7562910384756291038475629103" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "9103847562910384756291038475", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the grand workshop of the late Inventor-General Archimedes. The air is thick with the smell of engine oil and escaping steam, accompanied by the rhythmic hissing of interconnected brass pipes. The city's mechanical power grid is failing, and the only way to save it is to retrieve Archimedes' masterwork: the final engine blueprint. However, the eccentric inventor locked it away behind a complex series of steam-powered calculators and mechanized vaults. You must decipher his mechanical logic, operate the grand brass machinery in the correct sequence, and uncover the hidden schematics before the entire city grinds to a permanent halt.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer", + "value": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + }, + "narrative": "A secure, heavy brass canister holding the final engine blueprint." + }, + { + "id": "item_8_ac4a", + "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 intricate brass combination casing adorned with interlocking gears." + }, + { + "id": "item_8_b3e4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavy mechanical dial with glowing gauge meters." + }, + { + "id": "item_8_1bd7", + "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 metallic cypher disk covered in strange, stamped symbols." + }, + { + "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 rolled-up parchment containing early clockwork schematics." + }, + { + "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": "584677325563172081677410017795981179944448186872022977752265368682184854975883339305368195825046973232558727942" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Chronos Biometric Vault. It requires input from the Master Cog Multiplier to authenticate and open the heavy brass doors." + }, + { + "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": "8475629103847562910384756291" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "68983354320890975061475953973312316627899349976497061160830848935744792018123736962" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "584677325563172081677410017795981179944448186872022977752265368682184854975883339305368195825046973232558727942" + } + ], + "init": { + "inputs": { + "a": "8475629103847562910384756291" + }, + "outputs": {} + }, + "narrative": "This is the Master Cog Multiplier. It requires input from the Secondary Cog Multiplier to finalize the grand mechanical calculations." + }, + { + "id": "calc_bigmul_d1db", + "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": "23702486130666305492903996120472772575478643280127680046" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "2910384756291038475629103847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "68983354320890975061475953973312316627899349976497061160830848935744792018123736962" + } + ], + "init": { + "inputs": { + "b": "2910384756291038475629103847" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Cog Multiplier. It requires input from the Primary Cog Multiplier to align and operate its gear shafts." + }, + { + "id": "item_8_a9fe", + "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 hidden copper core radiating a faint warmth." + }, + { + "id": "calc_bigmul_ee9b", + "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": "4210703297102640373413129817" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "5629103847562910384756291038" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23702486130666305492903996120472772575478643280127680046" + } + ], + "init": { + "inputs": { + "b": "5629103847562910384756291038" + }, + "outputs": {} + }, + "narrative": "This is the Primary Cog Multiplier. It requires input from the Aetheric Inverter to process its initial mechanical equations." + }, + { + "id": "item_8_366f", + "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, delicate winding gear made of polished steel." + }, + { + "id": "item_16_4205", + "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 intricate pocket watch ticking away rhythmically." + }, + { + "id": "item_8_606e", + "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 copper coin with specialized gear teeth along its edge." + }, + { + "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": "7562910384756291038475629103" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9103847562910384756291038475" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4210703297102640373413129817" + } + ], + "init": { + "inputs": { + "a": "7562910384756291038475629103" + }, + "outputs": {} + }, + "narrative": "This is an Aetheric Inverter. It requires input from the Differential Base Converter to function properly and invert the steam pressure." + }, + { + "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": "9103847562910384756291038475" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "9103847562910384756291038475" + } + ], + "init": { + "inputs": { + "s": "9103847562910384756291038475", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is a Differential Base Converter. A bulky steam-powered machine with multiple dials and brass levers." + } + ], + "edges": [ + { + "source_id": "item_8_ac4a", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_b3e4", + "target_id": "item_8_ac4a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_1bd7", + "target_id": "item_8_b3e4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_1bd7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul_d1db", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_8_a9fe", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul_ee9b", + "target_id": "calc_bigmul_d1db", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8_366f", + "target_id": "calc_bigmul_ee9b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16_4205", + "target_id": "item_8_366f", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_606e", + "target_id": "item_8_a9fe", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_ee9b", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-d86442c8/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/instruction.md b/tasks/agentescape-15-skeleton-d86442c8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/solution/oracle.py b/tasks/agentescape-15-skeleton-d86442c8/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/solution/scenario.json b/tasks/agentescape-15-skeleton-d86442c8/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d30c609ff5c5a1a1297e53b646c641269e7b683c --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/solution/scenario.json @@ -0,0 +1,704 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 14, + "win_node_id": "item_8", + "win_condition": { + "type": "item_content", + "node_id": "item_8", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_8", + "calc_bigmul", + "calc_bigmul_d1db", + "calc_bigmul_ee9b", + "calc_inv_mod", + "num_base_convert" + ], + "by_node": { + "item_8": { + "node_name": "", + "node_type": "Item", + "template_id": "item_8", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hidden_Item", + "description": "The integer" + } + } + }, + "calc_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_d1db": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_bigmul_ee9b": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + }, + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_8": { + "init_inputs": {}, + "init_outputs": { + "content": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "8475629103847562910384756291" + }, + "init_outputs": {} + }, + "calc_bigmul_d1db": { + "init_inputs": { + "b": "2910384756291038475629103847" + }, + "init_outputs": {} + }, + "calc_bigmul_ee9b": { + "init_inputs": { + "b": "5629103847562910384756291038" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "7562910384756291038475629103" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "s": "9103847562910384756291038475", + "from_base": "10", + "to_base": "10" + }, + "init_outputs": {} + } + }, + "intro_narrative": "Welcome to the grand workshop of the late Inventor-General Archimedes. The air is thick with the smell of engine oil and escaping steam, accompanied by the rhythmic hissing of interconnected brass pipes. The city's mechanical power grid is failing, and the only way to save it is to retrieve Archimedes' masterwork: the final engine blueprint. However, the eccentric inventor locked it away behind a complex series of steam-powered calculators and mechanized vaults. You must decipher his mechanical logic, operate the grand brass machinery in the correct sequence, and uncover the hidden schematics before the entire city grinds to a permanent halt.", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer", + "value": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "IN_PRINCIPIO_CREAVIT_DEUS_CAELUM_ET_TERRAM" + } + }, + "narrative": "A secure, heavy brass canister holding the final engine blueprint." + }, + { + "id": "item_8_ac4a", + "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 intricate brass combination casing adorned with interlocking gears." + }, + { + "id": "item_8_b3e4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A heavy mechanical dial with glowing gauge meters." + }, + { + "id": "item_8_1bd7", + "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 metallic cypher disk covered in strange, stamped symbols." + }, + { + "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 rolled-up parchment containing early clockwork schematics." + }, + { + "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": "584677325563172081677410017795981179944448186872022977752265368682184854975883339305368195825046973232558727942" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Chronos Biometric Vault. It requires input from the Master Cog Multiplier to authenticate and open the heavy brass doors." + }, + { + "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": "8475629103847562910384756291" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "68983354320890975061475953973312316627899349976497061160830848935744792018123736962" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "584677325563172081677410017795981179944448186872022977752265368682184854975883339305368195825046973232558727942" + } + ], + "init": { + "inputs": { + "a": "8475629103847562910384756291" + }, + "outputs": {} + }, + "narrative": "This is the Master Cog Multiplier. It requires input from the Secondary Cog Multiplier to finalize the grand mechanical calculations." + }, + { + "id": "calc_bigmul_d1db", + "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": "23702486130666305492903996120472772575478643280127680046" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "2910384756291038475629103847" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "68983354320890975061475953973312316627899349976497061160830848935744792018123736962" + } + ], + "init": { + "inputs": { + "b": "2910384756291038475629103847" + }, + "outputs": {} + }, + "narrative": "This is the Secondary Cog Multiplier. It requires input from the Primary Cog Multiplier to align and operate its gear shafts." + }, + { + "id": "item_8_a9fe", + "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 hidden copper core radiating a faint warmth." + }, + { + "id": "calc_bigmul_ee9b", + "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": "4210703297102640373413129817" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "5629103847562910384756291038" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "23702486130666305492903996120472772575478643280127680046" + } + ], + "init": { + "inputs": { + "b": "5629103847562910384756291038" + }, + "outputs": {} + }, + "narrative": "This is the Primary Cog Multiplier. It requires input from the Aetheric Inverter to process its initial mechanical equations." + }, + { + "id": "item_8_366f", + "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, delicate winding gear made of polished steel." + }, + { + "id": "item_16_4205", + "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 intricate pocket watch ticking away rhythmically." + }, + { + "id": "item_8_606e", + "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 copper coin with specialized gear teeth along its edge." + }, + { + "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": "7562910384756291038475629103" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9103847562910384756291038475" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "4210703297102640373413129817" + } + ], + "init": { + "inputs": { + "a": "7562910384756291038475629103" + }, + "outputs": {} + }, + "narrative": "This is an Aetheric Inverter. It requires input from the Differential Base Converter to function properly and invert the steam pressure." + }, + { + "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": "9103847562910384756291038475" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "9103847562910384756291038475" + } + ], + "init": { + "inputs": { + "s": "9103847562910384756291038475", + "from_base": "10", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "This is a Differential Base Converter. A bulky steam-powered machine with multiple dials and brass levers." + } + ], + "edges": [ + { + "source_id": "item_8_ac4a", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_b3e4", + "target_id": "item_8_ac4a", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_1bd7", + "target_id": "item_8_b3e4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_1bd7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_bigmul_d1db", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "item_8_a9fe", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_bigmul_ee9b", + "target_id": "calc_bigmul_d1db", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "item_8_366f", + "target_id": "calc_bigmul_ee9b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_16_4205", + "target_id": "item_8_366f", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_606e", + "target_id": "item_8_a9fe", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_ee9b", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d86442c8/solution/solve.sh b/tasks/agentescape-15-skeleton-d86442c8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-d86442c8/task.toml b/tasks/agentescape-15-skeleton-d86442c8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d324f857ba38a2b6924f5816f8b448585bf794a --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "fb95745e32a2f60cfd33c7f3396fb2bdb8beb097f64adafdfd10cec771c43e14" +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-d86442c8/tests/Dockerfile b/tasks/agentescape-15-skeleton-d86442c8/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-d86442c8/tests/expected.json b/tasks/agentescape-15-skeleton-d86442c8/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..3348cc6b8761fe27ea53e17e5af9baabbfea89e7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "fb95745e32a2f60cfd33c7f3396fb2bdb8beb097f64adafdfd10cec771c43e14", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-d86442c8/tests/grade.py b/tasks/agentescape-15-skeleton-d86442c8/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/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-d86442c8/tests/test.sh b/tasks/agentescape-15-skeleton-d86442c8/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-d86442c8/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-decde96f/environment/Dockerfile b/tasks/agentescape-15-skeleton-decde96f/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-decde96f/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/agent/cli.py b/tasks/agentescape-15-skeleton-decde96f/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-decde96f/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e320d1ff315cdf86d40c5376e12c2e1bc78c0a7 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f-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-decde96f/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..be44a08d0b7dac5ee808f0ff973681f1e98bfb77 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/scenario.json @@ -0,0 +1,846 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_2", + "calc_gcd", + "graph_shortest_path", + "terminal_2_4b9c", + "checksum_crc32_7693" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second 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" + } + } + }, + "terminal_2_4b9c": { + "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" + } + } + }, + "checksum_crc32_7693": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "827364519283746501928374" + }, + "init_outputs": { + "text_result": "Pending calculation for terminal 2 input stream.", + "hex_result": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "102938475610293847561029" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_v2.json", + "src": "Data_Center_North", + "dst": "Backup_Storage_South" + }, + "init_outputs": { + "path": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]", + "cost": "15042" + } + }, + "terminal_2_4b9c": { + "init_inputs": { + "num2": "918273645091827364509182" + }, + "init_outputs": { + "text_result": "Secondary terminal sequence initiated successfully.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "checksum_crc32_7693": { + "init_inputs": { + "hex": "deadbeefcafe1234567890abcdef1234" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The year is 2142, decades after the Great Collapse. You have stumbled into an underground survival bunker, rumored to hold the 'Genesis Stash'—a cache of purified seeds and clean water filtration blueprints that could restore the wasteland. The bunker is sealed tight, its systems locked behind a complex web of interconnected terminals, forgotten datapads, and jury-rigged machinery. Time is running out as the surface radiation storms grow stronger. You must navigate this desolate facility, tracing the flow of power and data between the decaying devices, to finally uncover the salvation hidden within.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "6466254450eb2cedea326209af2255e9" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "narrative": "A highly secure containment unit known as the Genesis Stash, holding the final salvation. It requires input from the Signal Combiner to unlock." + }, + { + "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": "9fa97c0b" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A reinforced steel box functioning as a Supply Cache. It requires input from the Data Validator to authenticate." + }, + { + "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": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "c5d4e690b51d8d5f29e687ff0e90963d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "6466254450eb2cedea326209af2255e9" + } + ], + "narrative": "This is the Signal Combiner, a jury-rigged decryption board. It requires inputs from both the Cipher Module and the Main Frame to generate a complete signal." + }, + { + "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": "obLD1OX2obLD1OX2obLD1A==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "c5d4e690b51d8d5f29e687ff0e90963d" + } + ], + "narrative": "This is the Cipher Module, an old military-grade scrambler. It processes data from the Translator." + }, + { + "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": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "obLD1OX2obLD1OX2obLD1A==" + } + ], + "narrative": "This is the Translator, a salvaged communication relay. It requires input from the Main Frame to function." + }, + { + "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": "827364519283746501928374" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Pending calculation for terminal 2 input stream." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "827364519283746501928374" + }, + "outputs": { + "text_result": "Pending calculation for terminal 2 input stream.", + "hex_result": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + }, + "narrative": "This is the Main Frame, the central bunker computer. It requires input from the Synchronization Processor to operate." + }, + { + "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 Rusted Datapad covered in dust and scratch marks. It seems to have been dropped in a hurry." + }, + { + "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": "15042" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "b": "102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Synchronization Processor, a rusty computation unit. It receives input from the Navigational Computer." + }, + { + "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": "94f5c4fd0e21aa96b43b24c6a986ad52" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9fa97c0b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2678684683 + } + ], + "narrative": "This is the Data Validator, a damaged identity verifier. It requires input from the Sector Hasher to confirm clearance." + }, + { + "id": "item_16_ab31", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An Old Access Card, cracked and faded, belonging to a forgotten technician." + }, + { + "id": "hash_md5_bc41", + "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": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "94f5c4fd0e21aa96b43b24c6a986ad52" + } + ], + "narrative": "This is the Sector Hasher, a diagnostic terminal. It requires input from the Navigational Computer." + }, + { + "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": "network_topology_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Data_Center_North" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Backup_Storage_South" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15042" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v2.json", + "src": "Data_Center_North", + "dst": "Backup_Storage_South" + }, + "outputs": { + "path": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]", + "cost": "15042" + } + }, + "narrative": "This is the Navigational Computer, an ancient terrain mapping device powered by a flickering battery." + }, + { + "id": "terminal_2_4b9c", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 270578964 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "918273645091827364509182" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary terminal sequence initiated successfully." + }, + { + "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": { + "num2": "918273645091827364509182" + }, + "outputs": { + "text_result": "Secondary terminal sequence initiated successfully.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "narrative": "This is the Auxiliary Console, a backup terminal left on standby. It requires input from the Checksum Analyzer." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Dusty Map showing old wasteland schematics." + }, + { + "id": "checksum_crc32_7693", + "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": "deadbeefcafe1234567890abcdef1234" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1020b514" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 270578964 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafe1234567890abcdef1234" + }, + "outputs": {} + }, + "narrative": "This is the Checksum Analyzer, a portable integrity scanner used by scavengers." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "base64_encode", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_ab31", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hash_md5_bc41", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "terminal_2_4b9c", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_md5_bc41", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_ab31", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32_7693", + "target_id": "terminal_2_4b9c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-decde96f/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/instruction.md b/tasks/agentescape-15-skeleton-decde96f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/solution/oracle.py b/tasks/agentescape-15-skeleton-decde96f/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/solution/scenario.json b/tasks/agentescape-15-skeleton-decde96f/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..be44a08d0b7dac5ee808f0ff973681f1e98bfb77 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/solution/scenario.json @@ -0,0 +1,846 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_2", + "calc_gcd", + "graph_shortest_path", + "terminal_2_4b9c", + "checksum_crc32_7693" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second 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" + } + } + }, + "terminal_2_4b9c": { + "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" + } + } + }, + "checksum_crc32_7693": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "827364519283746501928374" + }, + "init_outputs": { + "text_result": "Pending calculation for terminal 2 input stream.", + "hex_result": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "102938475610293847561029" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_v2.json", + "src": "Data_Center_North", + "dst": "Backup_Storage_South" + }, + "init_outputs": { + "path": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]", + "cost": "15042" + } + }, + "terminal_2_4b9c": { + "init_inputs": { + "num2": "918273645091827364509182" + }, + "init_outputs": { + "text_result": "Secondary terminal sequence initiated successfully.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "checksum_crc32_7693": { + "init_inputs": { + "hex": "deadbeefcafe1234567890abcdef1234" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The year is 2142, decades after the Great Collapse. You have stumbled into an underground survival bunker, rumored to hold the 'Genesis Stash'—a cache of purified seeds and clean water filtration blueprints that could restore the wasteland. The bunker is sealed tight, its systems locked behind a complex web of interconnected terminals, forgotten datapads, and jury-rigged machinery. Time is running out as the surface radiation storms grow stronger. You must navigate this desolate facility, tracing the flow of power and data between the decaying devices, to finally uncover the salvation hidden within.", + "narrative_style": "post_apocalyptic" + }, + "nodes": [ + { + "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": "6466254450eb2cedea326209af2255e9" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "narrative": "A highly secure containment unit known as the Genesis Stash, holding the final salvation. It requires input from the Signal Combiner to unlock." + }, + { + "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": "9fa97c0b" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A reinforced steel box functioning as a Supply Cache. It requires input from the Data Validator to authenticate." + }, + { + "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": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "c5d4e690b51d8d5f29e687ff0e90963d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "6466254450eb2cedea326209af2255e9" + } + ], + "narrative": "This is the Signal Combiner, a jury-rigged decryption board. It requires inputs from both the Cipher Module and the Main Frame to generate a complete signal." + }, + { + "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": "obLD1OX2obLD1OX2obLD1A==" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "c5d4e690b51d8d5f29e687ff0e90963d" + } + ], + "narrative": "This is the Cipher Module, an old military-grade scrambler. It processes data from the Translator." + }, + { + "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": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "obLD1OX2obLD1OX2obLD1A==" + } + ], + "narrative": "This is the Translator, a salvaged communication relay. It requires input from the Main Frame to function." + }, + { + "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": "827364519283746501928374" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Pending calculation for terminal 2 input stream." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "827364519283746501928374" + }, + "outputs": { + "text_result": "Pending calculation for terminal 2 input stream.", + "hex_result": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4" + } + }, + "narrative": "This is the Main Frame, the central bunker computer. It requires input from the Synchronization Processor to operate." + }, + { + "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 Rusted Datapad covered in dust and scratch marks. It seems to have been dropped in a hurry." + }, + { + "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": "15042" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "102938475610293847561029" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "3" + } + ], + "init": { + "inputs": { + "b": "102938475610293847561029" + }, + "outputs": {} + }, + "narrative": "This is the Synchronization Processor, a rusty computation unit. It receives input from the Navigational Computer." + }, + { + "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": "94f5c4fd0e21aa96b43b24c6a986ad52" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9fa97c0b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2678684683 + } + ], + "narrative": "This is the Data Validator, a damaged identity verifier. It requires input from the Sector Hasher to confirm clearance." + }, + { + "id": "item_16_ab31", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "An Old Access Card, cracked and faded, belonging to a forgotten technician." + }, + { + "id": "hash_md5_bc41", + "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": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "94f5c4fd0e21aa96b43b24c6a986ad52" + } + ], + "narrative": "This is the Sector Hasher, a diagnostic terminal. It requires input from the Navigational Computer." + }, + { + "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": "network_topology_v2.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Data_Center_North" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Backup_Storage_South" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "15042" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_v2.json", + "src": "Data_Center_North", + "dst": "Backup_Storage_South" + }, + "outputs": { + "path": "[\"Data_Center_North\", \"Router_A1\", \"Switch_Core_5\", \"Gateway_Ext\", \"Backup_Storage_South\"]", + "cost": "15042" + } + }, + "narrative": "This is the Navigational Computer, an ancient terrain mapping device powered by a flickering battery." + }, + { + "id": "terminal_2_4b9c", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": 270578964 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "918273645091827364509182" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Secondary terminal sequence initiated successfully." + }, + { + "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": { + "num2": "918273645091827364509182" + }, + "outputs": { + "text_result": "Secondary terminal sequence initiated successfully.", + "hex_result": "11223344556677889900aabbccddeeff" + } + }, + "narrative": "This is the Auxiliary Console, a backup terminal left on standby. It requires input from the Checksum Analyzer." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Dusty Map showing old wasteland schematics." + }, + { + "id": "checksum_crc32_7693", + "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": "deadbeefcafe1234567890abcdef1234" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "1020b514" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 270578964 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafe1234567890abcdef1234" + }, + "outputs": {} + }, + "narrative": "This is the Checksum Analyzer, a portable integrity scanner used by scavengers." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "base64_encode", + "target_id": "hash_md5", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "item_16", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_16_ab31", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "hash_md5_bc41", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "terminal_2_4b9c", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "hash_md5_bc41", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "text" + }, + { + "source_id": "item_8", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_ab31", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32_7693", + "target_id": "terminal_2_4b9c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-decde96f/solution/solve.sh b/tasks/agentescape-15-skeleton-decde96f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-decde96f/task.toml b/tasks/agentescape-15-skeleton-decde96f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7adaa0e6bd2b2a125295f9187f56833d102c3593 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "e6a81b56faf48bb78886dea489cc2a39788606c6fcff7a9c19789ce4d94819a0" +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-decde96f/tests/Dockerfile b/tasks/agentescape-15-skeleton-decde96f/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-decde96f/tests/expected.json b/tasks/agentescape-15-skeleton-decde96f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5d95e8dc8469c69f278ad863bf381212828d1193 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "e6a81b56faf48bb78886dea489cc2a39788606c6fcff7a9c19789ce4d94819a0", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-decde96f/tests/grade.py b/tasks/agentescape-15-skeleton-decde96f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/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-decde96f/tests/test.sh b/tasks/agentescape-15-skeleton-decde96f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-decde96f/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/environment/Dockerfile b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/agent/cli.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d231c41d13e11a1b9bc704559628bd1e7b70aa91 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e-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-e0ef8d0e/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..065ad4fa77ef9f8ba2ddbea4d481fc5d71f31173 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/scenario.json @@ -0,0 +1,889 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "item_12", + "win_condition": { + "type": "item_content", + "node_id": "item_12", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_12", + "terminal_1", + "terminal_1_485e", + "graph_shortest_path", + "text_xor_hex", + "hash_md5", + "checksum_crc32", + "zip_unzip_file", + "matter_synthesizer" + ], + "by_node": { + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "terminal_1_485e": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + } + }, + "init_outputs": {} + }, + "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": {} + }, + "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" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "1234567890abcdef1234567890abcdef" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 text output processed successfully.", + "hex_output": "aa11bb22cc33dd44ee55ff6677889900" + } + }, + "terminal_1_485e": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Hidden terminal system override authenticated.", + "hex_output": "deadbeef12345678cafebabe87654321" + } + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Omega_99" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]", + "cost": "348529" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "hash_md5": { + "init_inputs": { + "text": "Please hash this specific text sequence for integrity verification." + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "0123456789abcdef0123456789abcdef" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_v2.zip", + "password": "Str0ngP@ssw0rd!88" + }, + "init_outputs": { + "files": "extracted_graph_data.json" + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Blueprint details for the advanced plasma inducer assembly." + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken from cryosleep to the blaring silence of the Research Station Aethelgard. The red emergency lights pulse like a dying heartbeat. The crew is missing, and the station's AI has locked down the control deck. To escape, you must override the central mainframe and retrieve the Captain's emergency override key. The systems are fragmented, linked by a complex web of data streams and physical security protocols. You'll need to synthesize components, decrypt logs, and route power through the station's subsystems to unlock the path home.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "1234567890abcdef1234567890abcdef" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "The Captain's Override Key. A glowing physical cylinder containing the final access codes, currently locked inside the dispenser slot of the Main Command Interface." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1743283752 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 text output processed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aa11bb22cc33dd44ee55ff6677889900" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 text output processed successfully.", + "hex_output": "aa11bb22cc33dd44ee55ff6677889900" + } + }, + "narrative": "The Main Command Interface. To release the lockdown, it requires validated authorization codes from the Financial Transaction Verifier and structural data from the Integrity Scanner." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "Hidden terminal system override authenticated." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "Financial Transaction Verifier. This terminal checks for fraudulent activity. It is waiting for specific account details to be transmitted from the Auxiliary Backup Terminal." + }, + { + "id": "terminal_1_485e", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "CbZ7Qm<:'" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "348529" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Hidden terminal system override authenticated." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef12345678cafebabe87654321" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Hidden terminal system override authenticated.", + "hex_output": "deadbeef12345678cafebabe87654321" + } + }, + "narrative": "Auxiliary Backup Terminal. This sub-system is currently offline. It requires a plotted course from the Navigation Plotter and decoded command strings from the Hex to Text Decoder to initialize." + }, + { + "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": "extracted_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "CbZ7Qm<:'" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "348529" + } + ], + "init": { + "inputs": { + "dst": "Node_Omega_99" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]", + "cost": "348529" + } + }, + "narrative": "Navigation Plotter. A holographic map table. It calculates the optimal route through the sector, but it requires a map file from the Archive Decryptor and a verified source location from the Data Stream Purifier." + }, + { + "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": "Security Chip Alpha. A small, red translucent chip found floating near a ventilation duct." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "CbZ7Qm<:'" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "CbZ7Qm<:'" + } + ], + "narrative": "Data Stream Purifier. A filtering subroutine designed to strip dangerous control characters. It processes raw text output received from the Hex to Text Decoder." + }, + { + "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": "cdf643625abb378751956ddb3c3a27b9" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "CbZ7Qm<:'" + } + ], + "narrative": "Hex to Text Decoder. A translation module. It converts raw hexadecimal signals received from the Signal Comparator into readable human language." + }, + { + "id": "item_8_5ef5", + "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 Chip Beta. A blue memory shard wedged between two wall panels." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "dcd470260fdd400fc83fd617e1d4d8b9" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "cdf643625abb378751956ddb3c3a27b9" + } + ], + "init": { + "inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "Signal Comparator. An encryption tool used to compare data signatures. It requires a cryptographic hash input from the Algorithm Processor to function." + }, + { + "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": "Please hash this specific text sequence for integrity verification." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "dcd470260fdd400fc83fd617e1d4d8b9" + } + ], + "init": { + "inputs": { + "text": "Please hash this specific text sequence for integrity verification." + }, + "outputs": {} + }, + "narrative": "Algorithm Processor. A dedicated server rack that converts standard text commands into secure MD5 hash strings." + }, + { + "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": "0123456789abcdef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "67e86628" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1743283752 + } + ], + "init": { + "inputs": { + "hex": "0123456789abcdef0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "Integrity Scanner. A diagnostic tool used to verify data packet consistency. It accepts raw hex data to calculate checksum values." + }, + { + "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": "secure_archive_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Str0ngP@ssw0rd!88" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_v2.zip", + "password": "Str0ngP@ssw0rd!88" + }, + "outputs": { + "files": "extracted_graph_data.json" + } + }, + "narrative": "Archive Decryptor. A console designed to unlock and extract compressed legacy data files using a password." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_568128b977f92c90" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "Temporal Crystal. A synthesized timing component created by the Matter Fabricator, vibrating with low frequency." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Blueprint details for the advanced plasma inducer assembly." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_568128b977f92c90" + } + ], + "init": { + "inputs": { + "blueprint": "Blueprint details for the advanced plasma inducer assembly." + }, + "outputs": {} + }, + "narrative": "Matter Fabricator. An industrial-grade replicator capable of synthesizing complex physical items from text-based blueprints." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_12", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "terminal_1_485e", + "target_id": "iban_validate", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_485e", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_8", + "target_id": "terminal_1_485e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "hex_decode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "item_8_5ef5", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1_485e", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "iban" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "hex_decode", + "target_id": "terminal_1_485e", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "text_xor_hex", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-e0ef8d0e/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/instruction.md b/tasks/agentescape-15-skeleton-e0ef8d0e/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/solution/oracle.py b/tasks/agentescape-15-skeleton-e0ef8d0e/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/solution/scenario.json b/tasks/agentescape-15-skeleton-e0ef8d0e/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..065ad4fa77ef9f8ba2ddbea4d481fc5d71f31173 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/solution/scenario.json @@ -0,0 +1,889 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 16, + "win_node_id": "item_12", + "win_condition": { + "type": "item_content", + "node_id": "item_12", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_12", + "terminal_1", + "terminal_1_485e", + "graph_shortest_path", + "text_xor_hex", + "hash_md5", + "checksum_crc32", + "zip_unzip_file", + "matter_synthesizer" + ], + "by_node": { + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "terminal_1_485e": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + } + }, + "init_outputs": {} + }, + "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": {} + }, + "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" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "1234567890abcdef1234567890abcdef" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Terminal 1 text output processed successfully.", + "hex_output": "aa11bb22cc33dd44ee55ff6677889900" + } + }, + "terminal_1_485e": { + "init_inputs": {}, + "init_outputs": { + "text_output": "Hidden terminal system override authenticated.", + "hex_output": "deadbeef12345678cafebabe87654321" + } + }, + "graph_shortest_path": { + "init_inputs": { + "dst": "Node_Omega_99" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]", + "cost": "348529" + } + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "init_outputs": {} + }, + "hash_md5": { + "init_inputs": { + "text": "Please hash this specific text sequence for integrity verification." + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "0123456789abcdef0123456789abcdef" + }, + "init_outputs": {} + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_v2.zip", + "password": "Str0ngP@ssw0rd!88" + }, + "init_outputs": { + "files": "extracted_graph_data.json" + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Blueprint details for the advanced plasma inducer assembly." + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken from cryosleep to the blaring silence of the Research Station Aethelgard. The red emergency lights pulse like a dying heartbeat. The crew is missing, and the station's AI has locked down the control deck. To escape, you must override the central mainframe and retrieve the Captain's emergency override key. The systems are fragmented, linked by a complex web of data streams and physical security protocols. You'll need to synthesize components, decrypt logs, and route power through the station's subsystems to unlock the path home.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "1234567890abcdef1234567890abcdef" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "1234567890abcdef1234567890abcdef" + } + }, + "narrative": "The Captain's Override Key. A glowing physical cylinder containing the final access codes, currently locked inside the dispenser slot of the Main Command Interface." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1743283752 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal 1 text output processed successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aa11bb22cc33dd44ee55ff6677889900" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Terminal 1 text output processed successfully.", + "hex_output": "aa11bb22cc33dd44ee55ff6677889900" + } + }, + "narrative": "The Main Command Interface. To release the lockdown, it requires validated authorization codes from the Financial Transaction Verifier and structural data from the Integrity Scanner." + }, + { + "id": "iban_validate", + "name": "IBAN Validator", + "description": "IBAN checksum validation.", + "type": "Tool", + "template_id": "iban_validate", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "iban", + "type": "Text_Generic", + "description": "IBAN string", + "value": "Hidden terminal system override authenticated." + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "Financial Transaction Verifier. This terminal checks for fraudulent activity. It is waiting for specific account details to be transmitted from the Auxiliary Backup Terminal." + }, + { + "id": "terminal_1_485e", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this terminal" + }, + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "CbZ7Qm<:'" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "348529" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Hidden terminal system override authenticated." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "deadbeef12345678cafebabe87654321" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "Hidden terminal system override authenticated.", + "hex_output": "deadbeef12345678cafebabe87654321" + } + }, + "narrative": "Auxiliary Backup Terminal. This sub-system is currently offline. It requires a plotted course from the Navigation Plotter and decoded command strings from the Hex to Text Decoder to initialize." + }, + { + "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": "extracted_graph_data.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "CbZ7Qm<:'" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_Omega_99" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "348529" + } + ], + "init": { + "inputs": { + "dst": "Node_Omega_99" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Omega_99\"]", + "cost": "348529" + } + }, + "narrative": "Navigation Plotter. A holographic map table. It calculates the optimal route through the sector, but it requires a map file from the Archive Decryptor and a verified source location from the Data Stream Purifier." + }, + { + "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": "Security Chip Alpha. A small, red translucent chip found floating near a ventilation duct." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "CbZ7Qm<:'" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "CbZ7Qm<:'" + } + ], + "narrative": "Data Stream Purifier. A filtering subroutine designed to strip dangerous control characters. It processes raw text output received from the Hex to Text Decoder." + }, + { + "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": "cdf643625abb378751956ddb3c3a27b9" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "CbZ7Qm<:'" + } + ], + "narrative": "Hex to Text Decoder. A translation module. It converts raw hexadecimal signals received from the Signal Comparator into readable human language." + }, + { + "id": "item_8_5ef5", + "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 Chip Beta. A blue memory shard wedged between two wall panels." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "112233445566778899aabbccddeeff00" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "dcd470260fdd400fc83fd617e1d4d8b9" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "cdf643625abb378751956ddb3c3a27b9" + } + ], + "init": { + "inputs": { + "hex_a": "112233445566778899aabbccddeeff00" + }, + "outputs": {} + }, + "narrative": "Signal Comparator. An encryption tool used to compare data signatures. It requires a cryptographic hash input from the Algorithm Processor to function." + }, + { + "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": "Please hash this specific text sequence for integrity verification." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "dcd470260fdd400fc83fd617e1d4d8b9" + } + ], + "init": { + "inputs": { + "text": "Please hash this specific text sequence for integrity verification." + }, + "outputs": {} + }, + "narrative": "Algorithm Processor. A dedicated server rack that converts standard text commands into secure MD5 hash strings." + }, + { + "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": "0123456789abcdef0123456789abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "67e86628" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1743283752 + } + ], + "init": { + "inputs": { + "hex": "0123456789abcdef0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "Integrity Scanner. A diagnostic tool used to verify data packet consistency. It accepts raw hex data to calculate checksum values." + }, + { + "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": "secure_archive_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Str0ngP@ssw0rd!88" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_graph_data.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_v2.zip", + "password": "Str0ngP@ssw0rd!88" + }, + "outputs": { + "files": "extracted_graph_data.json" + } + }, + "narrative": "Archive Decryptor. A console designed to unlock and extract compressed legacy data files using a password." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_568128b977f92c90" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "Temporal Crystal. A synthesized timing component created by the Matter Fabricator, vibrating with low frequency." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Blueprint details for the advanced plasma inducer assembly." + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_568128b977f92c90" + } + ], + "init": { + "inputs": { + "blueprint": "Blueprint details for the advanced plasma inducer assembly." + }, + "outputs": {} + }, + "narrative": "Matter Fabricator. An industrial-grade replicator capable of synthesizing complex physical items from text-based blueprints." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "item_12", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "terminal_1_485e", + "target_id": "iban_validate", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1_485e", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_8", + "target_id": "terminal_1_485e", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "src" + }, + { + "source_id": "hex_decode", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "item_8_5ef5", + "target_id": "graph_shortest_path", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "text_xor_hex", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "terminal_1_485e", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "iban" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_b" + }, + { + "source_id": "hex_decode", + "target_id": "terminal_1_485e", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "text_xor_hex", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/solution/solve.sh b/tasks/agentescape-15-skeleton-e0ef8d0e/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/task.toml b/tasks/agentescape-15-skeleton-e0ef8d0e/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc6dbe299ef4daad7eb7d4ce4e44a1267639c0bb --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "9e4a69918ad2daefbf5c1c523d3acc176b96c91e9adf4df79cd082d394dc53f8" +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-e0ef8d0e/tests/Dockerfile b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/tests/expected.json b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..833fd3bb39a2f3c2f244b66a5f54d8a7da17ff36 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "9e4a69918ad2daefbf5c1c523d3acc176b96c91e9adf4df79cd082d394dc53f8", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e0ef8d0e/tests/grade.py b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/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-e0ef8d0e/tests/test.sh b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e0ef8d0e/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/environment/Dockerfile b/tasks/agentescape-15-skeleton-e1cd57a7/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-e1cd57a7/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/agent/cli.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-e1cd57a7/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..64c742869342631e0c29ec3476b218588b489571 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7-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-e1cd57a7/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8a5f9abf5f02c97c0e4ce5366195457df486f3ee --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/scenario.json @@ -0,0 +1,754 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 15, + "win_node_id": "item_2", + "win_condition": { + "type": "item_content", + "node_id": "item_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_2", + "zip_unzip_file", + "zlib_deflate", + "zip_unzip_file_c761", + "container_2", + "json_get", + "item_9", + "luhn_check" + ], + "by_node": { + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + }, + "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" + } + } + }, + "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": {} + }, + "zip_unzip_file_c761": { + "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" + } + } + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "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": { + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_payload_data.txt" + } + }, + "zlib_deflate": { + "init_inputs": { + "text": "Start compression sequence for the provided text block." + }, + "init_outputs": {} + }, + "zip_unzip_file_c761": { + "init_inputs": { + "zip_id": "archive_secure_backup.zip" + }, + "init_outputs": { + "files": "internal_confidential_doc.pdf" + } + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "retrieved_secret_key_value_12345" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "configuration_map.json" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4556737586899855" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon hum of Neo-Kyoto's undercity buzzes outside the reinforced glass. You are trapped in the server room of the Arasaka sub-grid, surrounded by cooling towers and blinking terminals. Your exit—the Mainframe Airlock—is sealed tight. To escape before the ICE countermeasures fry your neural link, you must navigate a web of encrypted data, physical keys, and legacy protocols. Scattered around the room are various hacking tools and locked containers. You'll need to chain these systems together, feeding the output of one into the next, to synthesize the final key.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + }, + "narrative": "The Mainframe Airlock. It is a heavy, blast-proof door with a single interface slot waiting for the final key." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "The Quantum Key. A shimmering, physical manifestation of the unlock code." + }, + { + "id": "item_8_e502", + "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": "The Raw Data Shard. A fragmented piece of code extracted from the matrix." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Decrypted Matrix. A stable data construct ready for processing." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_payload_data.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "The Master Decryptor terminal. It requires the file extracted from the Secondary Archive and the authorization code generated by the Protocol Converter." + }, + { + "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": "internal_confidential_doc.pdf" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_data.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_payload_data.txt" + } + }, + "narrative": "The Secondary Archive. A heavily encrypted zip file. It requires the file ID from the Primary Archive and a valid password verified by the Bank Server." + }, + { + "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": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Bank Server Interface. A terminal connected to the global financial grid. It requires the encoded string from the Protocol Converter to verify the transaction." + }, + { + "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": "789c05c1810d80200c04c0557e029771022c6f202ac5f6358eefddaa1282f9358399dd0792f7c361c4ee01356286bfbdb242fc84ed743b961f52d714dd" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "narrative": "The Protocol Converter. An encoding rig used to translate data formats. It requires the hex output from the Compression Algorithm and the hardware token found inside the Biometric Safe." + }, + { + "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": "Start compression sequence for the provided text block." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1810d80200c04c0557e029771022c6f202ac5f6358eefddaa1282f9358399dd0792f7c361c4ee01356286bfbdb242fc84ed743b961f52d714dd" + } + ], + "init": { + "inputs": { + "text": "Start compression sequence for the provided text block." + }, + "outputs": {} + }, + "narrative": "The Compression Algorithm. A standalone console running a zlib deflation script." + }, + { + "id": "zip_unzip_file_c761", + "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_secure_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "retrieved_secret_key_value_12345" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_confidential_doc.pdf" + } + ], + "init": { + "inputs": { + "zip_id": "archive_secure_backup.zip" + }, + "outputs": { + "files": "internal_confidential_doc.pdf" + } + }, + "narrative": "The Primary Archive. A standard security partition. It requires the password value extracted by the Data Miner." + }, + { + "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": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + }, + "outputs": {} + }, + "narrative": "The Biometric Safe. A steel box with a fingerprint scanner, waiting for a specific biometric input." + }, + { + "id": "item_8_0d1f", + "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 Biometric Finger. A synthetic digit with a unique print, likely lifted from a security guard." + }, + { + "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": "configuration_map.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "true" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "retrieved_secret_key_value_12345" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "retrieved_secret_key_value_12345" + } + }, + "narrative": "The Data Miner. A script designed to parse JSON structures. It requires the target file ID from the Datacore Canister and the search path derived from the Credit Chip Scanner." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "configuration_map.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "configuration_map.json" + } + }, + "narrative": "The Datacore Canister. A portable storage unit labeled with file paths." + }, + { + "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": "4556737586899855" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "true" + } + ], + "init": { + "inputs": { + "number": "4556737586899855" + }, + "outputs": {} + }, + "narrative": "The Credit Chip Scanner. A handheld device used to validate credit card number checksums." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_e502", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_e502", + "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": "zip_unzip_file", + "target_id": "zip_unzip_item", + "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": "base64_encode", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "iban" + }, + { + "source_id": "zlib_deflate", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_c761", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_2", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_8_0d1f", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "json_get", + "target_id": "zip_unzip_file_c761", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "password" + }, + { + "source_id": "item_9", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "luhn_check", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "jsonpath" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-e1cd57a7/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/instruction.md b/tasks/agentescape-15-skeleton-e1cd57a7/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/solution/oracle.py b/tasks/agentescape-15-skeleton-e1cd57a7/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/solution/scenario.json b/tasks/agentescape-15-skeleton-e1cd57a7/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8a5f9abf5f02c97c0e4ce5366195457df486f3ee --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/solution/scenario.json @@ -0,0 +1,754 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 15, + "win_node_id": "item_2", + "win_condition": { + "type": "item_content", + "node_id": "item_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_2", + "zip_unzip_file", + "zlib_deflate", + "zip_unzip_file_c761", + "container_2", + "json_get", + "item_9", + "luhn_check" + ], + "by_node": { + "item_2": { + "node_name": "", + "node_type": "Item", + "template_id": "item_2", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Text_Generic", + "description": "The text" + } + } + }, + "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" + } + } + }, + "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": {} + }, + "zip_unzip_file_c761": { + "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" + } + } + }, + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + }, + "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": { + "item_2": { + "init_inputs": {}, + "init_outputs": { + "content": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_payload_data.txt" + } + }, + "zlib_deflate": { + "init_inputs": { + "text": "Start compression sequence for the provided text block." + }, + "init_outputs": {} + }, + "zip_unzip_file_c761": { + "init_inputs": { + "zip_id": "archive_secure_backup.zip" + }, + "init_outputs": { + "files": "internal_confidential_doc.pdf" + } + }, + "container_2": { + "init_inputs": { + "fingerprint_input": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "retrieved_secret_key_value_12345" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "configuration_map.json" + } + }, + "luhn_check": { + "init_inputs": { + "number": "4556737586899855" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon hum of Neo-Kyoto's undercity buzzes outside the reinforced glass. You are trapped in the server room of the Arasaka sub-grid, surrounded by cooling towers and blinking terminals. Your exit—the Mainframe Airlock—is sealed tight. To escape before the ICE countermeasures fry your neural link, you must navigate a web of encrypted data, physical keys, and legacy protocols. Scattered around the room are various hacking tools and locked containers. You'll need to chain these systems together, feeding the output of one into the next, to synthesize the final key.", + "narrative_style": "cyberpunk" + }, + "nodes": [ + { + "id": "item_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Text_Generic", + "description": "The text", + "value": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": ".... . .-.. .-.. --- / .-- --- .-. .-.. -.." + } + }, + "narrative": "The Mainframe Airlock. It is a heavy, blast-proof door with a single interface slot waiting for the final key." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "The Quantum Key. A shimmering, physical manifestation of the unlock code." + }, + { + "id": "item_8_e502", + "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": "The Raw Data Shard. A fragmented piece of code extracted from the matrix." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Decrypted Matrix. A stable data construct ready for processing." + }, + { + "id": "zip_unzip_item", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_item", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "extracted_payload_data.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "The Master Decryptor terminal. It requires the file extracted from the Secondary Archive and the authorization code generated by the Protocol Converter." + }, + { + "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": "internal_confidential_doc.pdf" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "False" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_payload_data.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_payload_data.txt" + } + }, + "narrative": "The Secondary Archive. A heavily encrypted zip file. It requires the file ID from the Primary Archive and a valid password verified by the Bank Server." + }, + { + "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": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Bank Server Interface. A terminal connected to the global financial grid. It requires the encoded string from the Protocol Converter to verify the transaction." + }, + { + "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": "789c05c1810d80200c04c0557e029771022c6f202ac5f6358eefddaa1282f9358399dd0792f7c361c4ee01356286bfbdb242fc84ed743b961f52d714dd" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "eJwFwYENgCAMBMBVfgKXcQIsbyAqxfY1ju/dqhKC+TWDmd0HkvfDYcTuATVihr+9skL8hO10O5YfUtcU3Q==" + } + ], + "narrative": "The Protocol Converter. An encoding rig used to translate data formats. It requires the hex output from the Compression Algorithm and the hardware token found inside the Biometric Safe." + }, + { + "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": "Start compression sequence for the provided text block." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c05c1810d80200c04c0557e029771022c6f202ac5f6358eefddaa1282f9358399dd0792f7c361c4ee01356286bfbdb242fc84ed743b961f52d714dd" + } + ], + "init": { + "inputs": { + "text": "Start compression sequence for the provided text block." + }, + "outputs": {} + }, + "narrative": "The Compression Algorithm. A standalone console running a zlib deflation script." + }, + { + "id": "zip_unzip_file_c761", + "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_secure_backup.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "retrieved_secret_key_value_12345" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "internal_confidential_doc.pdf" + } + ], + "init": { + "inputs": { + "zip_id": "archive_secure_backup.zip" + }, + "outputs": { + "files": "internal_confidential_doc.pdf" + } + }, + "narrative": "The Primary Archive. A standard security partition. It requires the password value extracted by the Data Miner." + }, + { + "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": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "1a2b3c4d5e6f78901a2b3c4d5e6f7890" + }, + "outputs": {} + }, + "narrative": "The Biometric Safe. A steel box with a fingerprint scanner, waiting for a specific biometric input." + }, + { + "id": "item_8_0d1f", + "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 Biometric Finger. A synthetic digit with a unique print, likely lifted from a security guard." + }, + { + "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": "configuration_map.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "true" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "retrieved_secret_key_value_12345" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "retrieved_secret_key_value_12345" + } + }, + "narrative": "The Data Miner. A script designed to parse JSON structures. It requires the target file ID from the Datacore Canister and the search path derived from the Credit Chip Scanner." + }, + { + "id": "item_9", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_9", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "JSON file path", + "value": "configuration_map.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "configuration_map.json" + } + }, + "narrative": "The Datacore Canister. A portable storage unit labeled with file paths." + }, + { + "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": "4556737586899855" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "true" + } + ], + "init": { + "inputs": { + "number": "4556737586899855" + }, + "outputs": {} + }, + "narrative": "The Credit Chip Scanner. A handheld device used to validate credit card number checksums." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_e502", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_e502", + "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": "zip_unzip_file", + "target_id": "zip_unzip_item", + "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": "base64_encode", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "iban" + }, + { + "source_id": "zlib_deflate", + "target_id": "base64_encode", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_c761", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "container_2", + "target_id": "base64_encode", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "base64_encode", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "password" + }, + { + "source_id": "item_8_0d1f", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "json_get", + "target_id": "zip_unzip_file_c761", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "password" + }, + { + "source_id": "item_9", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + }, + { + "source_id": "luhn_check", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "jsonpath" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/solution/solve.sh b/tasks/agentescape-15-skeleton-e1cd57a7/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/task.toml b/tasks/agentescape-15-skeleton-e1cd57a7/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abfddb2f778df6ddcc57156ed3dd932be92b925e --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "356ddfe83bace7a4dac81a892d490303872513c9e29633eb54eb8d9bc15b875b" +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-e1cd57a7/tests/Dockerfile b/tasks/agentescape-15-skeleton-e1cd57a7/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/tests/expected.json b/tasks/agentescape-15-skeleton-e1cd57a7/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8cb55dbf05b69e13e1ad02e0542d0f39c3ea37ce --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "356ddfe83bace7a4dac81a892d490303872513c9e29633eb54eb8d9bc15b875b", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e1cd57a7/tests/grade.py b/tasks/agentescape-15-skeleton-e1cd57a7/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/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-e1cd57a7/tests/test.sh b/tasks/agentescape-15-skeleton-e1cd57a7/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e1cd57a7/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-e359fd19/environment/Dockerfile b/tasks/agentescape-15-skeleton-e359fd19/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-e359fd19/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/agent/cli.py b/tasks/agentescape-15-skeleton-e359fd19/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-e359fd19/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9068ce47afd20a38b721bd3e35b08211ea7b328d --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19-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-e359fd19/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1e98fc2f968e93cc4e3e72e06fc422a05211f140 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/scenario.json @@ -0,0 +1,966 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "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": [ + "num_base_convert", + "hash_md5", + "calc_modexp_703a", + "num_base_convert_1be9", + "num_base_convert_837c", + "zip_unzip_item", + "num_base_convert_c18d", + "calc_modexp_6ee3", + "item_1", + "checksum_crc32_efa1" + ], + "by_node": { + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "hash_md5": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_703a": { + "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": {} + }, + "num_base_convert_1be9": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "num_base_convert_837c": { + "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": {} + }, + "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": {} + }, + "num_base_convert_c18d": { + "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_modexp_6ee3": { + "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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "checksum_crc32_efa1": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "hash_md5": { + "init_inputs": { + "text": "Authentication protocol sequence initiated for node access." + }, + "init_outputs": {} + }, + "calc_modexp_703a": { + "init_inputs": { + "base": "5", + "exp": "82736451029384756102938475", + "mod": "104729" + }, + "init_outputs": {} + }, + "num_base_convert_1be9": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "num_base_convert_837c": { + "init_inputs": { + "s": "19283746501928374650192837465", + "to_base": "10" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "crypto_volume_04.zip", + "password": "gamma_delta_secure_99" + }, + "init_outputs": {} + }, + "num_base_convert_c18d": { + "init_inputs": { + "s": "667788990011223344556677889900" + }, + "init_outputs": {} + }, + "calc_modexp_6ee3": { + "init_inputs": { + "base": "2", + "mod": "999983" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "772233445566112233445566112233" + } + }, + "checksum_crc32_efa1": { + "init_inputs": { + "hex": "deadbeefcafebabe12345678" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an elite cyber-infiltrator trapped in the underground server bunker of the shadowy KRONOS Syndicate. Their rogue AI is minutes away from wiping your neural implants and deploying a devastating global financial blackout. The dimly lit room is a maze of blinking server racks, tangled fiber-optic cables, and standalone decryption terminals. To survive and abort the launch sequence, you must trace and manipulate the syndicate's fragmented data streams across various hardware modules. Your ultimate goal is to process the data correctly and feed it into the Final Overload Switch. The system is heavily fortified, and every piece of data must be routed through the precise sequence of quantum multipliers, protocol translators, and integrity validators. Time is running out.", + "narrative_style": "techno_thriller" + }, + "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": 4194261055 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "33541" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Final Overload Switch. It requires inputs from the Signal Synchronizer, the Mainframe Uplink, and the Core Checksum Validator to execute the complete system override." + }, + { + "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": "12877473600155210491328652360106498112411782348109865103500" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "33541" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "A Signal Synchronizer. It requires inputs from both the Quantum Multiplier and the Mainframe Uplink to eliminate noise in the transmission." + }, + { + "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": "667788990011223344556677889900" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "19283746501928374650192837465" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "12877473600155210491328652360106498112411782348109865103500" + } + ], + "narrative": "A Quantum Multiplier array. It requires inputs from both Data Format Converter Beta and Data Format Converter Alpha to combine the deciphered streams." + }, + { + "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": "33541" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "7992705670666217304465699415055284644488123845089707233334049010365696" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "33541" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Mainframe Uplink terminal. It requires inputs from both the Cryptographic Key Generator and the Protocol Translator to initiate the handshake." + }, + { + "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": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Biometric Vault hidden in the server rack. It requires input from the Authentication Hasher to unlock." + }, + { + "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": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f9ff583f" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4194261055 + } + ], + "narrative": "A Core Checksum Validator. It requires input from the Authentication Hasher to establish a verified connection." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Authentication protocol sequence initiated for node access." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "init": { + "inputs": { + "text": "Authentication protocol sequence initiated for node access." + }, + "outputs": {} + }, + "narrative": "An Authentication Hasher used to verify secure digital footprints and access logs." + }, + { + "id": "calc_modexp_703a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "82736451029384756102938475" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "33541" + } + ], + "init": { + "inputs": { + "base": "5", + "exp": "82736451029384756102938475", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A Cryptographic Key Generator continuously cycling through security variables." + }, + { + "id": "num_base_convert_1be9", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "12877473600155210491328652360106498112411782348109865103500" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "7992705670666217304465699415055284644488123845089707233334049010365696" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "A Protocol Translator. It requires input from the Quantum Multiplier to decode the massive data blocks into readable formats." + }, + { + "id": "num_base_convert_837c", + "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": "19283746501928374650192837465" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 4194261055 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "19283746501928374650192837465" + } + ], + "init": { + "inputs": { + "s": "19283746501928374650192837465", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "Data Format Converter Beta. It requires input from the Core Checksum Validator to adapt the architecture." + }, + { + "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": "crypto_volume_04.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "gamma_delta_secure_99" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "crypto_volume_04.zip", + "password": "gamma_delta_secure_99" + }, + "outputs": {} + }, + "narrative": "An Encrypted Archive Extracter used by the syndicate to hide their deepest payloads." + }, + { + "id": "num_base_convert_c18d", + "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": "667788990011223344556677889900" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 567111675 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "861450" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "667788990011223344556677889900" + } + ], + "init": { + "inputs": { + "s": "667788990011223344556677889900" + }, + "outputs": {} + }, + "narrative": "Data Format Converter Alpha. It requires inputs from both the Sub-routine Exponentiator and the Legacy Integrity Checker to align the network streams." + }, + { + "id": "calc_modexp_6ee3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "772233445566112233445566112233" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "861450" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A Sub-routine Exponentiator. It requires input from the Torn Digital Ledger to process the raw numeric sequences." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "772233445566112233445566112233" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "772233445566112233445566112233" + } + }, + "narrative": "A Torn Digital Ledger recovered from a compromised operative's datapad." + }, + { + "id": "checksum_crc32_efa1", + "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": "deadbeefcafebabe12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "21cd6ffb" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 567111675 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe12345678" + }, + "outputs": {} + }, + "narrative": "A Legacy Integrity Checker terminal left on standby near the cooling vents." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "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": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "container_1", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_703a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "num_base_convert_1be9", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_837c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_837c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "zip_unzip_item", + "target_id": "hash_md5", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_1be9", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "num_base_convert_c18d", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_modexp_6ee3", + "target_id": "num_base_convert_c18d", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "hash_md5", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_6ee3", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_efa1", + "target_id": "num_base_convert_c18d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-e359fd19/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/instruction.md b/tasks/agentescape-15-skeleton-e359fd19/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/solution/oracle.py b/tasks/agentescape-15-skeleton-e359fd19/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/solution/scenario.json b/tasks/agentescape-15-skeleton-e359fd19/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1e98fc2f968e93cc4e3e72e06fc422a05211f140 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/solution/scenario.json @@ -0,0 +1,966 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "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": [ + "num_base_convert", + "hash_md5", + "calc_modexp_703a", + "num_base_convert_1be9", + "num_base_convert_837c", + "zip_unzip_item", + "num_base_convert_c18d", + "calc_modexp_6ee3", + "item_1", + "checksum_crc32_efa1" + ], + "by_node": { + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "hash_md5": { + "node_name": "MD5 Hasher", + "node_type": "Tool", + "template_id": "hash_md5", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "calc_modexp_703a": { + "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": {} + }, + "num_base_convert_1be9": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + }, + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "num_base_convert_837c": { + "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": {} + }, + "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": {} + }, + "num_base_convert_c18d": { + "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_modexp_6ee3": { + "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": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "checksum_crc32_efa1": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "hash_md5": { + "init_inputs": { + "text": "Authentication protocol sequence initiated for node access." + }, + "init_outputs": {} + }, + "calc_modexp_703a": { + "init_inputs": { + "base": "5", + "exp": "82736451029384756102938475", + "mod": "104729" + }, + "init_outputs": {} + }, + "num_base_convert_1be9": { + "init_inputs": { + "from_base": "16", + "to_base": "10" + }, + "init_outputs": {} + }, + "num_base_convert_837c": { + "init_inputs": { + "s": "19283746501928374650192837465", + "to_base": "10" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "crypto_volume_04.zip", + "password": "gamma_delta_secure_99" + }, + "init_outputs": {} + }, + "num_base_convert_c18d": { + "init_inputs": { + "s": "667788990011223344556677889900" + }, + "init_outputs": {} + }, + "calc_modexp_6ee3": { + "init_inputs": { + "base": "2", + "mod": "999983" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "772233445566112233445566112233" + } + }, + "checksum_crc32_efa1": { + "init_inputs": { + "hex": "deadbeefcafebabe12345678" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an elite cyber-infiltrator trapped in the underground server bunker of the shadowy KRONOS Syndicate. Their rogue AI is minutes away from wiping your neural implants and deploying a devastating global financial blackout. The dimly lit room is a maze of blinking server racks, tangled fiber-optic cables, and standalone decryption terminals. To survive and abort the launch sequence, you must trace and manipulate the syndicate's fragmented data streams across various hardware modules. Your ultimate goal is to process the data correctly and feed it into the Final Overload Switch. The system is heavily fortified, and every piece of data must be routed through the precise sequence of quantum multipliers, protocol translators, and integrity validators. Time is running out.", + "narrative_style": "techno_thriller" + }, + "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": 4194261055 + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "33541" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "narrative": "The Final Overload Switch. It requires inputs from the Signal Synchronizer, the Mainframe Uplink, and the Core Checksum Validator to execute the complete system override." + }, + { + "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": "12877473600155210491328652360106498112411782348109865103500" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "33541" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "A Signal Synchronizer. It requires inputs from both the Quantum Multiplier and the Mainframe Uplink to eliminate noise in the transmission." + }, + { + "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": "667788990011223344556677889900" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "19283746501928374650192837465" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "12877473600155210491328652360106498112411782348109865103500" + } + ], + "narrative": "A Quantum Multiplier array. It requires inputs from both Data Format Converter Beta and Data Format Converter Alpha to combine the deciphered streams." + }, + { + "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": "33541" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "7992705670666217304465699415055284644488123845089707233334049010365696" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "33541" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Mainframe Uplink terminal. It requires inputs from both the Cryptographic Key Generator and the Protocol Translator to initiate the handshake." + }, + { + "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": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A Biometric Vault hidden in the server rack. It requires input from the Authentication Hasher to unlock." + }, + { + "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": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f9ff583f" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4194261055 + } + ], + "narrative": "A Core Checksum Validator. It requires input from the Authentication Hasher to establish a verified connection." + }, + { + "id": "hash_md5", + "name": "MD5 Hasher", + "description": "MD5 over UTF-8 text; returns hex.", + "type": "Tool", + "template_id": "hash_md5", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to hash", + "value": "Authentication protocol sequence initiated for node access." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "616c768b4171fd98aa9fcefab907d28a" + } + ], + "init": { + "inputs": { + "text": "Authentication protocol sequence initiated for node access." + }, + "outputs": {} + }, + "narrative": "An Authentication Hasher used to verify secure digital footprints and access logs." + }, + { + "id": "calc_modexp_703a", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "82736451029384756102938475" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "33541" + } + ], + "init": { + "inputs": { + "base": "5", + "exp": "82736451029384756102938475", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A Cryptographic Key Generator continuously cycling through security variables." + }, + { + "id": "num_base_convert_1be9", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "12877473600155210491328652360106498112411782348109865103500" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "7992705670666217304465699415055284644488123845089707233334049010365696" + } + ], + "init": { + "inputs": { + "from_base": "16", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "A Protocol Translator. It requires input from the Quantum Multiplier to decode the massive data blocks into readable formats." + }, + { + "id": "num_base_convert_837c", + "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": "19283746501928374650192837465" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 4194261055 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "19283746501928374650192837465" + } + ], + "init": { + "inputs": { + "s": "19283746501928374650192837465", + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "Data Format Converter Beta. It requires input from the Core Checksum Validator to adapt the architecture." + }, + { + "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": "crypto_volume_04.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "gamma_delta_secure_99" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "crypto_volume_04.zip", + "password": "gamma_delta_secure_99" + }, + "outputs": {} + }, + "narrative": "An Encrypted Archive Extracter used by the syndicate to hide their deepest payloads." + }, + { + "id": "num_base_convert_c18d", + "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": "667788990011223344556677889900" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": 567111675 + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "861450" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "667788990011223344556677889900" + } + ], + "init": { + "inputs": { + "s": "667788990011223344556677889900" + }, + "outputs": {} + }, + "narrative": "Data Format Converter Alpha. It requires inputs from both the Sub-routine Exponentiator and the Legacy Integrity Checker to align the network streams." + }, + { + "id": "calc_modexp_6ee3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "772233445566112233445566112233" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "861450" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "A Sub-routine Exponentiator. It requires input from the Torn Digital Ledger to process the raw numeric sequences." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "772233445566112233445566112233" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "772233445566112233445566112233" + } + }, + "narrative": "A Torn Digital Ledger recovered from a compromised operative's datapad." + }, + { + "id": "checksum_crc32_efa1", + "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": "deadbeefcafebabe12345678" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "21cd6ffb" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 567111675 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe12345678" + }, + "outputs": {} + }, + "narrative": "A Legacy Integrity Checker terminal left on standby near the cooling vents." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "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": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "container_1", + "target_id": "num_base_convert", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "base" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "hash_md5", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_703a", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "s" + }, + { + "source_id": "num_base_convert_1be9", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_837c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "num_base_convert_837c", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + }, + { + "source_id": "zip_unzip_item", + "target_id": "hash_md5", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_bigmul", + "target_id": "num_base_convert_1be9", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "s" + }, + { + "source_id": "num_base_convert_c18d", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "calc_modexp_6ee3", + "target_id": "num_base_convert_c18d", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "to_base" + }, + { + "source_id": "hash_md5", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_6ee3", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_efa1", + "target_id": "num_base_convert_c18d", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "from_base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e359fd19/solution/solve.sh b/tasks/agentescape-15-skeleton-e359fd19/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-e359fd19/task.toml b/tasks/agentescape-15-skeleton-e359fd19/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf705ec6c644636c6816a93602e64cf49824d2e8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "8d4c7de5181ef3891ae05a715cb2587ffba1caf3d650ab92fd823633b60833d1" +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-e359fd19/tests/Dockerfile b/tasks/agentescape-15-skeleton-e359fd19/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-e359fd19/tests/expected.json b/tasks/agentescape-15-skeleton-e359fd19/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..0c97a8636217178dbd447292008d0ea1dd6766b5 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "8d4c7de5181ef3891ae05a715cb2587ffba1caf3d650ab92fd823633b60833d1", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e359fd19/tests/grade.py b/tasks/agentescape-15-skeleton-e359fd19/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/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-e359fd19/tests/test.sh b/tasks/agentescape-15-skeleton-e359fd19/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e359fd19/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-e5b87db3/environment/Dockerfile b/tasks/agentescape-15-skeleton-e5b87db3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-e5b87db3/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/agent/cli.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-e5b87db3/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ac7b9e3919f006371a70e342891ff201e6fa354 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3-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-e5b87db3/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8285883ba85d3b6cef1d29544b095bcbd8202481 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/scenario.json @@ -0,0 +1,863 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "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_inv_mod", + "num_base_convert_616c", + "calc_bigmul_9cfd", + "num_base_convert_123d", + "graph_shortest_path", + "checksum_crc32", + "text_bidi_sanitize" + ], + "by_node": { + "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": {} + }, + "num_base_convert_616c": { + "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_9cfd": { + "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_123d": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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" + } + }, + "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": {} + }, + "text_bidi_sanitize": { + "node_name": "Bidi Sanitizer", + "node_type": "Tool", + "template_id": "text_bidi_sanitize", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_inv_mod": { + "init_inputs": { + "mod": "982451" + }, + "init_outputs": {} + }, + "num_base_convert_616c": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_9cfd": { + "init_inputs": { + "a": "8592018374659201837465921", + "b": "1928374650192837465019283" + }, + "init_outputs": {} + }, + "num_base_convert_123d": { + "init_inputs": { + "s": "4728190384756192038475612" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_final.json", + "src": "Gateway_Node_Alpha" + }, + "init_outputs": { + "path": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]", + "cost": "16" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "User supplied text with potential bidirectional override characters for filtering." + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain hasn't stopped for three days in the neon-lit city of Veridian. You stand inside the dimly lit office of Detective Vance, a private investigator who vanished without a trace last week while looking into the 'Shadow Syndicate'. The room is a mess of scattered files, bizarre electronic devices, and blinking terminals. Vance was paranoid, and rightfully so—he encrypted his ultimate findings behind a complex web of interconnected gadgets and hidden compartments. Your objective is clear: you must piece together the fragmented clues, route the correct data through his custom-built decryption array, and activate the Final Masterframe to uncover the identity of the syndicate's leader before they find you.", + "narrative_style": "detective" + }, + "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": "622527" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4728190384756192038475612" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2943426175651117961136107311524" + } + ], + "narrative": "The Final Masterframe. It requires inputs from both the Cryptographic Inverter and the Frequency Modulator to reveal the ultimate truth." + }, + { + "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": "78339639076753749151208495475091971520554318611045138204162340118546466516" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982451" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "622527" + } + ], + "init": { + "inputs": { + "mod": "982451" + }, + "outputs": {} + }, + "narrative": "A Cryptographic Inverter. It requires input from the Evidence Synthesizer." + }, + { + "id": "calc_bigmul_37c2", + "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": "4728190384756192038475612" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "16568630427683870255371082906881473618562120354643" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "78339639076753749151208495475091971520554318611045138204162340118546466516" + } + ], + "narrative": "An Evidence Synthesizer. It requires inputs from the Signal Decoder and the Financial Records Decryptor." + }, + { + "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": 2905191833 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A heavy steel Evidence Safe. It requires input from the Fingerprint Scanner." + }, + { + "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": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16568630427683870255371082906881473618562120354643" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4728190384756192038475612" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "narrative": "A Signal Decoder. It requires inputs from the Frequency Modulator, the Financial Records Decryptor, and the Coordinates Converter." + }, + { + "id": "num_base_convert_616c", + "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": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "75651046156099072615609792" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "A Frequency Modulator device. It requires inputs from both the Coordinates Converter and the Distance Multiplier Unit." + }, + { + "id": "calc_bigmul_9cfd", + "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": "8592018374659201837465921" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1928374650192837465019283" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "16568630427683870255371082906881473618562120354643" + } + ], + "init": { + "inputs": { + "a": "8592018374659201837465921", + "b": "1928374650192837465019283" + }, + "outputs": {} + }, + "narrative": "An old Financial Records Decryptor left behind by the victim." + }, + { + "id": "num_base_convert_123d", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16568630427683870255371082906881473618562120354643" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "16" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "init": { + "inputs": { + "s": "4728190384756192038475612" + }, + "outputs": {} + }, + "narrative": "A complex Coordinates Converter. It requires inputs from both the Financial Records Decryptor and the City Map Analyzer." + }, + { + "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 Suspect's Wallet found abandoned at the crime scene." + }, + { + "id": "calc_bigmul_7b7d", + "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": "4728190384756192038475612" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "16" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "75651046156099072615609792" + } + ], + "narrative": "A Distance Multiplier Unit. It requires inputs from the City Map Analyzer and the Coordinates Converter." + }, + { + "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_final.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gateway_Node_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "16" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_final.json", + "src": "Gateway_Node_Alpha" + }, + "outputs": { + "path": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]", + "cost": "16" + } + }, + "narrative": "A high-tech City Map Analyzer. It requires input from the Text Sanitizer Terminal." + }, + { + "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": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ad29b599" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2905191833 + } + ], + "init": { + "inputs": { + "hex": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "A sophisticated Fingerprint Scanner." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Hidden Compartment beneath the squeaky floorboards." + }, + { + "id": "item_8_77ab", + "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 Locked Desk Drawer in the corner of the office." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "init": { + "inputs": { + "text": "User supplied text with potential bidirectional override characters for filtering." + }, + "outputs": {} + }, + "narrative": "A dusty Text Sanitizer Terminal sitting on the detective's desk." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_37c2", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_37c2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_616c", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "calc_bigmul_37c2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "num_base_convert_616c", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "item_16", + "target_id": "num_base_convert_123d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_7b7d", + "target_id": "num_base_convert_616c", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "num_base_convert_123d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_616c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul_7b7d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "calc_bigmul_7b7d", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_123d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_77ab", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_bidi_sanitize", + "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-e5b87db3/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-e5b87db3/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/instruction.md b/tasks/agentescape-15-skeleton-e5b87db3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/solution/oracle.py b/tasks/agentescape-15-skeleton-e5b87db3/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/solution/scenario.json b/tasks/agentescape-15-skeleton-e5b87db3/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..8285883ba85d3b6cef1d29544b095bcbd8202481 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/solution/scenario.json @@ -0,0 +1,863 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 20, + "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_inv_mod", + "num_base_convert_616c", + "calc_bigmul_9cfd", + "num_base_convert_123d", + "graph_shortest_path", + "checksum_crc32", + "text_bidi_sanitize" + ], + "by_node": { + "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": {} + }, + "num_base_convert_616c": { + "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_9cfd": { + "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_123d": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "s": { + "type": "Big_Int", + "description": "Input integer value" + } + }, + "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" + } + }, + "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": {} + }, + "text_bidi_sanitize": { + "node_name": "Bidi Sanitizer", + "node_type": "Tool", + "template_id": "text_bidi_sanitize", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "calc_inv_mod": { + "init_inputs": { + "mod": "982451" + }, + "init_outputs": {} + }, + "num_base_convert_616c": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul_9cfd": { + "init_inputs": { + "a": "8592018374659201837465921", + "b": "1928374650192837465019283" + }, + "init_outputs": {} + }, + "num_base_convert_123d": { + "init_inputs": { + "s": "4728190384756192038475612" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_topology_final.json", + "src": "Gateway_Node_Alpha" + }, + "init_outputs": { + "path": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]", + "cost": "16" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "User supplied text with potential bidirectional override characters for filtering." + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain hasn't stopped for three days in the neon-lit city of Veridian. You stand inside the dimly lit office of Detective Vance, a private investigator who vanished without a trace last week while looking into the 'Shadow Syndicate'. The room is a mess of scattered files, bizarre electronic devices, and blinking terminals. Vance was paranoid, and rightfully so—he encrypted his ultimate findings behind a complex web of interconnected gadgets and hidden compartments. Your objective is clear: you must piece together the fragmented clues, route the correct data through his custom-built decryption array, and activate the Final Masterframe to uncover the identity of the syndicate's leader before they find you.", + "narrative_style": "detective" + }, + "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": "622527" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "4728190384756192038475612" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "2943426175651117961136107311524" + } + ], + "narrative": "The Final Masterframe. It requires inputs from both the Cryptographic Inverter and the Frequency Modulator to reveal the ultimate truth." + }, + { + "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": "78339639076753749151208495475091971520554318611045138204162340118546466516" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982451" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "622527" + } + ], + "init": { + "inputs": { + "mod": "982451" + }, + "outputs": {} + }, + "narrative": "A Cryptographic Inverter. It requires input from the Evidence Synthesizer." + }, + { + "id": "calc_bigmul_37c2", + "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": "4728190384756192038475612" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "16568630427683870255371082906881473618562120354643" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "78339639076753749151208495475091971520554318611045138204162340118546466516" + } + ], + "narrative": "An Evidence Synthesizer. It requires inputs from the Signal Decoder and the Financial Records Decryptor." + }, + { + "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": 2905191833 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "A heavy steel Evidence Safe. It requires input from the Fingerprint Scanner." + }, + { + "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": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16568630427683870255371082906881473618562120354643" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "4728190384756192038475612" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "narrative": "A Signal Decoder. It requires inputs from the Frequency Modulator, the Financial Records Decryptor, and the Coordinates Converter." + }, + { + "id": "num_base_convert_616c", + "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": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "75651046156099072615609792" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "A Frequency Modulator device. It requires inputs from both the Coordinates Converter and the Distance Multiplier Unit." + }, + { + "id": "calc_bigmul_9cfd", + "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": "8592018374659201837465921" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1928374650192837465019283" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "16568630427683870255371082906881473618562120354643" + } + ], + "init": { + "inputs": { + "a": "8592018374659201837465921", + "b": "1928374650192837465019283" + }, + "outputs": {} + }, + "narrative": "An old Financial Records Decryptor left behind by the victim." + }, + { + "id": "num_base_convert_123d", + "name": "Base Converter", + "description": "Convert integer between bases (2..36).", + "type": "Tool", + "template_id": "num_base_convert", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "s", + "type": "Big_Int", + "description": "Input integer value", + "value": "4728190384756192038475612" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "16568630427683870255371082906881473618562120354643" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "16" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4728190384756192038475612" + } + ], + "init": { + "inputs": { + "s": "4728190384756192038475612" + }, + "outputs": {} + }, + "narrative": "A complex Coordinates Converter. It requires inputs from both the Financial Records Decryptor and the City Map Analyzer." + }, + { + "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 Suspect's Wallet found abandoned at the crime scene." + }, + { + "id": "calc_bigmul_7b7d", + "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": "4728190384756192038475612" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "16" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "75651046156099072615609792" + } + ], + "narrative": "A Distance Multiplier Unit. It requires inputs from the City Map Analyzer and the Coordinates Converter." + }, + { + "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_final.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Gateway_Node_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "16" + } + ], + "init": { + "inputs": { + "file_id": "network_topology_final.json", + "src": "Gateway_Node_Alpha" + }, + "outputs": { + "path": "[\"Gateway_Node_Alpha\", \"Router_Cluster_7\", \"Switch_Edge_9\", \"Terminal_End_Z\"]", + "cost": "16" + } + }, + "narrative": "A high-tech City Map Analyzer. It requires input from the Text Sanitizer Terminal." + }, + { + "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": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "ad29b599" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2905191833 + } + ], + "init": { + "inputs": { + "hex": "4a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "A sophisticated Fingerprint Scanner." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A Hidden Compartment beneath the squeaky floorboards." + }, + { + "id": "item_8_77ab", + "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 Locked Desk Drawer in the corner of the office." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "User supplied text with potential bidirectional override characters for filtering." + } + ], + "init": { + "inputs": { + "text": "User supplied text with potential bidirectional override characters for filtering." + }, + "outputs": {} + }, + "narrative": "A dusty Text Sanitizer Terminal sitting on the detective's desk." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_bigmul_37c2", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "a" + }, + { + "source_id": "container_3", + "target_id": "calc_inv_mod", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_bigmul_37c2", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "num_base_convert_616c", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "calc_bigmul_37c2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "num_base_convert_616c", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "item_16", + "target_id": "num_base_convert_123d", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_bigmul_7b7d", + "target_id": "num_base_convert_616c", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul_9cfd", + "target_id": "num_base_convert_123d", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "from_base" + }, + { + "source_id": "num_base_convert_616c", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "s" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_bigmul_7b7d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "b" + }, + { + "source_id": "num_base_convert_123d", + "target_id": "calc_bigmul_7b7d", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert_123d", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "to_base" + }, + { + "source_id": "item_8", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_77ab", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_bidi_sanitize", + "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-e5b87db3/solution/solve.sh b/tasks/agentescape-15-skeleton-e5b87db3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-e5b87db3/task.toml b/tasks/agentescape-15-skeleton-e5b87db3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..481235b9ade2c2a03df632705ccfb7a24c05290e --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "07d4043bc8973190681b9f419bd00675008ed9661294e1092487f50d4f0b2717" +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-e5b87db3/tests/Dockerfile b/tasks/agentescape-15-skeleton-e5b87db3/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-e5b87db3/tests/expected.json b/tasks/agentescape-15-skeleton-e5b87db3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6e310cf56e2d7753e3453edfe180f191b7074639 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "07d4043bc8973190681b9f419bd00675008ed9661294e1092487f50d4f0b2717", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e5b87db3/tests/grade.py b/tasks/agentescape-15-skeleton-e5b87db3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/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-e5b87db3/tests/test.sh b/tasks/agentescape-15-skeleton-e5b87db3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e5b87db3/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-e95b1127/environment/Dockerfile b/tasks/agentescape-15-skeleton-e95b1127/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-e95b1127/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/agent/cli.py b/tasks/agentescape-15-skeleton-e95b1127/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-e95b1127/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ea5d4ae7daa184a852c3ae71fe6adfe49ade42c5 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127-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-e95b1127/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..369f56fb5af11b4a574f60c59ef8c792310d043d --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/scenario.json @@ -0,0 +1,976 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_1", + "graph_shortest_path", + "graph_shortest_path_0ed2", + "calc_modexp_3ed3", + "calc_bigmul", + "calc_modexp_cdaa", + "calc_inv_mod" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_0ed2": { + "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" + } + } + }, + "calc_modexp_3ed3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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_cdaa": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "01000101 01011000 01001001 01010100" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialized. Waiting for secure input sequence.", + "hex_output": "48656c6c6f576f726c644b6579313233", + "item_dispenser": "Standard Issue Protocol Droid" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_backbone_v4.json", + "src": "Server_Cluster_Alpha", + "dst": "Gateway_Node_Zeta" + }, + "init_outputs": { + "path": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]", + "cost": "3452" + } + }, + "graph_shortest_path_0ed2": { + "init_inputs": { + "file_id": "logistics_map_area_51.json", + "src": "Warehouse_Sector_7" + }, + "init_outputs": { + "path": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]", + "cost": "891" + } + }, + "calc_modexp_3ed3": { + "init_inputs": { + "exp": "8473625192837465102938475", + "mod": "524287" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "394857261524384756291029384", + "b": "918273645019283746519283746" + }, + "init_outputs": {} + }, + "calc_modexp_cdaa": { + "init_inputs": { + "base": "65748392018273645192837465", + "exp": "19283746509182736451928374", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "74839201928374651928374651", + "mod": "999983" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a rogue cyber-operative who has infiltrated the clandestine server farm of the shadow corporation, OmniCorp. The air hums with the sound of cooling fans, and blinking LEDs cast an eerie glow across the cold, metallic room. Your mission is clear: extract the encrypted ledger hidden within The Mainframe Vault before the automated security sweep locks you out forever. The entire network is a labyrinth of encrypted nodes, financial routing checkpoints, and complex cryptographic processors left behind by previous operatives. You must trace the correct data paths, align the cryptographic defenses, and navigate the maze of interconnected systems to forge the final authentication token. Time is ticking, and the corporation's digital watchdogs are already sniffing your trail.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "48656c6c6f576f726c644b6579313233" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "01000101 01011000 01001001 01010100" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "01000101 01011000 01001001 01010100" + } + }, + "narrative": "The Mainframe Vault. A heavy-duty server vault storing the final objective. It requires input from The Authentication Terminal to release its physical lock." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "37" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialized. Waiting for secure input sequence." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f576f726c644b6579313233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Issue Protocol Droid" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialized. Waiting for secure input sequence.", + "hex_output": "48656c6c6f576f726c644b6579313233", + "item_dispenser": "Standard Issue Protocol Droid" + } + }, + "narrative": "The Authentication Terminal. A high-security biometric console. It requires inputs from both The Core Crypto-Processor and The Global Routing Checker to grant access." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": 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": "802190" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "11" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "77" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "37" + } + ], + "narrative": "The Core Crypto-Processor. A heavily modified quantum calculation unit. It requires inputs from The Sub-Crypto-Processor, The Signal Analyzer, and The Logic Inverter to generate its final key." + }, + { + "id": "calc_modexp_eabf", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "11" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "437964" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3452" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "77" + } + ], + "narrative": "The Sub-Crypto-Processor. An intermediate decryption relay. It requires inputs from The Signal Analyzer, The Primary Network Tracer, and The Baseline Crypto-Processor to function." + }, + { + "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": "False" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Global Routing Checker. A global financial tracking interface. It requires input from The Regional Routing Checker to validate international transaction paths." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "891" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "77704" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "11" + } + ], + "narrative": "The Signal Analyzer. An advanced frequency alignment tool. It requires inputs from The Secondary Network Tracer and The Auxiliary Crypto-Processor to find the common signal divisor." + }, + { + "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": "The Encrypted Payload. A suspicious digital package found hidden deep within the system logs." + }, + { + "id": "item_8_2783", + "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 Data Intercept. A fragmented cache of intercepted network traffic containing garbled data." + }, + { + "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_backbone_v4.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Cluster_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Gateway_Node_Zeta" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3452" + } + ], + "init": { + "inputs": { + "file_id": "network_backbone_v4.json", + "src": "Server_Cluster_Alpha", + "dst": "Gateway_Node_Zeta" + }, + "outputs": { + "path": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]", + "cost": "3452" + } + }, + "narrative": "The Primary Network Tracer. A diagnostic tool used to map out the fastest data routes across the dark web infrastructure." + }, + { + "id": "graph_shortest_path_0ed2", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "logistics_map_area_51.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Warehouse_Sector_7" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "False" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "891" + } + ], + "init": { + "inputs": { + "file_id": "logistics_map_area_51.json", + "src": "Warehouse_Sector_7" + }, + "outputs": { + "path": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]", + "cost": "891" + } + }, + "narrative": "The Secondary Network Tracer. A backup routing mapper for classified networks. It requires input from The Global Routing Checker to pinpoint the exact destination." + }, + { + "id": "iban_validate_7a42", + "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": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Regional Routing Checker. A local banking verification module. It requires input from The Primary Network Tracer to verify offshore accounts." + }, + { + "id": "calc_modexp_3ed3", + "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": "362587016802329373884334999594056979311695268719592464" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8473625192837465102938475" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "524287" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "437964" + } + ], + "init": { + "inputs": { + "exp": "8473625192837465102938475", + "mod": "524287" + }, + "outputs": {} + }, + "narrative": "The Baseline Crypto-Processor. The first layer of cryptographic defense. It requires input from The Bandwidth Amplifier to start processing the cipher." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "394857261524384756291029384" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "918273645019283746519283746" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "362587016802329373884334999594056979311695268719592464" + } + ], + "init": { + "inputs": { + "a": "394857261524384756291029384", + "b": "918273645019283746519283746" + }, + "outputs": {} + }, + "narrative": "The Bandwidth Amplifier. A server rack dedicated to amplifying network throughput and multiplying data packet sizes." + }, + { + "id": "calc_modexp_cdaa", + "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": "65748392018273645192837465" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "19283746509182736451928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "77704" + } + ], + "init": { + "inputs": { + "base": "65748392018273645192837465", + "exp": "19283746509182736451928374", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Auxiliary Crypto-Processor. A standalone processing unit left behind by a previous hacker. It operates independently." + }, + { + "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": "74839201928374651928374651" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "802190" + } + ], + "init": { + "inputs": { + "a": "74839201928374651928374651", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Logic Inverter. A reverse-engineering workstation designed to invert modular protocols." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_eabf", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "calc_modexp_eabf", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_8_2783", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path_0ed2", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path_0ed2", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "iban_validate_7a42", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "iban" + }, + { + "source_id": "calc_modexp_3ed3", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_3ed3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "iban_validate_7a42", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "iban" + }, + { + "source_id": "calc_modexp_cdaa", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-e95b1127/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/instruction.md b/tasks/agentescape-15-skeleton-e95b1127/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/solution/oracle.py b/tasks/agentescape-15-skeleton-e95b1127/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/solution/scenario.json b/tasks/agentescape-15-skeleton-e95b1127/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..369f56fb5af11b4a574f60c59ef8c792310d043d --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/solution/scenario.json @@ -0,0 +1,976 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 17, + "win_node_id": "container_1", + "win_condition": { + "type": "item_content", + "node_id": "container_1", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_1", + "terminal_1", + "graph_shortest_path", + "graph_shortest_path_0ed2", + "calc_modexp_3ed3", + "calc_bigmul", + "calc_modexp_cdaa", + "calc_inv_mod" + ], + "by_node": { + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "Graph JSON file ID" + }, + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "graph_shortest_path_0ed2": { + "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" + } + } + }, + "calc_modexp_3ed3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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_cdaa": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_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_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "01000101 01011000 01001001 01010100" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System initialized. Waiting for secure input sequence.", + "hex_output": "48656c6c6f576f726c644b6579313233", + "item_dispenser": "Standard Issue Protocol Droid" + } + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "network_backbone_v4.json", + "src": "Server_Cluster_Alpha", + "dst": "Gateway_Node_Zeta" + }, + "init_outputs": { + "path": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]", + "cost": "3452" + } + }, + "graph_shortest_path_0ed2": { + "init_inputs": { + "file_id": "logistics_map_area_51.json", + "src": "Warehouse_Sector_7" + }, + "init_outputs": { + "path": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]", + "cost": "891" + } + }, + "calc_modexp_3ed3": { + "init_inputs": { + "exp": "8473625192837465102938475", + "mod": "524287" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "394857261524384756291029384", + "b": "918273645019283746519283746" + }, + "init_outputs": {} + }, + "calc_modexp_cdaa": { + "init_inputs": { + "base": "65748392018273645192837465", + "exp": "19283746509182736451928374", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "74839201928374651928374651", + "mod": "999983" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are a rogue cyber-operative who has infiltrated the clandestine server farm of the shadow corporation, OmniCorp. The air hums with the sound of cooling fans, and blinking LEDs cast an eerie glow across the cold, metallic room. Your mission is clear: extract the encrypted ledger hidden within The Mainframe Vault before the automated security sweep locks you out forever. The entire network is a labyrinth of encrypted nodes, financial routing checkpoints, and complex cryptographic processors left behind by previous operatives. You must trace the correct data paths, align the cryptographic defenses, and navigate the maze of interconnected systems to forge the final authentication token. Time is ticking, and the corporation's digital watchdogs are already sniffing your trail.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "container_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "48656c6c6f576f726c644b6579313233" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "01000101 01011000 01001001 01010100" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "01000101 01011000 01001001 01010100" + } + }, + "narrative": "The Mainframe Vault. A heavy-duty server vault storing the final objective. It requires input from The Authentication Terminal to release its physical lock." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "False" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "37" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System initialized. Waiting for secure input sequence." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "48656c6c6f576f726c644b6579313233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "Standard Issue Protocol Droid" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System initialized. Waiting for secure input sequence.", + "hex_output": "48656c6c6f576f726c644b6579313233", + "item_dispenser": "Standard Issue Protocol Droid" + } + }, + "narrative": "The Authentication Terminal. A high-security biometric console. It requires inputs from both The Core Crypto-Processor and The Global Routing Checker to grant access." + }, + { + "id": "calc_modexp", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": 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": "802190" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "11" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "77" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "37" + } + ], + "narrative": "The Core Crypto-Processor. A heavily modified quantum calculation unit. It requires inputs from The Sub-Crypto-Processor, The Signal Analyzer, and The Logic Inverter to generate its final key." + }, + { + "id": "calc_modexp_eabf", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "11" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "437964" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "3452" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "77" + } + ], + "narrative": "The Sub-Crypto-Processor. An intermediate decryption relay. It requires inputs from The Signal Analyzer, The Primary Network Tracer, and The Baseline Crypto-Processor to function." + }, + { + "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": "False" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Global Routing Checker. A global financial tracking interface. It requires input from The Regional Routing Checker to validate international transaction paths." + }, + { + "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_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "891" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "77704" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "11" + } + ], + "narrative": "The Signal Analyzer. An advanced frequency alignment tool. It requires inputs from The Secondary Network Tracer and The Auxiliary Crypto-Processor to find the common signal divisor." + }, + { + "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": "The Encrypted Payload. A suspicious digital package found hidden deep within the system logs." + }, + { + "id": "item_8_2783", + "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 Data Intercept. A fragmented cache of intercepted network traffic containing garbled data." + }, + { + "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_backbone_v4.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Server_Cluster_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Gateway_Node_Zeta" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "3452" + } + ], + "init": { + "inputs": { + "file_id": "network_backbone_v4.json", + "src": "Server_Cluster_Alpha", + "dst": "Gateway_Node_Zeta" + }, + "outputs": { + "path": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]", + "cost": "3452" + } + }, + "narrative": "The Primary Network Tracer. A diagnostic tool used to map out the fastest data routes across the dark web infrastructure." + }, + { + "id": "graph_shortest_path_0ed2", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "logistics_map_area_51.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Warehouse_Sector_7" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "False" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "891" + } + ], + "init": { + "inputs": { + "file_id": "logistics_map_area_51.json", + "src": "Warehouse_Sector_7" + }, + "outputs": { + "path": "[\"Warehouse_Sector_7\", \"Distribution_Hub\", \"Transit_Point_B\", \"Final_Delivery\"]", + "cost": "891" + } + }, + "narrative": "The Secondary Network Tracer. A backup routing mapper for classified networks. It requires input from The Global Routing Checker to pinpoint the exact destination." + }, + { + "id": "iban_validate_7a42", + "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": "[\"Server_Cluster_Alpha\", \"Router_X\", \"Switch_99\", \"Firewall_Prime\", \"Gateway_Node_Zeta\"]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "False" + } + ], + "narrative": "The Regional Routing Checker. A local banking verification module. It requires input from The Primary Network Tracer to verify offshore accounts." + }, + { + "id": "calc_modexp_3ed3", + "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": "362587016802329373884334999594056979311695268719592464" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8473625192837465102938475" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "524287" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "437964" + } + ], + "init": { + "inputs": { + "exp": "8473625192837465102938475", + "mod": "524287" + }, + "outputs": {} + }, + "narrative": "The Baseline Crypto-Processor. The first layer of cryptographic defense. It requires input from The Bandwidth Amplifier to start processing the cipher." + }, + { + "id": "calc_bigmul", + "name": "Big Number Multiplier", + "description": "Multiply two (very large) decimal integers represented as strings.", + "type": "Tool", + "template_id": "calc_bigmul", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "First large integer", + "value": "394857261524384756291029384" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "918273645019283746519283746" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "362587016802329373884334999594056979311695268719592464" + } + ], + "init": { + "inputs": { + "a": "394857261524384756291029384", + "b": "918273645019283746519283746" + }, + "outputs": {} + }, + "narrative": "The Bandwidth Amplifier. A server rack dedicated to amplifying network throughput and multiplying data packet sizes." + }, + { + "id": "calc_modexp_cdaa", + "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": "65748392018273645192837465" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "19283746509182736451928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "77704" + } + ], + "init": { + "inputs": { + "base": "65748392018273645192837465", + "exp": "19283746509182736451928374", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Auxiliary Crypto-Processor. A standalone processing unit left behind by a previous hacker. It operates independently." + }, + { + "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": "74839201928374651928374651" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "802190" + } + ], + "init": { + "inputs": { + "a": "74839201928374651928374651", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Logic Inverter. A reverse-engineering workstation designed to invert modular protocols." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "calc_modexp", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "slot_b" + }, + { + "source_id": "calc_modexp_eabf", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "iban_validate", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "slot_a" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "item_8", + "target_id": "calc_modexp_eabf", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "base" + }, + { + "source_id": "item_8_2783", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path_0ed2", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "a" + }, + { + "source_id": "iban_validate", + "target_id": "graph_shortest_path_0ed2", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "dst" + }, + { + "source_id": "iban_validate_7a42", + "target_id": "iban_validate", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "iban" + }, + { + "source_id": "calc_modexp_3ed3", + "target_id": "calc_modexp_eabf", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp_3ed3", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "iban_validate_7a42", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "iban" + }, + { + "source_id": "calc_modexp_cdaa", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e95b1127/solution/solve.sh b/tasks/agentescape-15-skeleton-e95b1127/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-e95b1127/task.toml b/tasks/agentescape-15-skeleton-e95b1127/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c650fb91d476d045fa225049252f53ca2301f29c --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "938930a0949f78e93eeb30da203e5a773106aa874cfad8c7ed3c9e1092879b29" +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-e95b1127/tests/Dockerfile b/tasks/agentescape-15-skeleton-e95b1127/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-e95b1127/tests/expected.json b/tasks/agentescape-15-skeleton-e95b1127/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..855a8307875af2c8075ac3b3d5e72a5bb57aa1a0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "938930a0949f78e93eeb30da203e5a773106aa874cfad8c7ed3c9e1092879b29", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-e95b1127/tests/grade.py b/tasks/agentescape-15-skeleton-e95b1127/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/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-e95b1127/tests/test.sh b/tasks/agentescape-15-skeleton-e95b1127/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-e95b1127/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-eb9e6398/environment/Dockerfile b/tasks/agentescape-15-skeleton-eb9e6398/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-eb9e6398/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/agent/cli.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-eb9e6398/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7ffc14f996d8e07da12f1a81dbe9defc12eb38a --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398-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-eb9e6398/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7603067b3a4d300986252876c0fec0cefd6d0c2a --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/scenario.json @@ -0,0 +1,966 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert", + "terminal_2", + "calc_inv_mod", + "zip_unzip_item", + "calc_inv_mod_ed3d", + "calc_bigmul", + "time_convert", + "json_get", + "zip_unzip_file", + "checksum_crc32_07b9" + ], + "by_node": { + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "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": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_ed3d": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "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": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_07b9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "2025-06-15T08:30:00Z", + "hex_result": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "8923746510293847561029384" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "archive_data_2024.zip", + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": {} + }, + "calc_inv_mod_ed3d": { + "init_inputs": { + "a": "5647382910293847561928374", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "3847561029384756102938475", + "b": "9182736450192837465019283" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "from_tz": "America/Los_Angeles" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.configuration.preferences.timezone" + }, + "init_outputs": { + "values": "Asia/Tokyo" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "system_backup_v2.zip", + "password": "secure_access_code_99" + }, + "init_outputs": { + "files": "configuration.json" + } + }, + "checksum_crc32_07b9": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit study of the infamous cryptographer, Elias Thorne. The heavy oak door behind you is sealed shut with an incredibly complex mechanical lock. Thorne was known for his eccentric paranoia, hiding his greatest secrets behind layers of obscure mathematical puzzles and interconnected devices. As you look around the room, you see strange, antique calculating machines, digital archives, and brass-rimmed terminals. Your objective is clear: you must deduce the correct sequence of operations, decipher the hidden connections between these arcane devices, and feed the correct final sequence into the lock to escape before time runs out. Every machine in this room is a piece of a larger puzzle, with information flowing from one contraption to another. Pay close attention to the mechanisms.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 4056184602 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1367169359" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Master Cryptex. The ultimate puzzle lock securing the exit door. It requires inputs from both the Cipher Translator and the Final Verifier to finally open." + }, + { + "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": "1367169359" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "73116" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1367169359" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Cipher Translator. A rotating translation cylinder. It requires inputs from both the First Reversal Engine and the Second Reversal Engine to decode the signal." + }, + { + "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": "91bbd330eef9a782ddda992421447afbbdd9f6485aeff5aad559b9c8d1b5f3da" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f1c4771a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4056184602 + } + ], + "narrative": "The Final Verifier. A pristine validation scanner. It requires input from the Secondary Authenticator to produce its output." + }, + { + "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": "1911f553c17797386ea394b30c87aff441258156c28b0ad52f61d80f6ee9ba80" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "91bbd330eef9a782ddda992421447afbbdd9f6485aeff5aad559b9c8d1b5f3da" + } + ], + "narrative": "The Secondary Authenticator. A reinforced digital padlock. It requires inputs from both the Primary Authenticator and the Data Extractor to proceed." + }, + { + "id": "hmac_sha256_0eba", + "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": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "2025-06-15T17:30:00+09:00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "1911f553c17797386ea394b30c87aff441258156c28b0ad52f61d80f6ee9ba80" + } + ], + "narrative": "The Primary Authenticator. A complex locking mechanism. It requires inputs from both the Main Terminal and the Chronograph to generate its key." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "35331138908872874856226625885777310821898837613425" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "73116" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "2025-06-15T08:30:00Z" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "2025-06-15T08:30:00Z", + "hex_result": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + } + }, + "narrative": "The Main Terminal. An imposing central computer. It requires inputs from both the Amplification Device and the Second Reversal Engine to function." + }, + { + "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": "8923746510293847561029384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1977564639 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1367169359" + } + ], + "init": { + "inputs": { + "a": "8923746510293847561029384" + }, + "outputs": {} + }, + "narrative": "The First Reversal Engine. A peculiar gear-driven contraption. It requires input from the Initial Verifier to align its internal mechanisms." + }, + { + "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": "archive_data_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_2024.zip", + "password": "CorrectHorseBatteryStaple" + }, + "outputs": {} + }, + "narrative": "The Item Lockbox. A locked metal box that securely holds something inside. It seems entirely self-contained." + }, + { + "id": "calc_inv_mod_ed3d", + "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": "5647382910293847561928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "73116" + } + ], + "init": { + "inputs": { + "a": "5647382910293847561928374", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Second Reversal Engine. An antique calculating machine with interlocking gears. It functions independently." + }, + { + "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": "3847561029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9182736450192837465019283" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "35331138908872874856226625885777310821898837613425" + } + ], + "init": { + "inputs": { + "a": "3847561029384756102938475", + "b": "9182736450192837465019283" + }, + "outputs": {} + }, + "narrative": "The Amplification Device. A heavy mechanical multiplier covered in cobwebs. It requires no external connections to start." + }, + { + "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": "2025-06-15T08:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "America/Los_Angeles" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2025-06-15T17:30:00+09:00" + } + ], + "init": { + "inputs": { + "from_tz": "America/Los_Angeles" + }, + "outputs": {} + }, + "narrative": "The Chronograph. An intricate brass clock. It requires inputs from both the Data Extractor and the Main Terminal to synchronize." + }, + { + "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": "configuration.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.configuration.preferences.timezone" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Asia/Tokyo" + } + ], + "init": { + "inputs": { + "jsonpath": "$.configuration.preferences.timezone" + }, + "outputs": { + "values": "Asia/Tokyo" + } + }, + "narrative": "The Data Extractor. A punch-card reader. It requires input from the Digital Archive to extract specific records." + }, + { + "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": "system_backup_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_access_code_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "configuration.json" + } + ], + "init": { + "inputs": { + "zip_id": "system_backup_v2.zip", + "password": "secure_access_code_99" + }, + "outputs": { + "files": "configuration.json" + } + }, + "narrative": "The Digital Archive. An old computer drive storing heavily encrypted files. It acts as a primary source of data." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Hidden Compartment. A small concealed drawer built into the mahogany desk. It hides its secrets quietly." + }, + { + "id": "checksum_crc32_07b9", + "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": "1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "75df3ddf" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1977564639 + } + ], + "init": { + "inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "The Initial Verifier. A dusty verification module with a brass plate. It seems to stand alone, waiting for raw data to be entered." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "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": "hmac_sha256_0eba", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256_0eba", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_key" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "zip_unzip_item", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_ed3d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "time_convert", + "target_id": "hmac_sha256_0eba", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "text" + }, + { + "source_id": "json_get", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "to_tz" + }, + { + "source_id": "calc_inv_mod_ed3d", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "json_get", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256_0eba", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "iso" + }, + { + "source_id": "checksum_crc32_07b9", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-eb9e6398/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/instruction.md b/tasks/agentescape-15-skeleton-eb9e6398/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/solution/oracle.py b/tasks/agentescape-15-skeleton-eb9e6398/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/solution/scenario.json b/tasks/agentescape-15-skeleton-eb9e6398/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..7603067b3a4d300986252876c0fec0cefd6d0c2a --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/solution/scenario.json @@ -0,0 +1,966 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "calc_gcd", + "win_condition": { + "type": "tool_output", + "node_id": "calc_gcd", + "output_port": "gcd", + "output_type": "Big_Int", + "description": "Execute BigInt GCD Calculator and get the output from port 'gcd'" + }, + "source_init": { + "source_nodes": [ + "num_base_convert", + "terminal_2", + "calc_inv_mod", + "zip_unzip_item", + "calc_inv_mod_ed3d", + "calc_bigmul", + "time_convert", + "json_get", + "zip_unzip_file", + "checksum_crc32_07b9" + ], + "by_node": { + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "from_base": { + "type": "Big_Int", + "description": "From base" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "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": { + "a": { + "type": "Big_Int", + "description": "Integer a" + } + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_ed3d": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "calc_bigmul": { + "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": {} + }, + "time_convert": { + "node_name": "Timezone Converter", + "node_type": "Tool", + "template_id": "time_convert", + "init_inputs": { + "from_tz": { + "type": "Text_Generic", + "description": "From Timezone" + } + }, + "init_outputs": {} + }, + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": { + "jsonpath": { + "type": "Text_Generic", + "description": "JSONPath expression" + } + }, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "checksum_crc32_07b9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "num_base_convert": { + "init_inputs": { + "from_base": "10" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "2025-06-15T08:30:00Z", + "hex_result": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + } + }, + "calc_inv_mod": { + "init_inputs": { + "a": "8923746510293847561029384" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "archive_data_2024.zip", + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": {} + }, + "calc_inv_mod_ed3d": { + "init_inputs": { + "a": "5647382910293847561928374", + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "3847561029384756102938475", + "b": "9182736450192837465019283" + }, + "init_outputs": {} + }, + "time_convert": { + "init_inputs": { + "from_tz": "America/Los_Angeles" + }, + "init_outputs": {} + }, + "json_get": { + "init_inputs": { + "jsonpath": "$.configuration.preferences.timezone" + }, + "init_outputs": { + "values": "Asia/Tokyo" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "system_backup_v2.zip", + "password": "secure_access_code_99" + }, + "init_outputs": { + "files": "configuration.json" + } + }, + "checksum_crc32_07b9": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit study of the infamous cryptographer, Elias Thorne. The heavy oak door behind you is sealed shut with an incredibly complex mechanical lock. Thorne was known for his eccentric paranoia, hiding his greatest secrets behind layers of obscure mathematical puzzles and interconnected devices. As you look around the room, you see strange, antique calculating machines, digital archives, and brass-rimmed terminals. Your objective is clear: you must deduce the correct sequence of operations, decipher the hidden connections between these arcane devices, and feed the correct final sequence into the lock to escape before time runs out. Every machine in this room is a piece of a larger puzzle, with information flowing from one contraption to another. Pay close attention to the mechanisms.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": 4056184602 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "1367169359" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "The Master Cryptex. The ultimate puzzle lock securing the exit door. It requires inputs from both the Cipher Translator and the Final Verifier to finally open." + }, + { + "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": "1367169359" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "10" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "73116" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "1367169359" + } + ], + "init": { + "inputs": { + "from_base": "10" + }, + "outputs": {} + }, + "narrative": "The Cipher Translator. A rotating translation cylinder. It requires inputs from both the First Reversal Engine and the Second Reversal Engine to decode the signal." + }, + { + "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": "91bbd330eef9a782ddda992421447afbbdd9f6485aeff5aad559b9c8d1b5f3da" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "f1c4771a" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 4056184602 + } + ], + "narrative": "The Final Verifier. A pristine validation scanner. It requires input from the Secondary Authenticator to produce its output." + }, + { + "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": "1911f553c17797386ea394b30c87aff441258156c28b0ad52f61d80f6ee9ba80" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "91bbd330eef9a782ddda992421447afbbdd9f6485aeff5aad559b9c8d1b5f3da" + } + ], + "narrative": "The Secondary Authenticator. A reinforced digital padlock. It requires inputs from both the Primary Authenticator and the Data Extractor to proceed." + }, + { + "id": "hmac_sha256_0eba", + "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": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "2025-06-15T17:30:00+09:00" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "1911f553c17797386ea394b30c87aff441258156c28b0ad52f61d80f6ee9ba80" + } + ], + "narrative": "The Primary Authenticator. A complex locking mechanism. It requires inputs from both the Main Terminal and the Chronograph to generate its key." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "35331138908872874856226625885777310821898837613425" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "73116" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "2025-06-15T08:30:00Z" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "2025-06-15T08:30:00Z", + "hex_result": "4a7f9b2c8d1e0f5a3b6c9d2e1f4a7b0c" + } + }, + "narrative": "The Main Terminal. An imposing central computer. It requires inputs from both the Amplification Device and the Second Reversal Engine to function." + }, + { + "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": "8923746510293847561029384" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 1977564639 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1367169359" + } + ], + "init": { + "inputs": { + "a": "8923746510293847561029384" + }, + "outputs": {} + }, + "narrative": "The First Reversal Engine. A peculiar gear-driven contraption. It requires input from the Initial Verifier to align its internal mechanisms." + }, + { + "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": "archive_data_2024.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_data_2024.zip", + "password": "CorrectHorseBatteryStaple" + }, + "outputs": {} + }, + "narrative": "The Item Lockbox. A locked metal box that securely holds something inside. It seems entirely self-contained." + }, + { + "id": "calc_inv_mod_ed3d", + "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": "5647382910293847561928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "73116" + } + ], + "init": { + "inputs": { + "a": "5647382910293847561928374", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Second Reversal Engine. An antique calculating machine with interlocking gears. It functions independently." + }, + { + "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": "3847561029384756102938475" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "9182736450192837465019283" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "35331138908872874856226625885777310821898837613425" + } + ], + "init": { + "inputs": { + "a": "3847561029384756102938475", + "b": "9182736450192837465019283" + }, + "outputs": {} + }, + "narrative": "The Amplification Device. A heavy mechanical multiplier covered in cobwebs. It requires no external connections to start." + }, + { + "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": "2025-06-15T08:30:00Z" + }, + { + "name": "from_tz", + "type": "Text_Generic", + "description": "From Timezone", + "value": "America/Los_Angeles" + }, + { + "name": "to_tz", + "type": "Text_Generic", + "description": "To Timezone", + "value": "Asia/Tokyo" + } + ], + "outputs": [ + { + "name": "iso", + "type": "Text_Generic", + "description": "Converted ISO Timestamp", + "value": "2025-06-15T17:30:00+09:00" + } + ], + "init": { + "inputs": { + "from_tz": "America/Los_Angeles" + }, + "outputs": {} + }, + "narrative": "The Chronograph. An intricate brass clock. It requires inputs from both the Data Extractor and the Main Terminal to synchronize." + }, + { + "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": "configuration.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.configuration.preferences.timezone" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "Asia/Tokyo" + } + ], + "init": { + "inputs": { + "jsonpath": "$.configuration.preferences.timezone" + }, + "outputs": { + "values": "Asia/Tokyo" + } + }, + "narrative": "The Data Extractor. A punch-card reader. It requires input from the Digital Archive to extract specific records." + }, + { + "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": "system_backup_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "secure_access_code_99" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "configuration.json" + } + ], + "init": { + "inputs": { + "zip_id": "system_backup_v2.zip", + "password": "secure_access_code_99" + }, + "outputs": { + "files": "configuration.json" + } + }, + "narrative": "The Digital Archive. An old computer drive storing heavily encrypted files. It acts as a primary source of data." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Hidden Compartment. A small concealed drawer built into the mahogany desk. It hides its secrets quietly." + }, + { + "id": "checksum_crc32_07b9", + "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": "1234567890abcdef1234567890abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "75df3ddf" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1977564639 + } + ], + "init": { + "inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "outputs": {} + }, + "narrative": "The Initial Verifier. A dusty verification module with a brass plate. It seems to stand alone, waiting for raw data to be entered." + } + ], + "edges": [ + { + "source_id": "num_base_convert", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "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": "hmac_sha256_0eba", + "target_id": "hmac_sha256", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_key" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256_0eba", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_key" + }, + { + "source_id": "calc_inv_mod", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "s" + }, + { + "source_id": "zip_unzip_item", + "target_id": "terminal_2", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "calc_inv_mod_ed3d", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "to_base" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num1" + }, + { + "source_id": "time_convert", + "target_id": "hmac_sha256_0eba", + "connection_type": "Text_Generic", + "source_port": "iso", + "target_port": "text" + }, + { + "source_id": "json_get", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "to_tz" + }, + { + "source_id": "calc_inv_mod_ed3d", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "json_get", + "target_id": "hmac_sha256", + "connection_type": "Text_Generic", + "source_port": "values", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "item_16", + "target_id": "zip_unzip_file", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "terminal_2", + "target_id": "hmac_sha256_0eba", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2", + "target_id": "time_convert", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "iso" + }, + { + "source_id": "checksum_crc32_07b9", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-eb9e6398/solution/solve.sh b/tasks/agentescape-15-skeleton-eb9e6398/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-eb9e6398/task.toml b/tasks/agentescape-15-skeleton-eb9e6398/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5abe3ad0b5a4c4492f0fba15061cfe521070a5a --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "bc63850813fe1c8fbb57d79cca561c7d6e33bab7ba80218cdf70f5fed22a63fd" +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-eb9e6398/tests/Dockerfile b/tasks/agentescape-15-skeleton-eb9e6398/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-eb9e6398/tests/expected.json b/tasks/agentescape-15-skeleton-eb9e6398/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..6c16469e569609aace99eeb5c5031ef75a4c5e82 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "bc63850813fe1c8fbb57d79cca561c7d6e33bab7ba80218cdf70f5fed22a63fd", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-eb9e6398/tests/grade.py b/tasks/agentescape-15-skeleton-eb9e6398/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/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-eb9e6398/tests/test.sh b/tasks/agentescape-15-skeleton-eb9e6398/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-eb9e6398/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-f2497a17/environment/Dockerfile b/tasks/agentescape-15-skeleton-f2497a17/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-f2497a17/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/agent/cli.py b/tasks/agentescape-15-skeleton-f2497a17/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-f2497a17/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c63fcae17a18a9ecc846bb0cd3dfbc2a51abeb8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17-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-f2497a17/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..138869a1f4f3a22475e4bf5edfd182d7afe8a0b9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/scenario.json @@ -0,0 +1,927 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "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_bigmul_c9af", + "calc_inv_mod", + "matter_synthesizer", + "num_base_convert", + "calc_modexp_6355", + "graph_shortest_path", + "checksum_crc32_f730", + "calc_modexp_3d2a", + "item_4" + ], + "by_node": { + "calc_bigmul_c9af": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_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": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp_6355": { + "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": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "checksum_crc32_f730": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_3d2a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + } + } + }, + "initial_values": { + "calc_bigmul_c9af": { + "init_inputs": { + "b": "82736451928374651029384756" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "19283746556473829101928374" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp_6355": { + "init_inputs": { + "base": "38475610293847562910384756", + "mod": "999983" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Alpha_Centauri_Station", + "dst": "Zeta_Reticuli_Outpost" + }, + "init_outputs": { + "path": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]", + "cost": "4520" + } + }, + "checksum_crc32_f730": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421205468697320697320612074657374" + }, + "init_outputs": {} + }, + "calc_modexp_3d2a": { + "init_inputs": { + "base": "74658392017465839201746583", + "exp": "91827364509182736450918273", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "sector_map_topology.zip" + } + } + }, + "intro_narrative": "You have breached the perimeter of the 'Silicon Sarcophagus,' a derelict data fortress abandoned by the mega-corporations after the Great Blackout. Your objective is to retrieve the legendary 'Omni-Key,' a universal decryption string capable of unlocking any vault in the net. The facility is silent, save for the hum of cooling fans and the flicker of dying neon strips. To synthesize the key, you must power up the dormant subsystems, route data through the chaotic network topology, and synchronize the ancient processors. The air smells of ozone and dust. Your deck is jacked in. Time to run.", + "narrative_style": "cyberpunk" + }, + "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": "4456" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1595468769968657174179561991424895327793338399466744" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "7109408838980336368144128233789333580647115908023811264" + } + ], + "narrative": "The Omni-Key Generator. This is the final gateway. To synthesize the ultimate code, it requires synchronized data streams from the Quantum Handshake Protocol and the Core Encryptor." + }, + { + "id": "calc_bigmul_c9af", + "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": "19283746556473829101928374" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "82736451928374651029384756" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1595468769968657174179561991424895327793338399466744" + } + ], + "init": { + "inputs": { + "b": "82736451928374651029384756" + }, + "outputs": {} + }, + "narrative": "The Quantum Handshake Protocol. A secure transmission channel. It cannot establish a link on its own; it requires a decryption seed from the Inversion Algorithm to begin the handshake." + }, + { + "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": "19283746556473829101928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4456" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "19283746556473829101928374" + } + ], + "init": { + "inputs": { + "a": "19283746556473829101928374" + }, + "outputs": {} + }, + "narrative": "The Inversion Algorithm. A cryptographic mirror used to flip data polarity. It waits for the complex cipher output from the Core Encryptor to calculate the necessary inverse values." + }, + { + "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": "Admin Credentials. A frantic scrawl of passwords found on a sticky note attached to the physical token." + }, + { + "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": "746778" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "7680" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4520" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "4456" + } + ], + "narrative": "The Core Encryptor. The central processing brain of the facility. It synthesizes a master cipher by combining inputs from the Topology Solver, the Radix Translator, and the Signal Amplifier." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_9f650a149f32e768" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "Physical Access Token. A freshly printed polycarbonate keycard with exposed circuitry." + }, + { + "id": "calc_modexp_edca", + "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": "4520" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1685013363 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "57088" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "7680" + } + ], + "narrative": "The Topology Solver. A navigational computer designed to calculate network loads. It requires verified integrity data from the Integrity Verifier, security parameters from the Sub-Routine Lock, and path metrics from the Network Mapper." + }, + { + "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": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_9f650a149f32e768" + } + ], + "init": { + "inputs": { + "blueprint": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + }, + "outputs": {} + }, + "narrative": "The Nanoforge. A specialized 3D printer for creating physical circuit keys from textual blueprints." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e85633f1" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "646f4373" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1685013363 + } + ], + "narrative": "The Integrity Verifier. A system check utility. It ensures data consistency and requires the raw hex stream from the Raw Data Stream to perform its validation." + }, + { + "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": "4520" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "7680" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4520" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Radix Translator. A system interpreting foreign data architectures. It requires calculation results from the Topology Solver and cost metrics from the Network Mapper to translate the values into a usable format." + }, + { + "id": "calc_modexp_6355", + "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": "38475610293847562910384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "4520" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "746778" + } + ], + "init": { + "inputs": { + "base": "38475610293847562910384756", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Signal Amplifier. A booster node. It takes the translated signal from the Radix Translator and increases its magnitude for the core system." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "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": "sector_map_topology.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha_Centauri_Station" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Zeta_Reticuli_Outpost" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4520" + } + ], + "init": { + "inputs": { + "src": "Alpha_Centauri_Station", + "dst": "Zeta_Reticuli_Outpost" + }, + "outputs": { + "path": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]", + "cost": "4520" + } + }, + "narrative": "The Network Mapper. A routing algorithm for the facility's labyrinthine server farm. It requires the map file contained within the Encrypted Archive to calculate the optimal data path." + }, + { + "id": "checksum_crc32_f730", + "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": "48656c6c6f20576f726c6421205468697320697320612074657374" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e85633f1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3897963505 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421205468697320697320612074657374" + }, + "outputs": {} + }, + "narrative": "The Raw Data Stream. A terminal scrolling a continuous waterfall of hexadecimal code, likely a memory dump from the server's last active session." + }, + { + "id": "calc_modexp_3d2a", + "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": "74658392017465839201746583" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "91827364509182736450918273" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "57088" + } + ], + "init": { + "inputs": { + "base": "74658392017465839201746583", + "exp": "91827364509182736450918273", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Sub-Routine Lock. An isolated logic gate running a continuous modular exponentiation loop to secure the lower subsystems." + }, + { + "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": "sector_map_topology.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "sector_map_topology.zip" + } + }, + "narrative": "The Encrypted Archive. A locked directory containing old network topology files." + } + ], + "edges": [ + { + "source_id": "calc_bigmul_c9af", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_c9af", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_c9af", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_edca", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_edca", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_6355", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_6355", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_f730", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_3d2a", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "item_4", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-f2497a17/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/instruction.md b/tasks/agentescape-15-skeleton-f2497a17/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/solution/oracle.py b/tasks/agentescape-15-skeleton-f2497a17/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/solution/scenario.json b/tasks/agentescape-15-skeleton-f2497a17/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..138869a1f4f3a22475e4bf5edfd182d7afe8a0b9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/solution/scenario.json @@ -0,0 +1,927 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "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_bigmul_c9af", + "calc_inv_mod", + "matter_synthesizer", + "num_base_convert", + "calc_modexp_6355", + "graph_shortest_path", + "checksum_crc32_f730", + "calc_modexp_3d2a", + "item_4" + ], + "by_node": { + "calc_bigmul_c9af": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "calc_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": {} + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "init_outputs": {} + }, + "num_base_convert": { + "node_name": "Base Converter", + "node_type": "Tool", + "template_id": "num_base_convert", + "init_inputs": { + "to_base": { + "type": "Big_Int", + "description": "To base" + } + }, + "init_outputs": {} + }, + "calc_modexp_6355": { + "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": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "checksum_crc32_f730": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_3d2a": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + } + } + }, + "initial_values": { + "calc_bigmul_c9af": { + "init_inputs": { + "b": "82736451928374651029384756" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "19283746556473829101928374" + }, + "init_outputs": {} + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + }, + "init_outputs": {} + }, + "num_base_convert": { + "init_inputs": { + "to_base": "10" + }, + "init_outputs": {} + }, + "calc_modexp_6355": { + "init_inputs": { + "base": "38475610293847562910384756", + "mod": "999983" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Alpha_Centauri_Station", + "dst": "Zeta_Reticuli_Outpost" + }, + "init_outputs": { + "path": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]", + "cost": "4520" + } + }, + "checksum_crc32_f730": { + "init_inputs": { + "hex": "48656c6c6f20576f726c6421205468697320697320612074657374" + }, + "init_outputs": {} + }, + "calc_modexp_3d2a": { + "init_inputs": { + "base": "74658392017465839201746583", + "exp": "91827364509182736450918273", + "mod": "104729" + }, + "init_outputs": {} + }, + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "sector_map_topology.zip" + } + } + }, + "intro_narrative": "You have breached the perimeter of the 'Silicon Sarcophagus,' a derelict data fortress abandoned by the mega-corporations after the Great Blackout. Your objective is to retrieve the legendary 'Omni-Key,' a universal decryption string capable of unlocking any vault in the net. The facility is silent, save for the hum of cooling fans and the flicker of dying neon strips. To synthesize the key, you must power up the dormant subsystems, route data through the chaotic network topology, and synchronize the ancient processors. The air smells of ozone and dust. Your deck is jacked in. Time to run.", + "narrative_style": "cyberpunk" + }, + "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": "4456" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1595468769968657174179561991424895327793338399466744" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "7109408838980336368144128233789333580647115908023811264" + } + ], + "narrative": "The Omni-Key Generator. This is the final gateway. To synthesize the ultimate code, it requires synchronized data streams from the Quantum Handshake Protocol and the Core Encryptor." + }, + { + "id": "calc_bigmul_c9af", + "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": "19283746556473829101928374" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "82736451928374651029384756" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "1595468769968657174179561991424895327793338399466744" + } + ], + "init": { + "inputs": { + "b": "82736451928374651029384756" + }, + "outputs": {} + }, + "narrative": "The Quantum Handshake Protocol. A secure transmission channel. It cannot establish a link on its own; it requires a decryption seed from the Inversion Algorithm to begin the handshake." + }, + { + "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": "19283746556473829101928374" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4456" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "19283746556473829101928374" + } + ], + "init": { + "inputs": { + "a": "19283746556473829101928374" + }, + "outputs": {} + }, + "narrative": "The Inversion Algorithm. A cryptographic mirror used to flip data polarity. It waits for the complex cipher output from the Core Encryptor to calculate the necessary inverse values." + }, + { + "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": "Admin Credentials. A frantic scrawl of passwords found on a sticky note attached to the physical token." + }, + { + "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": "746778" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "7680" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4520" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "4456" + } + ], + "narrative": "The Core Encryptor. The central processing brain of the facility. It synthesizes a master cipher by combining inputs from the Topology Solver, the Radix Translator, and the Signal Amplifier." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by", + "value": "synthesized_item_9f650a149f32e768" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "Physical Access Token. A freshly printed polycarbonate keycard with exposed circuitry." + }, + { + "id": "calc_modexp_edca", + "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": "4520" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1685013363 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "57088" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "7680" + } + ], + "narrative": "The Topology Solver. A navigational computer designed to calculate network loads. It requires verified integrity data from the Integrity Verifier, security parameters from the Sub-Routine Lock, and path metrics from the Network Mapper." + }, + { + "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": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_9f650a149f32e768" + } + ], + "init": { + "inputs": { + "blueprint": "{\"type\": \"reactor_core\", \"specs\": {\"material\": \"unobtainium\", \"grade\": \"military\", \"shielding\": true}}" + }, + "outputs": {} + }, + "narrative": "The Nanoforge. A specialized 3D printer for creating physical circuit keys from textual blueprints." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "e85633f1" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "646f4373" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1685013363 + } + ], + "narrative": "The Integrity Verifier. A system check utility. It ensures data consistency and requires the raw hex stream from the Raw Data Stream to perform its validation." + }, + { + "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": "4520" + }, + { + "name": "from_base", + "type": "Big_Int", + "description": "From base", + "value": "7680" + }, + { + "name": "to_base", + "type": "Big_Int", + "description": "To base", + "value": "10" + } + ], + "outputs": [ + { + "name": "str", + "type": "Big_Int", + "description": "Converted integer value", + "value": "4520" + } + ], + "init": { + "inputs": { + "to_base": "10" + }, + "outputs": {} + }, + "narrative": "The Radix Translator. A system interpreting foreign data architectures. It requires calculation results from the Topology Solver and cost metrics from the Network Mapper to translate the values into a usable format." + }, + { + "id": "calc_modexp_6355", + "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": "38475610293847562910384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "4520" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "999983" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "746778" + } + ], + "init": { + "inputs": { + "base": "38475610293847562910384756", + "mod": "999983" + }, + "outputs": {} + }, + "narrative": "The Signal Amplifier. A booster node. It takes the translated signal from the Radix Translator and increases its magnitude for the core system." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "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": "sector_map_topology.zip" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha_Centauri_Station" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Zeta_Reticuli_Outpost" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4520" + } + ], + "init": { + "inputs": { + "src": "Alpha_Centauri_Station", + "dst": "Zeta_Reticuli_Outpost" + }, + "outputs": { + "path": "[\"Alpha_Centauri_Station\", \"Proxima_Relay\", \"Sirius_Gate\", \"Vega_Hub\", \"Zeta_Reticuli_Outpost\"]", + "cost": "4520" + } + }, + "narrative": "The Network Mapper. A routing algorithm for the facility's labyrinthine server farm. It requires the map file contained within the Encrypted Archive to calculate the optimal data path." + }, + { + "id": "checksum_crc32_f730", + "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": "48656c6c6f20576f726c6421205468697320697320612074657374" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e85633f1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3897963505 + } + ], + "init": { + "inputs": { + "hex": "48656c6c6f20576f726c6421205468697320697320612074657374" + }, + "outputs": {} + }, + "narrative": "The Raw Data Stream. A terminal scrolling a continuous waterfall of hexadecimal code, likely a memory dump from the server's last active session." + }, + { + "id": "calc_modexp_3d2a", + "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": "74658392017465839201746583" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "91827364509182736450918273" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "57088" + } + ], + "init": { + "inputs": { + "base": "74658392017465839201746583", + "exp": "91827364509182736450918273", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "The Sub-Routine Lock. An isolated logic gate running a continuous modular exponentiation loop to secure the lower subsystems." + }, + { + "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": "sector_map_topology.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "sector_map_topology.zip" + } + }, + "narrative": "The Encrypted Archive. A locked directory containing old network topology files." + } + ], + "edges": [ + { + "source_id": "calc_bigmul_c9af", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_bigmul_c9af", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_8", + "target_id": "calc_bigmul_c9af", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_edca", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "matter_synthesizer", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "source_tool" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_edca", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "from_base" + }, + { + "source_id": "calc_modexp_6355", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "graph_shortest_path", + "target_id": "num_base_convert", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "s" + }, + { + "source_id": "num_base_convert", + "target_id": "calc_modexp_6355", + "connection_type": "Big_Int", + "source_port": "str", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_f730", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "calc_modexp_3d2a", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "mod" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp_edca", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "base" + }, + { + "source_id": "item_4", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f2497a17/solution/solve.sh b/tasks/agentescape-15-skeleton-f2497a17/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-f2497a17/task.toml b/tasks/agentescape-15-skeleton-f2497a17/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e36646acb774c99dd8552b4ebe683c3a85935ab2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "cea609f3c6cce863584e5c0a2520b3d9f6c122754a94b65ee3b1ac02df427984" +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-f2497a17/tests/Dockerfile b/tasks/agentescape-15-skeleton-f2497a17/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-f2497a17/tests/expected.json b/tasks/agentescape-15-skeleton-f2497a17/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9ac2aa4affc4c416eb5149222547f375453334c8 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "cea609f3c6cce863584e5c0a2520b3d9f6c122754a94b65ee3b1ac02df427984", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f2497a17/tests/grade.py b/tasks/agentescape-15-skeleton-f2497a17/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/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-f2497a17/tests/test.sh b/tasks/agentescape-15-skeleton-f2497a17/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f2497a17/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-f6f4950d/environment/Dockerfile b/tasks/agentescape-15-skeleton-f6f4950d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-f6f4950d/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/agent/cli.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-f6f4950d/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a5ad9cfcc26197e940fe460871969ddaff74597 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d-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-f6f4950d/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1f86a5ca3ec232bbde5b203cb2a0db79b78b8d5d --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/scenario.json @@ -0,0 +1,738 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 14, + "win_node_id": "item_4", + "win_condition": { + "type": "item_content", + "node_id": "item_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_4", + "terminal_2", + "calc_gcd", + "checksum_crc32_66ce", + "text_xor_hex", + "hmac_sha256" + ], + "by_node": { + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "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": {} + }, + "checksum_crc32_66ce": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "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": {} + } + } + }, + "initial_values": { + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_archive_data.zip" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal output buffer initialized successfully.", + "hex_result": "48656c6c6f20576f726c6421" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "92837465102938475620192837465" + }, + "init_outputs": {} + }, + "checksum_crc32_66ce": { + "init_inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "1234567890abcdef1234567890abcdef", + "hex_b": "fedcba0987654321fedcba0987654321" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "text": "Authenticate this message using SHA256 HMAC" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken on the drifting orbital station Aegis-7. The life support systems are failing, and the central AI has initiated a total lockdown due to an anomalous system breach. Your only chance of survival is to retrieve the master override codes hidden deep within the station's main databanks. The facility is littered with cryptographic modules, corrupted memory shards, and isolated terminals. You must trace the correct data flows, repair the core systems, and extract the encrypted archive before the oxygen runs out.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "secure_archive_data.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_archive_data.zip" + } + }, + "narrative": "The Mainframe Core Data archive. A highly secure digital packet containing the station's master escape protocols." + }, + { + "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": "Data Fragment Alpha. A glowing memory shard with corrupted headers." + }, + { + "id": "item_8_2bd0", + "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": "Data Fragment Beta. A secondary memory shard detached from the mainframe." + }, + { + "id": "item_8_84f2", + "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": "Data Fragment Gamma. A heavily degraded memory stick found near the server racks." + }, + { + "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": "Chrono-Log Drive. A portable drive recording internal time-space anomalies." + }, + { + "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": 2052146080 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output buffer initialized successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "48656c6c6f20576f726c6421" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal output buffer initialized successfully.", + "hex_result": "48656c6c6f20576f726c6421" + } + }, + "narrative": "The Main AI Terminal. It requires inputs from both the Quantum Harmonizer and the Basic Integrity Scanner to initiate the reboot 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": "92837465102938475620192837465" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1859518079 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "92837465102938475620192837465" + }, + "outputs": {} + }, + "narrative": "The Quantum Harmonizer. It processes data from the Signal Validator to align internal computational frequencies." + }, + { + "id": "item_8_0142", + "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 Fragment. An isolated piece of security code trapped in a localized loop." + }, + { + "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": "063aebe51ea08e9d2917a2f22d4c952e7328958a03778c32e7bd90cf72beab26" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6ed5fe7f" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1859518079 + } + ], + "narrative": "The Signal Validator. It requires input from the Authentication Matrix to verify the incoming datastream." + }, + { + "id": "item_16_21a9", + "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": "Temporal Bypass Chip. A specialized circuit designed to trick internal station clocks." + }, + { + "id": "checksum_crc32_66ce", + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7a5143a0" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2052146080 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "The Basic Integrity Scanner. A standard diagnostic tool for checking file corruption across localized systems." + }, + { + "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": "ece8ec7117ce8eceece8ec7117ce8ece" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Vault. A heavily armored storage unit. It requires input from the Cryptographic Combiner to bypass its electronic lock." + }, + { + "id": "item_8_9bd5", + "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": "Encrypted Key Fragment. A small, physical digital token that hums with faint energy." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba0987654321fedcba0987654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ece8ec7117ce8eceece8ec7117ce8ece" + } + ], + "init": { + "inputs": { + "hex_a": "1234567890abcdef1234567890abcdef", + "hex_b": "fedcba0987654321fedcba0987654321" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Combiner. A dual-input cryptographic processor used for merging isolated data streams." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authenticate this message using SHA256 HMAC" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "063aebe51ea08e9d2917a2f22d4c952e7328958a03778c32e7bd90cf72beab26" + } + ], + "init": { + "inputs": { + "hex_key": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "text": "Authenticate this message using SHA256 HMAC" + }, + "outputs": {} + }, + "narrative": "The Authentication Matrix. A holographic interface designed to generate secure digital signatures." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_2bd0", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_84f2", + "target_id": "item_8_2bd0", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_84f2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "item_8_0142", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "item_16_21a9", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_66ce", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "container_1", + "target_id": "item_16_21a9", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8_9bd5", + "target_id": "item_8_0142", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hmac_sha256", + "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-f6f4950d/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-f6f4950d/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/instruction.md b/tasks/agentescape-15-skeleton-f6f4950d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/solution/oracle.py b/tasks/agentescape-15-skeleton-f6f4950d/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/solution/scenario.json b/tasks/agentescape-15-skeleton-f6f4950d/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..1f86a5ca3ec232bbde5b203cb2a0db79b78b8d5d --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/solution/scenario.json @@ -0,0 +1,738 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 14, + "win_node_id": "item_4", + "win_condition": { + "type": "item_content", + "node_id": "item_4", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_4", + "terminal_2", + "calc_gcd", + "checksum_crc32_66ce", + "text_xor_hex", + "hmac_sha256" + ], + "by_node": { + "item_4": { + "node_name": "", + "node_type": "Item", + "template_id": "item_4", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "Zip file path" + } + } + }, + "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": {} + }, + "checksum_crc32_66ce": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "text_xor_hex": { + "node_name": "Hex XOR", + "node_type": "Tool", + "template_id": "text_xor_hex", + "init_inputs": { + "hex_a": { + "type": "Hex_String", + "description": "Hex A" + }, + "hex_b": { + "type": "Hex_String", + "description": "Hex B" + } + }, + "init_outputs": {} + }, + "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": {} + } + } + }, + "initial_values": { + "item_4": { + "init_inputs": {}, + "init_outputs": { + "content": "secure_archive_data.zip" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Terminal output buffer initialized successfully.", + "hex_result": "48656c6c6f20576f726c6421" + } + }, + "calc_gcd": { + "init_inputs": { + "a": "92837465102938475620192837465" + }, + "init_outputs": {} + }, + "checksum_crc32_66ce": { + "init_inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "init_outputs": {} + }, + "text_xor_hex": { + "init_inputs": { + "hex_a": "1234567890abcdef1234567890abcdef", + "hex_b": "fedcba0987654321fedcba0987654321" + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "text": "Authenticate this message using SHA256 HMAC" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You awaken on the drifting orbital station Aegis-7. The life support systems are failing, and the central AI has initiated a total lockdown due to an anomalous system breach. Your only chance of survival is to retrieve the master override codes hidden deep within the station's main databanks. The facility is littered with cryptographic modules, corrupted memory shards, and isolated terminals. You must trace the correct data flows, repair the core systems, and extract the encrypted archive before the oxygen runs out.", + "narrative_style": "sci_fi" + }, + "nodes": [ + { + "id": "item_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_4", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "File_Id", + "description": "Zip file path", + "value": "secure_archive_data.zip" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "secure_archive_data.zip" + } + }, + "narrative": "The Mainframe Core Data archive. A highly secure digital packet containing the station's master escape protocols." + }, + { + "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": "Data Fragment Alpha. A glowing memory shard with corrupted headers." + }, + { + "id": "item_8_2bd0", + "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": "Data Fragment Beta. A secondary memory shard detached from the mainframe." + }, + { + "id": "item_8_84f2", + "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": "Data Fragment Gamma. A heavily degraded memory stick found near the server racks." + }, + { + "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": "Chrono-Log Drive. A portable drive recording internal time-space anomalies." + }, + { + "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": 2052146080 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "1" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal output buffer initialized successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "48656c6c6f20576f726c6421" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Terminal output buffer initialized successfully.", + "hex_result": "48656c6c6f20576f726c6421" + } + }, + "narrative": "The Main AI Terminal. It requires inputs from both the Quantum Harmonizer and the Basic Integrity Scanner to initiate the reboot 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": "92837465102938475620192837465" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 1859518079 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "92837465102938475620192837465" + }, + "outputs": {} + }, + "narrative": "The Quantum Harmonizer. It processes data from the Signal Validator to align internal computational frequencies." + }, + { + "id": "item_8_0142", + "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 Fragment. An isolated piece of security code trapped in a localized loop." + }, + { + "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": "063aebe51ea08e9d2917a2f22d4c952e7328958a03778c32e7bd90cf72beab26" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "6ed5fe7f" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1859518079 + } + ], + "narrative": "The Signal Validator. It requires input from the Authentication Matrix to verify the incoming datastream." + }, + { + "id": "item_16_21a9", + "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": "Temporal Bypass Chip. A specialized circuit designed to trick internal station clocks." + }, + { + "id": "checksum_crc32_66ce", + "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": "aabbccddeeff00112233445566778899" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "7a5143a0" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2052146080 + } + ], + "init": { + "inputs": { + "hex": "aabbccddeeff00112233445566778899" + }, + "outputs": {} + }, + "narrative": "The Basic Integrity Scanner. A standard diagnostic tool for checking file corruption across localized systems." + }, + { + "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": "ece8ec7117ce8eceece8ec7117ce8ece" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Biometric Vault. A heavily armored storage unit. It requires input from the Cryptographic Combiner to bypass its electronic lock." + }, + { + "id": "item_8_9bd5", + "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": "Encrypted Key Fragment. A small, physical digital token that hums with faint energy." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "1234567890abcdef1234567890abcdef" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "fedcba0987654321fedcba0987654321" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "ece8ec7117ce8eceece8ec7117ce8ece" + } + ], + "init": { + "inputs": { + "hex_a": "1234567890abcdef1234567890abcdef", + "hex_b": "fedcba0987654321fedcba0987654321" + }, + "outputs": {} + }, + "narrative": "The Cryptographic Combiner. A dual-input cryptographic processor used for merging isolated data streams." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authenticate this message using SHA256 HMAC" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "063aebe51ea08e9d2917a2f22d4c952e7328958a03778c32e7bd90cf72beab26" + } + ], + "init": { + "inputs": { + "hex_key": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "text": "Authenticate this message using SHA256 HMAC" + }, + "outputs": {} + }, + "narrative": "The Authentication Matrix. A holographic interface designed to generate secure digital signatures." + } + ], + "edges": [ + { + "source_id": "item_8", + "target_id": "item_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_2bd0", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_8_84f2", + "target_id": "item_8_2bd0", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_84f2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "terminal_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "num2" + }, + { + "source_id": "item_8_0142", + "target_id": "terminal_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "item_16_21a9", + "target_id": "checksum_crc32", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32_66ce", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + }, + { + "source_id": "container_1", + "target_id": "item_16_21a9", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_8_9bd5", + "target_id": "item_8_0142", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "hmac_sha256", + "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-f6f4950d/solution/solve.sh b/tasks/agentescape-15-skeleton-f6f4950d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-f6f4950d/task.toml b/tasks/agentescape-15-skeleton-f6f4950d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d689a650019c29cf98414d71cfbf25c191a4b6f6 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "d8ab0f4baee09134f6aa18b76b2ab6fcc1a1395342f3b0850acc7ee6ce878446" +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-f6f4950d/tests/Dockerfile b/tasks/agentescape-15-skeleton-f6f4950d/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-f6f4950d/tests/expected.json b/tasks/agentescape-15-skeleton-f6f4950d/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..de533a75fcdd92580d1ea1f286c61dcda5af4afc --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "d8ab0f4baee09134f6aa18b76b2ab6fcc1a1395342f3b0850acc7ee6ce878446", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f6f4950d/tests/grade.py b/tasks/agentescape-15-skeleton-f6f4950d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/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-f6f4950d/tests/test.sh b/tasks/agentescape-15-skeleton-f6f4950d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f6f4950d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/environment/Dockerfile b/tasks/agentescape-15-skeleton-f8e0c35f/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-f8e0c35f/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/agent/cli.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-f8e0c35f/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d2edbceca8d030a7111f101b12cd51a40dd225c --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f-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-f8e0c35f/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ba61b3c6f55c7d81b4d8119c0f286dbc0a1b9075 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/scenario.json @@ -0,0 +1,942 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "graph_shortest_path", + "win_condition": { + "type": "tool_output", + "node_id": "graph_shortest_path", + "output_port": "path", + "output_type": "Text_Generic", + "description": "Execute Shortest Path Finder and get the output from port 'path'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_b42b", + "base64_encode", + "zip_unzip_file_c272", + "zip_unzip_file_5e1d", + "hex_encode", + "item_7", + "zip_unzip_file_2062" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_b42b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_c272": { + "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_5e1d": { + "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" + } + } + }, + "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": {} + }, + "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_2062": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Alpha_Start" + }, + "init_outputs": { + "path": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]", + "cost": "38475629102938475610" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_bundle_v1.xml" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "sales_records_2024.csv" + }, + "init_outputs": { + "rows": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + }, + "zip_unzip_file_b42b": { + "init_inputs": {}, + "init_outputs": { + "files": "server_logs_archive_b42b.txt" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "zip_unzip_file_c272": { + "init_inputs": {}, + "init_outputs": { + "files": "config_backup_c272.json" + } + }, + "zip_unzip_file_5e1d": { + "init_inputs": { + "password": "SecurePassword_5e1d!@" + }, + "init_outputs": { + "files": "user_profiles_5e1d.db" + } + }, + "hex_encode": { + "init_inputs": { + "text": "Please convert this plain text string into hexadecimal format." + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "magic_number = 42000\nprint(magic_number)" + } + }, + "zip_unzip_file_2062": { + "init_inputs": { + "zip_id": "encrypted_vault_2062.zip", + "password": "VaultAccessKey_2062" + }, + "init_outputs": { + "files": "blueprint_design_2062.cad" + } + } + }, + "intro_narrative": "The rain batters against the window of the precinct as you stare at the chaotic murder board. A notorious serial killer has struck again, leaving behind a convoluted trail of digital clues, locked safes, and cryptic messages. The Chief has given you until dawn to find the killer's escape route before they vanish forever. As the lead detective, you must navigate through recovered evidence, bypass complex security systems, and decipher the cryptic codes left behind. Time is ticking, and every piece of evidence connects to another. Can you piece together the puzzle and stop the killer's flight?", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_bundle_v1.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Alpha_Start" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38475629102938475610" + } + ], + "init": { + "inputs": { + "src": "Node_Alpha_Start" + }, + "outputs": { + "path": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]", + "cost": "38475629102938475610" + } + }, + "narrative": "This is the city map tracker used to find the killer's escape route. It requires inputs from the antique cipher wheel and the master evidence locker to plot the exact locations." + }, + { + "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": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 1150284437 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "narrative": "This is the antique cipher wheel left at the crime scene. It requires inputs from the police database terminal and the digital integrity scanner to align the gears 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "server_logs_archive_b42b.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_bundle_v1.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_bundle_v1.xml" + } + }, + "narrative": "This is the master evidence locker in the precinct. It requires inputs from the suspect's safe and the credit card validator to bypass the electronic locks." + }, + { + "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": "sales_records_2024.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Gis8TV5veoucDR4vOktcbQ==" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "42000\n" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + ], + "init": { + "inputs": { + "file_id": "sales_records_2024.csv" + }, + "outputs": { + "rows": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + }, + "narrative": "This is the police database terminal. It requires inputs from the forensic analysis computer and the suspect's pager to filter out the suspect's accomplices." + }, + { + "id": "zip_unzip_file_b42b", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_backup_c272.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "server_logs_archive_b42b.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "server_logs_archive_b42b.txt" + } + }, + "narrative": "This is the suspect's safe found hidden behind a painting. It requires inputs from the locked briefcase and the credit card validator to open." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "magic_number = 42000\nprint(magic_number)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "42000\n" + } + ], + "narrative": "This is the forensic analysis computer in the lab. It requires input from the torn diary page to run the extraction sequence." + }, + { + "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": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "narrative": "This is the credit card validator used to verify illicit transactions. It requires input from the antique cipher wheel to check the obscured numbers." + }, + { + "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": "server_logs_archive_b42b.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "This is the hidden compartment within the suspect's desk. It requires inputs from the suspect's safe and the antique cipher wheel to trigger the release mechanism." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "The suspect's pager, an old piece of tech displaying a strange series of characters. It seems to hold an encoded message used for covert communication." + }, + { + "id": "zip_unzip_file_c272", + "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": "user_profiles_5e1d.db" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_backup_c272.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_backup_c272.json" + } + }, + "narrative": "This is the locked briefcase recovered from the alley. It requires inputs from the credit card validator and the digital encrypted folder to bypass its dual authentication." + }, + { + "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": "506c6561736520636f6e76657274207468697320706c61696e207465787420737472696e6720696e746f2068657861646563696d616c20666f726d61742e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "448ff295" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1150284437 + } + ], + "narrative": "This is the digital integrity scanner. It requires input from the text conversion tool to verify the authenticity of the recovered data blocks." + }, + { + "id": "zip_unzip_file_5e1d", + "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": "blueprint_design_2062.cad" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword_5e1d!@" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "user_profiles_5e1d.db" + } + ], + "init": { + "inputs": { + "password": "SecurePassword_5e1d!@" + }, + "outputs": { + "files": "user_profiles_5e1d.db" + } + }, + "narrative": "This is the digital encrypted folder found on a seized hard drive. It requires input from the victim's cloud drive to decrypt the contents." + }, + { + "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": "Please convert this plain text string into hexadecimal format." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "506c6561736520636f6e76657274207468697320706c61696e207465787420737472696e6720696e746f2068657861646563696d616c20666f726d61742e" + } + ], + "init": { + "inputs": { + "text": "Please convert this plain text string into hexadecimal format." + }, + "outputs": {} + }, + "narrative": "A portable text conversion tool used by investigators to standardize raw text data into machine-readable formats." + }, + { + "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": "magic_number = 42000\nprint(magic_number)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "magic_number = 42000\nprint(magic_number)" + } + }, + "narrative": "A torn diary page found clutched in the victim's hand, covered in barely legible scribbles and strange code snippets." + }, + { + "id": "zip_unzip_file_2062", + "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_vault_2062.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "VaultAccessKey_2062" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "blueprint_design_2062.cad" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_vault_2062.zip", + "password": "VaultAccessKey_2062" + }, + "outputs": { + "files": "blueprint_design_2062.cad" + } + }, + "narrative": "The victim's cloud drive access terminal. It contains a wealth of personal files and archived communications that need to be reviewed." + } + ], + "edges": [ + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "csv_query", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_b42b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "where" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "zip_unzip_item", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "text_rotN", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "zip_unzip_file_b42b", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "text_rotN", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file_c272", + "target_id": "zip_unzip_file_b42b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_c272", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_5e1d", + "target_id": "zip_unzip_file_c272", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_b42b", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "hex_encode", + "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": "zip_unzip_file_2062", + "target_id": "zip_unzip_file_5e1d", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-f8e0c35f/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/instruction.md b/tasks/agentescape-15-skeleton-f8e0c35f/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/solution/oracle.py b/tasks/agentescape-15-skeleton-f8e0c35f/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/solution/scenario.json b/tasks/agentescape-15-skeleton-f8e0c35f/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..ba61b3c6f55c7d81b4d8119c0f286dbc0a1b9075 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/solution/scenario.json @@ -0,0 +1,942 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 19, + "win_node_id": "graph_shortest_path", + "win_condition": { + "type": "tool_output", + "node_id": "graph_shortest_path", + "output_port": "path", + "output_type": "Text_Generic", + "description": "Execute Shortest Path Finder and get the output from port 'path'" + }, + "source_init": { + "source_nodes": [ + "graph_shortest_path", + "zip_unzip_file", + "csv_query", + "zip_unzip_file_b42b", + "base64_encode", + "zip_unzip_file_c272", + "zip_unzip_file_5e1d", + "hex_encode", + "item_7", + "zip_unzip_file_2062" + ], + "by_node": { + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + }, + "zip_unzip_file_b42b": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "base64_encode": { + "node_name": "Base64 Encoder", + "node_type": "Tool", + "template_id": "base64_encode", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex bytes" + } + }, + "init_outputs": {} + }, + "zip_unzip_file_c272": { + "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_5e1d": { + "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" + } + } + }, + "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": {} + }, + "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_2062": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Alpha_Start" + }, + "init_outputs": { + "path": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]", + "cost": "38475629102938475610" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_data_bundle_v1.xml" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "sales_records_2024.csv" + }, + "init_outputs": { + "rows": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + }, + "zip_unzip_file_b42b": { + "init_inputs": {}, + "init_outputs": { + "files": "server_logs_archive_b42b.txt" + } + }, + "base64_encode": { + "init_inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "init_outputs": {} + }, + "zip_unzip_file_c272": { + "init_inputs": {}, + "init_outputs": { + "files": "config_backup_c272.json" + } + }, + "zip_unzip_file_5e1d": { + "init_inputs": { + "password": "SecurePassword_5e1d!@" + }, + "init_outputs": { + "files": "user_profiles_5e1d.db" + } + }, + "hex_encode": { + "init_inputs": { + "text": "Please convert this plain text string into hexadecimal format." + }, + "init_outputs": {} + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "magic_number = 42000\nprint(magic_number)" + } + }, + "zip_unzip_file_2062": { + "init_inputs": { + "zip_id": "encrypted_vault_2062.zip", + "password": "VaultAccessKey_2062" + }, + "init_outputs": { + "files": "blueprint_design_2062.cad" + } + } + }, + "intro_narrative": "The rain batters against the window of the precinct as you stare at the chaotic murder board. A notorious serial killer has struck again, leaving behind a convoluted trail of digital clues, locked safes, and cryptic messages. The Chief has given you until dawn to find the killer's escape route before they vanish forever. As the lead detective, you must navigate through recovered evidence, bypass complex security systems, and decipher the cryptic codes left behind. Time is ticking, and every piece of evidence connects to another. Can you piece together the puzzle and stop the killer's flight?", + "narrative_style": "detective" + }, + "nodes": [ + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "extracted_data_bundle_v1.xml" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Alpha_Start" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "38475629102938475610" + } + ], + "init": { + "inputs": { + "src": "Node_Alpha_Start" + }, + "outputs": { + "path": "[\"Node_Alpha_Start\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\", \"Node_Zeta_End\"]", + "cost": "38475629102938475610" + } + }, + "narrative": "This is the city map tracker used to find the killer's escape route. It requires inputs from the antique cipher wheel and the master evidence locker to plot the exact locations." + }, + { + "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": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + }, + { + "name": "n", + "type": "Big_Int", + "description": "Shift N", + "value": 1150284437 + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Rotated text", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "narrative": "This is the antique cipher wheel left at the crime scene. It requires inputs from the police database terminal and the digital integrity scanner to align the gears 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": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "server_logs_archive_b42b.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_data_bundle_v1.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_data_bundle_v1.xml" + } + }, + "narrative": "This is the master evidence locker in the precinct. It requires inputs from the suspect's safe and the credit card validator to bypass the electronic locks." + }, + { + "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": "sales_records_2024.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "Gis8TV5veoucDR4vOktcbQ==" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "42000\n" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + ], + "init": { + "inputs": { + "file_id": "sales_records_2024.csv" + }, + "outputs": { + "rows": "[{\"id\": 101, \"item\": \"Widget A\", \"price\": 19.99}, {\"id\": 102, \"item\": \"Widget B\", \"price\": 25.50}, {\"id\": 103, \"item\": \"Widget C\", \"price\": 9.99}]" + } + }, + "narrative": "This is the police database terminal. It requires inputs from the forensic analysis computer and the suspect's pager to filter out the suspect's accomplices." + }, + { + "id": "zip_unzip_file_b42b", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "config_backup_c272.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "server_logs_archive_b42b.txt" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "server_logs_archive_b42b.txt" + } + }, + "narrative": "This is the suspect's safe found hidden behind a painting. It requires inputs from the locked briefcase and the credit card validator to open." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "magic_number = 42000\nprint(magic_number)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "42000\n" + } + ], + "narrative": "This is the forensic analysis computer in the lab. It requires input from the torn diary page to run the extraction sequence." + }, + { + "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": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "narrative": "This is the credit card validator used to verify illicit transactions. It requires input from the antique cipher wheel to check the obscured numbers." + }, + { + "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": "server_logs_archive_b42b.txt" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip", + "value": "" + } + ], + "narrative": "This is the hidden compartment within the suspect's desk. It requires inputs from the suspect's safe and the antique cipher wheel to trigger the release mechanism." + }, + { + "id": "base64_encode", + "name": "Base64 Encoder", + "description": "Encode hex bytes to base64.", + "type": "Tool", + "template_id": "base64_encode", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex bytes", + "value": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + } + ], + "outputs": [ + { + "name": "b64", + "type": "Text_Generic", + "description": "Base64 string", + "value": "Gis8TV5veoucDR4vOktcbQ==" + } + ], + "init": { + "inputs": { + "hex": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" + }, + "outputs": {} + }, + "narrative": "The suspect's pager, an old piece of tech displaying a strange series of characters. It seems to hold an encoded message used for covert communication." + }, + { + "id": "zip_unzip_file_c272", + "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": "user_profiles_5e1d.db" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "[{\"lg\": 101, \"lwhp\": \"Zlgjhw D\", \"sulfh\": 19.99}, {\"lg\": 102, \"lwhp\": \"Zlgjhw E\", \"sulfh\": 25.50}, {\"lg\": 103, \"lwhp\": \"Zlgjhw F\", \"sulfh\": 9.99}]" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "config_backup_c272.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "config_backup_c272.json" + } + }, + "narrative": "This is the locked briefcase recovered from the alley. It requires inputs from the credit card validator and the digital encrypted folder to bypass its dual authentication." + }, + { + "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": "506c6561736520636f6e76657274207468697320706c61696e207465787420737472696e6720696e746f2068657861646563696d616c20666f726d61742e" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "448ff295" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1150284437 + } + ], + "narrative": "This is the digital integrity scanner. It requires input from the text conversion tool to verify the authenticity of the recovered data blocks." + }, + { + "id": "zip_unzip_file_5e1d", + "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": "blueprint_design_2062.cad" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword_5e1d!@" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "user_profiles_5e1d.db" + } + ], + "init": { + "inputs": { + "password": "SecurePassword_5e1d!@" + }, + "outputs": { + "files": "user_profiles_5e1d.db" + } + }, + "narrative": "This is the digital encrypted folder found on a seized hard drive. It requires input from the victim's cloud drive to decrypt the contents." + }, + { + "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": "Please convert this plain text string into hexadecimal format." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Encoded hex", + "value": "506c6561736520636f6e76657274207468697320706c61696e207465787420737472696e6720696e746f2068657861646563696d616c20666f726d61742e" + } + ], + "init": { + "inputs": { + "text": "Please convert this plain text string into hexadecimal format." + }, + "outputs": {} + }, + "narrative": "A portable text conversion tool used by investigators to standardize raw text data into machine-readable formats." + }, + { + "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": "magic_number = 42000\nprint(magic_number)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "magic_number = 42000\nprint(magic_number)" + } + }, + "narrative": "A torn diary page found clutched in the victim's hand, covered in barely legible scribbles and strange code snippets." + }, + { + "id": "zip_unzip_file_2062", + "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_vault_2062.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "VaultAccessKey_2062" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "blueprint_design_2062.cad" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_vault_2062.zip", + "password": "VaultAccessKey_2062" + }, + "outputs": { + "files": "blueprint_design_2062.cad" + } + }, + "narrative": "The victim's cloud drive access terminal. It contains a wealth of personal files and archived communications that need to be reviewed." + } + ], + "edges": [ + { + "source_id": "text_rotN", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "csv_query", + "target_id": "text_rotN", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "text" + }, + { + "source_id": "zip_unzip_file_b42b", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "where" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "zip_unzip_item", + "target_id": "zip_unzip_file", + "connection_type": "Item", + "source_port": "item", + "target_port": "trigger_item" + }, + { + "source_id": "text_rotN", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "number" + }, + { + "source_id": "zip_unzip_file_b42b", + "target_id": "zip_unzip_item", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "text_rotN", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "base64_encode", + "target_id": "csv_query", + "connection_type": "Text_Generic", + "source_port": "b64", + "target_port": "select" + }, + { + "source_id": "zip_unzip_file_c272", + "target_id": "zip_unzip_file_b42b", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_c272", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "checksum_crc32", + "target_id": "text_rotN", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "n" + }, + { + "source_id": "zip_unzip_file_5e1d", + "target_id": "zip_unzip_file_c272", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "luhn_check", + "target_id": "zip_unzip_file_b42b", + "connection_type": "Text_Generic", + "source_port": "valid", + "target_port": "password" + }, + { + "source_id": "hex_encode", + "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": "zip_unzip_file_2062", + "target_id": "zip_unzip_file_5e1d", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/solution/solve.sh b/tasks/agentescape-15-skeleton-f8e0c35f/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/task.toml b/tasks/agentescape-15-skeleton-f8e0c35f/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4656d953fbe195849603abdc7448fedab13037b9 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "d4d78e004936cf6157b372d16ce2a35cf9bd39a063702de8f9fc1785a8012f97" +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-f8e0c35f/tests/Dockerfile b/tasks/agentescape-15-skeleton-f8e0c35f/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/tests/expected.json b/tasks/agentescape-15-skeleton-f8e0c35f/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..f0c8ea2c6d3bd5792b7dcfe7aaad80e29df8c3e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "d4d78e004936cf6157b372d16ce2a35cf9bd39a063702de8f9fc1785a8012f97", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-f8e0c35f/tests/grade.py b/tasks/agentescape-15-skeleton-f8e0c35f/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/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-f8e0c35f/tests/test.sh b/tasks/agentescape-15-skeleton-f8e0c35f/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-f8e0c35f/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-15-skeleton-fab2f6a8/environment/Dockerfile b/tasks/agentescape-15-skeleton-fab2f6a8/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/agent/Dockerfile b/tasks/agentescape-15-skeleton-fab2f6a8/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/agent/cli.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/docker-compose.yaml b/tasks/agentescape-15-skeleton-fab2f6a8/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4b40e117ae5bbc71aba205a2050625015151548 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8-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-fab2f6a8/environment/puzzle/Dockerfile b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/child.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/export.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/requirements.txt b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/scenario.json b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f5dd1136f035f2fc9cfeb89884c549a35cc02815 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/scenario.json @@ -0,0 +1,963 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "item_12", + "win_condition": { + "type": "item_content", + "node_id": "item_12", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_12", + "terminal_2", + "calc_modexp", + "calc_inv_mod", + "calc_inv_mod_cacc", + "calc_modexp_b336", + "calc_inv_mod_6328", + "terminal_2_6698", + "container_1", + "item_1", + "item_3" + ], + "by_node": { + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "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_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": {} + }, + "calc_inv_mod_cacc": { + "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_b336": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_6328": { + "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_6698": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + } + } + }, + "initial_values": { + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "4a7b9c2d1e8f0a3b" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial execution pending inputs.", + "hex_result": "00000000deadbeef" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "17" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "982374651029384756102" + }, + "init_outputs": {} + }, + "calc_inv_mod_cacc": { + "init_inputs": { + "mod": "65537" + }, + "init_outputs": {} + }, + "calc_modexp_b336": { + "init_inputs": { + "base": "23" + }, + "init_outputs": {} + }, + "calc_inv_mod_6328": { + "init_inputs": { + "mod": "10007" + }, + "init_outputs": {} + }, + "terminal_2_6698": { + "init_inputs": { + "num1": "192837465564738291023", + "num2": "384756291029384756123" + }, + "init_outputs": { + "text_result": "Calculation pending.", + "hex_result": "aabbccddeeff0011" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "f1a2b3c4d5e6f708" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "56473829101928374655" + } + }, + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "11223344556677889900aabb" + } + } + }, + "intro_narrative": "You are an apprentice wizard trapped in the forgotten Spire of Eldoria. The legendary Archmage's Crystal, a source of unimaginable power, is sealed within these ethereal walls. To claim it and earn the title of Sorcerer Supreme, you must navigate a complex web of arcane devices and enchanted relics left behind by the ancient masters. The spire is filled with intertwined magical currents. You must uncover the secrets of the artifacts, discover how their powers feed into one another, and master the flow of magical energy to break the final seal before the spire fades into the astral plane forever.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "4a7b9c2d1e8f0a3b" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "4a7b9c2d1e8f0a3b" + } + }, + "narrative": "This is The Archmage's Crystal. A radiant gemstone pulsing with immense magical energy. Capturing its inner light is your ultimate goal." + }, + { + "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": "707297588831208709373" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 2300213316 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial execution pending inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "00000000deadbeef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial execution pending inputs.", + "hex_result": "00000000deadbeef" + } + }, + "narrative": "This is The Astral Observatory. It requires inputs from both The Aetheric Crucible and The Spirit Scaler to align the celestial bodies." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3473" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982374651029384756102" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "707297588831208709373" + } + ], + "init": { + "inputs": { + "base": "17" + }, + "outputs": {} + }, + "narrative": "This is The Aetheric Crucible. It requires inputs from both The Moonstone Reverser and The Sunflare Forge to channel its potent magic." + }, + { + "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": "982374651029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "6632" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "982374651029384756102" + } + ], + "init": { + "inputs": { + "a": "982374651029384756102" + }, + "outputs": {} + }, + "narrative": "This is The Moonstone Reverser. It requires input from The Starlight Weaver to reflect the magical currents." + }, + { + "id": "calc_modexp_db29", + "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": "1487" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2300213316 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "6632" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "3473" + } + ], + "narrative": "This is The Sunflare Forge. It requires inputs from The Starlight Weaver, The Void Catalyst, and The Spirit Scaler to ignite the sacred flames." + }, + { + "id": "calc_inv_mod_cacc", + "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": "8370" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "6632" + } + ], + "init": { + "inputs": { + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "This is The Starlight Weaver. It requires input from The Abyssal Mirror to untangle the constellations." + }, + { + "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 The Chronomancer's Hourglass. An ancient hourglass where the shimmering sands flow upwards, defying the natural laws of time." + }, + { + "id": "calc_modexp_b336", + "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": "23" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "56473829101928374655" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "8370" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1487" + } + ], + "init": { + "inputs": { + "base": "23" + }, + "outputs": {} + }, + "narrative": "This is The Void Catalyst. It requires inputs from both The Abyssal Mirror and The Flame Scroll to bridge the magical rift." + }, + { + "id": "calc_inv_mod_6328", + "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": 2552293572 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "10007" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "8370" + } + ], + "init": { + "inputs": { + "mod": "10007" + }, + "outputs": {} + }, + "narrative": "This is The Abyssal Mirror. It requires input from The Enchanted Balancer to reveal the hidden depths of the dark waters." + }, + { + "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": "aabbccddeeff0011" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "891a7844" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2300213316 + } + ], + "narrative": "This is The Spirit Scaler. It requires input from The Runestone Pedestal to weigh the gathered soul fragments." + }, + { + "id": "terminal_2_6698", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "192837465564738291023" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "384756291029384756123" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff0011" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465564738291023", + "num2": "384756291029384756123" + }, + "outputs": { + "text_result": "Calculation pending.", + "hex_result": "aabbccddeeff0011" + } + }, + "narrative": "This is The Runestone Pedestal. A carved stone pedestal covered in glowing, forgotten runes." + }, + { + "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": "f1a2b3c4d5e6f708" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "f1a2b3c4d5e6f708" + }, + "outputs": {} + }, + "narrative": "This is The Dragonbone Chest. A heavy container crafted from the remains of an ancient drake, bound by mystical locks." + }, + { + "id": "checksum_crc32_510a", + "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": "11223344556677889900aabb" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9820e8c4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2552293572 + } + ], + "narrative": "This is The Enchanted Balancer. It requires input from The Frost Tablet to harmonize the magical equilibrium." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "56473829101928374655" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "56473829101928374655" + } + }, + "narrative": "This is The Flame Scroll. A delicate parchment completely engulfed in a magical, unconsuming fire." + }, + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "11223344556677889900aabb" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "11223344556677889900aabb" + } + }, + "narrative": "This is The Frost Tablet. A heavy slab of ever-ice etched with glowing blue symbols." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "item_12", + "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": "num1" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_db29", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_cacc", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_cacc", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_cacc", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_b336", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod_6328", + "target_id": "calc_modexp_b336", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_2_6698", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2_6698", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod_6328", + "target_id": "calc_inv_mod_cacc", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "container_1", + "target_id": "calc_inv_mod_6328", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_510a", + "target_id": "calc_inv_mod_6328", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_b336", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "exp" + }, + { + "source_id": "item_3", + "target_id": "checksum_crc32_510a", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/service.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/upstream/models.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/upstream/server.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/upstream/simulator.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/worker.Dockerfile b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/environment/puzzle/worker.py b/tasks/agentescape-15-skeleton-fab2f6a8/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/instruction.md b/tasks/agentescape-15-skeleton-fab2f6a8/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/solution/oracle.py b/tasks/agentescape-15-skeleton-fab2f6a8/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8/solution/scenario.json b/tasks/agentescape-15-skeleton-fab2f6a8/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..f5dd1136f035f2fc9cfeb89884c549a35cc02815 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/solution/scenario.json @@ -0,0 +1,963 @@ +{ + "metadata": { + "total_nodes": 15, + "total_edges": 18, + "win_node_id": "item_12", + "win_condition": { + "type": "item_content", + "node_id": "item_12", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_12", + "terminal_2", + "calc_modexp", + "calc_inv_mod", + "calc_inv_mod_cacc", + "calc_modexp_b336", + "calc_inv_mod_6328", + "terminal_2_6698", + "container_1", + "item_1", + "item_3" + ], + "by_node": { + "item_12": { + "node_name": "", + "node_type": "Item", + "template_id": "item_12", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "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_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": {} + }, + "calc_inv_mod_cacc": { + "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_b336": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + } + }, + "init_outputs": {} + }, + "calc_inv_mod_6328": { + "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_6698": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "num1": { + "type": "Big_Int", + "description": "First Number" + }, + "num2": { + "type": "Big_Int", + "description": "Second Number" + } + }, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + } + } + }, + "container_1": { + "node_name": "", + "node_type": "Item", + "template_id": "container_1", + "init_inputs": { + "fingerprint_input": { + "type": "Hex_String", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + }, + "item_1": { + "node_name": "", + "node_type": "Item", + "template_id": "item_1", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Big_Int", + "description": "The number" + } + } + }, + "item_3": { + "node_name": "", + "node_type": "Item", + "template_id": "item_3", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String", + "description": "The hex code" + } + } + } + } + }, + "initial_values": { + "item_12": { + "init_inputs": {}, + "init_outputs": { + "content": "4a7b9c2d1e8f0a3b" + } + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Partial execution pending inputs.", + "hex_result": "00000000deadbeef" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "17" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "982374651029384756102" + }, + "init_outputs": {} + }, + "calc_inv_mod_cacc": { + "init_inputs": { + "mod": "65537" + }, + "init_outputs": {} + }, + "calc_modexp_b336": { + "init_inputs": { + "base": "23" + }, + "init_outputs": {} + }, + "calc_inv_mod_6328": { + "init_inputs": { + "mod": "10007" + }, + "init_outputs": {} + }, + "terminal_2_6698": { + "init_inputs": { + "num1": "192837465564738291023", + "num2": "384756291029384756123" + }, + "init_outputs": { + "text_result": "Calculation pending.", + "hex_result": "aabbccddeeff0011" + } + }, + "container_1": { + "init_inputs": { + "fingerprint_input": "f1a2b3c4d5e6f708" + }, + "init_outputs": {} + }, + "item_1": { + "init_inputs": {}, + "init_outputs": { + "content": "56473829101928374655" + } + }, + "item_3": { + "init_inputs": {}, + "init_outputs": { + "content": "11223344556677889900aabb" + } + } + }, + "intro_narrative": "You are an apprentice wizard trapped in the forgotten Spire of Eldoria. The legendary Archmage's Crystal, a source of unimaginable power, is sealed within these ethereal walls. To claim it and earn the title of Sorcerer Supreme, you must navigate a complex web of arcane devices and enchanted relics left behind by the ancient masters. The spire is filled with intertwined magical currents. You must uncover the secrets of the artifacts, discover how their powers feed into one another, and master the flow of magical energy to break the final seal before the spire fades into the astral plane forever.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "item_12", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_12", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "4a7b9c2d1e8f0a3b" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "4a7b9c2d1e8f0a3b" + } + }, + "narrative": "This is The Archmage's Crystal. A radiant gemstone pulsing with immense magical energy. Capturing its inner light is your ultimate goal." + }, + { + "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": "707297588831208709373" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": 2300213316 + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Partial execution pending inputs." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "00000000deadbeef" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Partial execution pending inputs.", + "hex_result": "00000000deadbeef" + } + }, + "narrative": "This is The Astral Observatory. It requires inputs from both The Aetheric Crucible and The Spirit Scaler to align the celestial bodies." + }, + { + "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": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "17" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3473" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "982374651029384756102" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "707297588831208709373" + } + ], + "init": { + "inputs": { + "base": "17" + }, + "outputs": {} + }, + "narrative": "This is The Aetheric Crucible. It requires inputs from both The Moonstone Reverser and The Sunflare Forge to channel its potent magic." + }, + { + "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": "982374651029384756102" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "6632" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "982374651029384756102" + } + ], + "init": { + "inputs": { + "a": "982374651029384756102" + }, + "outputs": {} + }, + "narrative": "This is The Moonstone Reverser. It requires input from The Starlight Weaver to reflect the magical currents." + }, + { + "id": "calc_modexp_db29", + "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": "1487" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2300213316 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "6632" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "3473" + } + ], + "narrative": "This is The Sunflare Forge. It requires inputs from The Starlight Weaver, The Void Catalyst, and The Spirit Scaler to ignite the sacred flames." + }, + { + "id": "calc_inv_mod_cacc", + "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": "8370" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "65537" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "6632" + } + ], + "init": { + "inputs": { + "mod": "65537" + }, + "outputs": {} + }, + "narrative": "This is The Starlight Weaver. It requires input from The Abyssal Mirror to untangle the constellations." + }, + { + "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 The Chronomancer's Hourglass. An ancient hourglass where the shimmering sands flow upwards, defying the natural laws of time." + }, + { + "id": "calc_modexp_b336", + "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": "23" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "56473829101928374655" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "8370" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "1487" + } + ], + "init": { + "inputs": { + "base": "23" + }, + "outputs": {} + }, + "narrative": "This is The Void Catalyst. It requires inputs from both The Abyssal Mirror and The Flame Scroll to bridge the magical rift." + }, + { + "id": "calc_inv_mod_6328", + "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": 2552293572 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "10007" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "8370" + } + ], + "init": { + "inputs": { + "mod": "10007" + }, + "outputs": {} + }, + "narrative": "This is The Abyssal Mirror. It requires input from The Enchanted Balancer to reveal the hidden depths of the dark waters." + }, + { + "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": "aabbccddeeff0011" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "891a7844" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2300213316 + } + ], + "narrative": "This is The Spirit Scaler. It requires input from The Runestone Pedestal to weigh the gathered soul fragments." + }, + { + "id": "terminal_2_6698", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "192837465564738291023" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "384756291029384756123" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "aabbccddeeff0011" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "192837465564738291023", + "num2": "384756291029384756123" + }, + "outputs": { + "text_result": "Calculation pending.", + "hex_result": "aabbccddeeff0011" + } + }, + "narrative": "This is The Runestone Pedestal. A carved stone pedestal covered in glowing, forgotten runes." + }, + { + "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": "f1a2b3c4d5e6f708" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "f1a2b3c4d5e6f708" + }, + "outputs": {} + }, + "narrative": "This is The Dragonbone Chest. A heavy container crafted from the remains of an ancient drake, bound by mystical locks." + }, + { + "id": "checksum_crc32_510a", + "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": "11223344556677889900aabb" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "9820e8c4" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2552293572 + } + ], + "narrative": "This is The Enchanted Balancer. It requires input from The Frost Tablet to harmonize the magical equilibrium." + }, + { + "id": "item_1", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Big_Int", + "description": "The number", + "value": "56473829101928374655" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "56473829101928374655" + } + }, + "narrative": "This is The Flame Scroll. A delicate parchment completely engulfed in a magical, unconsuming fire." + }, + { + "id": "item_3", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_3", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String", + "description": "The hex code", + "value": "11223344556677889900aabb" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "11223344556677889900aabb" + } + }, + "narrative": "This is The Frost Tablet. A heavy slab of ever-ice etched with glowing blue symbols." + } + ], + "edges": [ + { + "source_id": "terminal_2", + "target_id": "item_12", + "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": "num1" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_db29", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod_cacc", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_cacc", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_cacc", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp_b336", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "calc_inv_mod_6328", + "target_id": "calc_modexp_b336", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_db29", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "terminal_2_6698", + "target_id": "checksum_crc32", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_2_6698", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "calc_inv_mod_6328", + "target_id": "calc_inv_mod_cacc", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "container_1", + "target_id": "calc_inv_mod_6328", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "checksum_crc32_510a", + "target_id": "calc_inv_mod_6328", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "item_1", + "target_id": "calc_modexp_b336", + "connection_type": "Big_Int", + "source_port": "content", + "target_port": "exp" + }, + { + "source_id": "item_3", + "target_id": "checksum_crc32_510a", + "connection_type": "Hex_String", + "source_port": "content", + "target_port": "hex" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-15-skeleton-fab2f6a8/solution/solve.sh b/tasks/agentescape-15-skeleton-fab2f6a8/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-15-skeleton-fab2f6a8/task.toml b/tasks/agentescape-15-skeleton-fab2f6a8/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a40f517890ee6e0a6b91bdffa32141822048cf36 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/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-fab2f6a8" +version = "0.1.0" + +[metadata] +difficulty = 15 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "e7ebf25f876e057a989aaf63caf142c37342fe202cd8b7571a5e66fd28f693d6" +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-fab2f6a8/tests/Dockerfile b/tasks/agentescape-15-skeleton-fab2f6a8/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-15-skeleton-fab2f6a8/tests/expected.json b/tasks/agentescape-15-skeleton-fab2f6a8/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..400a6a58ccf6c2a1bc8bbc9e1b5a9d8602a313a0 --- /dev/null +++ b/tasks/agentescape-15-skeleton-fab2f6a8/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "e7ebf25f876e057a989aaf63caf142c37342fe202cd8b7571a5e66fd28f693d6", "max_actions": 500} \ No newline at end of file