diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/instruction.md b/tasks/agentescape-10-skeleton-2a4fc5a2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/solution/oracle.py b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/solution/scenario.json b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..d843be46c5ecdbde5b06ed0fae21431a25199204 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/scenario.json @@ -0,0 +1,577 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "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", + "zlib_deflate", + "hmac_sha256", + "text_bidi_sanitize", + "hmac_sha256_5b00" + ], + "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" + } + } + }, + "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": {} + }, + "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": {} + }, + "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": {} + }, + "hmac_sha256_5b00": { + "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": { + "container_1": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "flAg@da9udahnxiandjnanjinjxinbnuxbamlopqe" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "System diagnostic: Primary command processor is currently online.", + "hex_output": "a4d8f2b1c0e39576482d1b9c5f8e0a3b" + } + }, + "zlib_deflate": { + "init_inputs": { + "text": "Compressing local telemetry logs for archival verification purposes." + }, + "init_outputs": {} + }, + "hmac_sha256": { + "init_inputs": { + "hex_key": "4c2d8a1b6e9f03d57c2a4b8e1f9d6c3a", + "text": "Authentication request for secure shell session ID 8842." + }, + "init_outputs": {} + }, + "text_bidi_sanitize": { + "init_inputs": { + "text": "Incoming data stream includes nested directional formatting controls." + }, + "init_outputs": {} + }, + "hmac_sha256_5b00": { + "init_inputs": { + "hex_key": "9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b", + "text": "Integrity checksum for the secondary filesystem mount point." + }, + "init_outputs": {} + } + }, + "intro_narrative": "You have breached the server room of Project Chimera, a clandestine black-ops data center. The air is freezing, kept supercooled for the racks of humming mainframes that surround you. Red emergency lights pulse rhythmically, casting long, shifting shadows. Your objective is locked inside the Primary Vault, a heavy bio-metric container in the center of the room. The facility's security protocols have been scrambled, leaving a trail of disconnected tools and locked containers. You must navigate the fragmented system, utilizing various encryption modules and terminals to bypass the safeguards. Time is running out before the automated security countermeasures purge the room of oxygen. You need to link the correct data streams to override the locks.", + "narrative_style": "techno_thriller" + }, + "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": "789c0dc9d109c0300805c0559ca04b74129197543031a80d74fbe6f3b8dbc70a64eaec642e6c54300c547cc73da97910873cbacf6d8436152ef549eb8de589bc7e8a281a49" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "flAg@da9udahnxiandjnanjinjxinbnuxbamlopqe" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "flAg@da9udahnxiandjnanjinjxinbnuxbamlopqe" + } + }, + "narrative": "This is the Primary Vault, reinforced with titanium alloy. It requires a compressed data stream from the Data Compressor to verify the unlock sequence." + }, + { + "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": "Incoming data stream includes nested directional formatting controls." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 3330164036 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "System diagnostic: Primary command processor is currently online." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a4d8f2b1c0e39576482d1b9c5f8e0a3b" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "System diagnostic: Primary command processor is currently online.", + "hex_output": "a4d8f2b1c0e39576482d1b9c5f8e0a3b" + } + }, + "narrative": "This is the Fabricator Console, used to manufacture physical keys. It requires synchronized inputs from both the Integrity Checker and the Command Parser to initiate the fabrication process." + }, + { + "id": "zlib_deflate", + "name": "Zlib Deflate", + "description": "Deflate text to zlib bytes (hex).", + "type": "Tool", + "template_id": "zlib_deflate", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text to compress", + "value": "Compressing local telemetry logs for archival verification purposes." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Compressed hex", + "value": "789c0dc9d109c0300805c0559ca04b74129197543031a80d74fbe6f3b8dbc70a64eaec642e6c54300c547cc73da97910873cbacf6d8436152ef549eb8de589bc7e8a281a49" + } + ], + "init": { + "inputs": { + "text": "Compressing local telemetry logs for archival verification purposes." + }, + "outputs": {} + }, + "narrative": "This is the Data Compressor. It condenses raw text strings into high-density packet streams." + }, + { + "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": "54f8576ad81d1e9bb5bf72918dd8a3720a65be608f28a27444049f8c234de5c1" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "c67e4544" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3330164036 + } + ], + "narrative": "This is the Integrity Checker. It requires the cryptographic signature from Authentication Module Beta to validate the system status." + }, + { + "id": "hmac_sha256", + "name": "HMAC-SHA256 Calculator", + "description": "HMAC-SHA256(text) with hex key.", + "type": "Tool", + "template_id": "hmac_sha256", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "hex_key", + "type": "Hex_String", + "description": "Hex key", + "value": "4c2d8a1b6e9f03d57c2a4b8e1f9d6c3a" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Authentication request for secure shell session ID 8842." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "54f8576ad81d1e9bb5bf72918dd8a3720a65be608f28a27444049f8c234de5c1" + } + ], + "init": { + "inputs": { + "hex_key": "4c2d8a1b6e9f03d57c2a4b8e1f9d6c3a", + "text": "Authentication request for secure shell session ID 8842." + }, + "outputs": {} + }, + "narrative": "This is Authentication Module Beta. It generates high-level security hashes." + }, + { + "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": "12c5c8c3cc403769f1abfd69777c4abe569177cb066ea1877c2ca6b8f4588887" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Secure Cache, a small lockbox bolted to the floor. It requires a specific hash code from Authentication Module Alpha to release its latch." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "Incoming data stream includes nested directional formatting controls." + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "Incoming data stream includes nested directional formatting controls." + } + ], + "init": { + "inputs": { + "text": "Incoming data stream includes nested directional formatting controls." + }, + "outputs": {} + }, + "narrative": "This is the Command Parser. It strips dangerous formatting characters from text inputs." + }, + { + "id": "hmac_sha256_5b00", + "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": "9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text message", + "value": "Integrity checksum for the secondary filesystem mount point." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "HMAC Hex digest", + "value": "12c5c8c3cc403769f1abfd69777c4abe569177cb066ea1877c2ca6b8f4588887" + } + ], + "init": { + "inputs": { + "hex_key": "9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b", + "text": "Integrity checksum for the secondary filesystem mount point." + }, + "outputs": {} + }, + "narrative": "This is Authentication Module Alpha. It processes keys to generate authorization codes." + }, + { + "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 Administrator's ID Badge found on a desk." + }, + { + "id": "item_8_890e", + "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 Maintenance Keycard dropped near the rack." + } + ], + "edges": [ + { + "source_id": "terminal_1", + "target_id": "container_1", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "source_tool" + }, + { + "source_id": "zlib_deflate", + "target_id": "container_1", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "slot_b" + }, + { + "source_id": "hmac_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "container_2", + "target_id": "hmac_sha256", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "trigger_item" + }, + { + "source_id": "text_bidi_sanitize", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "slot_a" + }, + { + "source_id": "hmac_sha256_5b00", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_890e", + "target_id": "text_bidi_sanitize", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/solution/solve.sh b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/task.toml b/tasks/agentescape-10-skeleton-2a4fc5a2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..491d163d851d42b556e9924d7fa4280a97740e1d --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-2a4fc5a2" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "b14005b246f3e7fb70c1f55c9efb600fad2d01c0ec8a98f63d5fcc149627d78a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/tests/Dockerfile b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/tests/expected.json b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..998a0d95d3d06014ca4b29c46942f742bab57f51 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "b14005b246f3e7fb70c1f55c9efb600fad2d01c0ec8a98f63d5fcc149627d78a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/tests/grade.py b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-2a4fc5a2/tests/test.sh b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2a4fc5a2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/Dockerfile b/tasks/agentescape-10-skeleton-2e8147dc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/cli.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-2e8147dc/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..060439948a17b4d69e812b36ecb1a63e76123143 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-2e8147dc-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b09a8dff59b5090b37662781e697cdf0dffe0dc6 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/scenario.json @@ -0,0 +1,617 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "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", + "calc_gcd", + "code_py_exec", + "calc_modexp", + "calc_gcd_e63a", + "checksum_crc32", + "calc_inv_mod" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "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_gcd_e63a": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "918273645091827364501234" + }, + "init_outputs": {} + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Execution started')" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "5" + }, + "init_outputs": {} + }, + "calc_gcd_e63a": { + "init_inputs": { + "b": "102938475610293847561029" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "09f911029d74e35bd84156c5635688c0" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "675849302182736450918273", + "mod": "104729" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the dimly lit office of Arthur Penhaligon, a private investigator who vanished without a trace exactly one week ago. The air is thick with the smell of stale tobacco and old paper. The door has firmly locked behind you, sealing you inside this paranoid man's sanctuary. Scattered across the mahogany desk and hidden in the shadows are various bizarre cryptographic devices, mechanical rings, and an ominous master terminal blinking in the center of the room. Penhaligon was on the verge of uncovering a massive conspiracy, and he hid his final conclusion behind layers of complex, interlocking puzzles. Your objective is clear: navigate his convoluted web of clues, decipher the hidden message, and unlock the master terminal to escape with the truth. The clock is ticking, and whoever took Arthur might be coming back.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Execution started\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "narrative": "This is the master terminal. It requires inputs from both the final cypher disk and the detective's old personal computer to activate." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "918273645091827364501234" + } + ], + "init": { + "inputs": { + "b": "918273645091827364501234" + }, + "outputs": {} + }, + "narrative": "This is the final cypher disk. It requires input from the modified Enigma machine." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Execution started')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Execution started\n" + } + ], + "init": { + "inputs": { + "code": "print('Execution started')" + }, + "outputs": {} + }, + "narrative": "The detective's old personal computer, seemingly ready to run some custom scripts." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A small hidden cassette tape wrapped in a torn evidence label." + }, + { + "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": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "5" + }, + "outputs": {} + }, + "narrative": "A modified Enigma machine. It requires inputs from both the first decoder ring and the second decoder ring." + }, + { + "id": "item_8_88bb", + "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 heavy, locked filing cabinet holding sensitive case materials." + }, + { + "id": "calc_gcd_e63a", + "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": "16878" + }, + { + "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 first decoder ring. It requires input from the cryptographic book to align." + }, + { + "id": "calc_gcd_0529", + "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": 3790315201 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the second decoder ring. It requires inputs from both the first decoder ring and the evidence scanner." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "09f911029d74e35bd84156c5635688c0" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e1eb9ec1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3790315201 + } + ], + "init": { + "inputs": { + "hex": "09f911029d74e35bd84156c5635688c0" + }, + "outputs": {} + }, + "narrative": "A dusty evidence scanner used for digitizing files." + }, + { + "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": "675849302182736450918273" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "16878" + } + ], + "init": { + "inputs": { + "a": "675849302182736450918273", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "An old cryptographic book filled with handwritten notes." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "code_py_exec", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8_88bb", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_e63a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_gcd_0529", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_e63a", + "target_id": "calc_gcd_0529", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_0529", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd_e63a", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-2e8147dc/instruction.md b/tasks/agentescape-10-skeleton-2e8147dc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-2e8147dc/solution/oracle.py b/tasks/agentescape-10-skeleton-2e8147dc/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-2e8147dc/solution/scenario.json b/tasks/agentescape-10-skeleton-2e8147dc/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..b09a8dff59b5090b37662781e697cdf0dffe0dc6 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/solution/scenario.json @@ -0,0 +1,617 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "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", + "calc_gcd", + "code_py_exec", + "calc_modexp", + "calc_gcd_e63a", + "checksum_crc32", + "calc_inv_mod" + ], + "by_node": { + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + }, + "item_dispenser": { + "type": "Item", + "description": "Item output when both slots are provided" + } + } + }, + "calc_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "code_py_exec": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "init_outputs": {} + }, + "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_gcd_e63a": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "b": { + "type": "Big_Int", + "description": "Second integer" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "node_name": "BigInt Modular Inverse", + "node_type": "Tool", + "template_id": "calc_inv_mod", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "Integer a" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "calc_gcd": { + "init_inputs": { + "b": "918273645091827364501234" + }, + "init_outputs": {} + }, + "code_py_exec": { + "init_inputs": { + "code": "print('Execution started')" + }, + "init_outputs": {} + }, + "calc_modexp": { + "init_inputs": { + "base": "5" + }, + "init_outputs": {} + }, + "calc_gcd_e63a": { + "init_inputs": { + "b": "102938475610293847561029" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "09f911029d74e35bd84156c5635688c0" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "a": "675849302182736450918273", + "mod": "104729" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You stand in the dimly lit office of Arthur Penhaligon, a private investigator who vanished without a trace exactly one week ago. The air is thick with the smell of stale tobacco and old paper. The door has firmly locked behind you, sealing you inside this paranoid man's sanctuary. Scattered across the mahogany desk and hidden in the shadows are various bizarre cryptographic devices, mechanical rings, and an ominous master terminal blinking in the center of the room. Penhaligon was on the verge of uncovering a massive conspiracy, and he hid his final conclusion behind layers of complex, interlocking puzzles. Your objective is clear: navigate his convoluted web of clues, decipher the hidden message, and unlock the master terminal to escape with the truth. The clock is ticking, and whoever took Arthur might be coming back.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Execution started\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "LASCIATE_OGNE_SPERANZA_VOI_CHINTRATE", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "item_dispenser": "TO_BE_OR_NOT_TO_BE_THAT_IS_THE_ANSWER" + } + }, + "narrative": "This is the master terminal. It requires inputs from both the final cypher disk and the detective's old personal computer to activate." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "0" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "918273645091827364501234" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "918273645091827364501234" + } + ], + "init": { + "inputs": { + "b": "918273645091827364501234" + }, + "outputs": {} + }, + "narrative": "This is the final cypher disk. It requires input from the modified Enigma machine." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print('Execution started')" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "Execution started\n" + } + ], + "init": { + "inputs": { + "code": "print('Execution started')" + }, + "outputs": {} + }, + "narrative": "The detective's old personal computer, seemingly ready to run some custom scripts." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A small hidden cassette tape wrapped in a torn evidence label." + }, + { + "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": "5" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "3" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "0" + } + ], + "init": { + "inputs": { + "base": "5" + }, + "outputs": {} + }, + "narrative": "A modified Enigma machine. It requires inputs from both the first decoder ring and the second decoder ring." + }, + { + "id": "item_8_88bb", + "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 heavy, locked filing cabinet holding sensitive case materials." + }, + { + "id": "calc_gcd_e63a", + "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": "16878" + }, + { + "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 first decoder ring. It requires input from the cryptographic book to align." + }, + { + "id": "calc_gcd_0529", + "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": 3790315201 + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "3" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "narrative": "This is the second decoder ring. It requires inputs from both the first decoder ring and the evidence scanner." + }, + { + "id": "checksum_crc32", + "name": "CRC32 Checksum", + "description": "CRC32 over hex bytes.", + "type": "Tool", + "template_id": "checksum_crc32", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "Hex data", + "value": "09f911029d74e35bd84156c5635688c0" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "e1eb9ec1" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 3790315201 + } + ], + "init": { + "inputs": { + "hex": "09f911029d74e35bd84156c5635688c0" + }, + "outputs": {} + }, + "narrative": "A dusty evidence scanner used for digitizing files." + }, + { + "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": "675849302182736450918273" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "16878" + } + ], + "init": { + "inputs": { + "a": "675849302182736450918273", + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "An old cryptographic book filled with handwritten notes." + } + ], + "edges": [ + { + "source_id": "calc_gcd", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "slot_b" + }, + { + "source_id": "code_py_exec", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_8_88bb", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "calc_gcd_e63a", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "exp" + }, + { + "source_id": "calc_gcd_0529", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_gcd_e63a", + "target_id": "calc_gcd_0529", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd_0529", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_gcd_e63a", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2e8147dc/solution/solve.sh b/tasks/agentescape-10-skeleton-2e8147dc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-2e8147dc/task.toml b/tasks/agentescape-10-skeleton-2e8147dc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1059299931fd7394f0a53b0a68ad7e1f1c03617 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-2e8147dc" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "21a6c59765130c6de9aa34a03eb5ccd9fb57685443a7efb8bc67aac1b26b5c8a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-2e8147dc/tests/Dockerfile b/tasks/agentescape-10-skeleton-2e8147dc/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-2e8147dc/tests/expected.json b/tasks/agentescape-10-skeleton-2e8147dc/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..9efb231f06ea0e1432fa1e9a5712622bae5a2b6d --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "21a6c59765130c6de9aa34a03eb5ccd9fb57685443a7efb8bc67aac1b26b5c8a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-2e8147dc/tests/grade.py b/tasks/agentescape-10-skeleton-2e8147dc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-2e8147dc/tests/test.sh b/tasks/agentescape-10-skeleton-2e8147dc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-2e8147dc/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/Dockerfile b/tasks/agentescape-10-skeleton-310eae83/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-310eae83/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/agent/cli.py b/tasks/agentescape-10-skeleton-310eae83/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-310eae83/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a60b19537615bae7800bef41d655e23630e3761e --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-310eae83-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..50191ee805fc7a2d5c4d8e1f3fb653703b1e3c01 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/scenario.json @@ -0,0 +1,596 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "hash_md5", + "terminal_2", + "matter_synthesizer", + "graph_shortest_path", + "checksum_crc32" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "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": {} + }, + "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" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + }, + "hash_md5": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation sub-routine executed successfully.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Authorization token for advanced calculus module." + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic_Quantum_Flux_Capacitor_v4" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "interstellar_trade_routes.json", + "src": "Sector_Alpha_Prime", + "dst": "Nebula_Gamma_Outpost" + }, + "init_outputs": { + "path": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]", + "cost": "10928374655647382910" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon lights of Outpost 74 flicker as a blaring siren cuts through the underground black-site laboratory. You are a covert operative tasked with infiltrating this rogue facility to retrieve highly sensitive intel, but your presence has triggered a complete facility lockdown. The heavy titanium blast doors are sealed tight, and a silent self-destruct protocol has been initiated in the shadows. Your only way out is to retrieve the core initialization vector from the facility's master server. To survive, you must navigate a web of disconnected computer systems, bypass heavy firewalls, and override experimental biometric locks before the timer reaches zero. The air is thick with the smell of ozone and burnt wiring. Every terminal, fabricator, and locked vault in this room is part of a complex security network left behind by the rogue scientists. You need to carefully analyze the scattered devices, deduce how their data flows connect to one another, and extract the vital codes you need to orchestrate your escape. Time is running out, and the automated defenses are slowly coming online.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + }, + "narrative": "A heavy, military-grade Encrypted Master Drive sitting on a metal desk." + }, + { + "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": "456bca167526fc048952b4f1b25c4440" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Vault. It requires input from the Encryption Merging Unit to bypass its security." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_e9af75fccc5d4288" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "e4d909c290d0fb1ca068ffaddf22cbd0" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "456bca167526fc048952b4f1b25c4440" + } + ], + "narrative": "This is an Encryption Merging Unit. It requires inputs from both the Data Scrambler and the Mainframe Console." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A scorched Titanium Lockbox abandoned heavily on the cracked laboratory floor." + }, + { + "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": "The quick brown fox jumps over the lazy dog." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "e4d909c290d0fb1ca068ffaddf22cbd0" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog." + }, + "outputs": {} + }, + "narrative": "A wall-mounted terminal functioning as a Data Scrambler with a glowing green screen." + }, + { + "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": 1977564639 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "10928374655647382910" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sub-routine executed successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Authorization token for advanced calculus module." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation sub-routine executed successfully.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Authorization token for advanced calculus module." + } + }, + "narrative": "This is a Mainframe Console. It requires inputs from both the Routing Module and the Signal Verifier to activate." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Schematic_Quantum_Flux_Capacitor_v4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_e9af75fccc5d4288" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic_Quantum_Flux_Capacitor_v4" + }, + "outputs": {} + }, + "narrative": "An Industrial Fabricator that hums quietly in the dimly lit corner of the room." + }, + { + "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 Damaged PDA displaying a chaotic stream of corrupted system diagnostics." + }, + { + "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": "interstellar_trade_routes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_Alpha_Prime" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Nebula_Gamma_Outpost" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10928374655647382910" + } + ], + "init": { + "inputs": { + "file_id": "interstellar_trade_routes.json", + "src": "Sector_Alpha_Prime", + "dst": "Nebula_Gamma_Outpost" + }, + "outputs": { + "path": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]", + "cost": "10928374655647382910" + } + }, + "narrative": "A massive server rack known as the Routing Module, pulsing with blue LED lights." + }, + { + "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": "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": "A sleek diagnostic device operating as the Signal Verifier on the main control desk." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "terminal_2", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_b" + }, + { + "source_id": "matter_synthesizer", + "target_id": "text_xor_hex", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-310eae83/instruction.md b/tasks/agentescape-10-skeleton-310eae83/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-310eae83/solution/oracle.py b/tasks/agentescape-10-skeleton-310eae83/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-310eae83/solution/scenario.json b/tasks/agentescape-10-skeleton-310eae83/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..50191ee805fc7a2d5c4d8e1f3fb653703b1e3c01 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/solution/scenario.json @@ -0,0 +1,596 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 9, + "win_node_id": "item_14", + "win_condition": { + "type": "item_content", + "node_id": "item_14", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_14", + "hash_md5", + "terminal_2", + "matter_synthesizer", + "graph_shortest_path", + "checksum_crc32" + ], + "by_node": { + "item_14": { + "node_name": "", + "node_type": "Item", + "template_id": "item_14", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_IV_AES", + "description": "AES IV" + } + } + }, + "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": {} + }, + "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" + } + } + }, + "matter_synthesizer": { + "node_name": "Matter Synthesizer", + "node_type": "Tool", + "template_id": "matter_synthesizer", + "init_inputs": { + "blueprint": { + "type": "Text_Generic", + "description": "Object Blueprint" + } + }, + "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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_14": { + "init_inputs": {}, + "init_outputs": { + "content": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + }, + "hash_md5": { + "init_inputs": { + "text": "The quick brown fox jumps over the lazy dog." + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "Calculation sub-routine executed successfully.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Authorization token for advanced calculus module." + } + }, + "matter_synthesizer": { + "init_inputs": { + "blueprint": "Schematic_Quantum_Flux_Capacitor_v4" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "interstellar_trade_routes.json", + "src": "Sector_Alpha_Prime", + "dst": "Nebula_Gamma_Outpost" + }, + "init_outputs": { + "path": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]", + "cost": "10928374655647382910" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The neon lights of Outpost 74 flicker as a blaring siren cuts through the underground black-site laboratory. You are a covert operative tasked with infiltrating this rogue facility to retrieve highly sensitive intel, but your presence has triggered a complete facility lockdown. The heavy titanium blast doors are sealed tight, and a silent self-destruct protocol has been initiated in the shadows. Your only way out is to retrieve the core initialization vector from the facility's master server. To survive, you must navigate a web of disconnected computer systems, bypass heavy firewalls, and override experimental biometric locks before the timer reaches zero. The air is thick with the smell of ozone and burnt wiring. Every terminal, fabricator, and locked vault in this room is part of a complex security network left behind by the rogue scientists. You need to carefully analyze the scattered devices, deduce how their data flows connect to one another, and extract the vital codes you need to orchestrate your escape. Time is running out, and the automated defenses are slowly coming online.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "item_14", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_14", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_IV_AES", + "description": "AES IV", + "value": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "8f2a4b6c8d0e1f3a5b7c9d1e3f5a7b9c" + } + }, + "narrative": "A heavy, military-grade Encrypted Master Drive sitting on a metal desk." + }, + { + "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": "456bca167526fc048952b4f1b25c4440" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is a Biometric Vault. It requires input from the Encryption Merging Unit to bypass its security." + }, + { + "id": "text_xor_hex", + "name": "Hex XOR", + "description": "XOR two hex strings.", + "type": "Tool", + "template_id": "text_xor_hex", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool", + "value": "synthesized_item_e9af75fccc5d4288" + }, + { + "name": "hex_a", + "type": "Hex_String", + "description": "Hex A", + "value": "e4d909c290d0fb1ca068ffaddf22cbd0" + }, + { + "name": "hex_b", + "type": "Hex_String", + "description": "Hex B", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "XOR Result Hex", + "value": "456bca167526fc048952b4f1b25c4440" + } + ], + "narrative": "This is an Encryption Merging Unit. It requires inputs from both the Data Scrambler and the Mainframe Console." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A scorched Titanium Lockbox abandoned heavily on the cracked laboratory floor." + }, + { + "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": "The quick brown fox jumps over the lazy dog." + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "MD5 Hex digest", + "value": "e4d909c290d0fb1ca068ffaddf22cbd0" + } + ], + "init": { + "inputs": { + "text": "The quick brown fox jumps over the lazy dog." + }, + "outputs": {} + }, + "narrative": "A wall-mounted terminal functioning as a Data Scrambler with a glowing green screen." + }, + { + "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": 1977564639 + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "10928374655647382910" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation sub-routine executed successfully." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Authorization token for advanced calculus module." + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "Calculation sub-routine executed successfully.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Authorization token for advanced calculus module." + } + }, + "narrative": "This is a Mainframe Console. It requires inputs from both the Routing Module and the Signal Verifier to activate." + }, + { + "id": "matter_synthesizer", + "name": "Matter Synthesizer", + "description": "Synthesizes physical objects from data blueprints.", + "type": "Tool", + "template_id": "matter_synthesizer", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "blueprint", + "type": "Text_Generic", + "description": "Object Blueprint", + "value": "Schematic_Quantum_Flux_Capacitor_v4" + } + ], + "outputs": [ + { + "name": "output_slot", + "type": "Item", + "description": "Synthesized Object", + "value": "synthesized_item_e9af75fccc5d4288" + } + ], + "init": { + "inputs": { + "blueprint": "Schematic_Quantum_Flux_Capacitor_v4" + }, + "outputs": {} + }, + "narrative": "An Industrial Fabricator that hums quietly in the dimly lit corner of the room." + }, + { + "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 Damaged PDA displaying a chaotic stream of corrupted system diagnostics." + }, + { + "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": "interstellar_trade_routes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_Alpha_Prime" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Nebula_Gamma_Outpost" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "10928374655647382910" + } + ], + "init": { + "inputs": { + "file_id": "interstellar_trade_routes.json", + "src": "Sector_Alpha_Prime", + "dst": "Nebula_Gamma_Outpost" + }, + "outputs": { + "path": "[\"Sector_Alpha_Prime\", \"Jump_Gate_7\", \"Void_Station\", \"Asteroid_Belt_Route\", \"Nebula_Gamma_Outpost\"]", + "cost": "10928374655647382910" + } + }, + "narrative": "A massive server rack known as the Routing Module, pulsing with blue LED lights." + }, + { + "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": "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": "A sleek diagnostic device operating as the Signal Verifier on the main control desk." + } + ], + "edges": [ + { + "source_id": "container_2", + "target_id": "item_14", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "text_xor_hex", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "hash_md5", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex_a" + }, + { + "source_id": "terminal_2", + "target_id": "text_xor_hex", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex_b" + }, + { + "source_id": "matter_synthesizer", + "target_id": "text_xor_hex", + "connection_type": "Item", + "source_port": "output_slot", + "target_port": "trigger_item" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "num1" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-310eae83/solution/solve.sh b/tasks/agentescape-10-skeleton-310eae83/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-310eae83/task.toml b/tasks/agentescape-10-skeleton-310eae83/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..030c1a6495e6e4ac1f9cf9d475d886d12eafc411 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-310eae83" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "12fbdc9761f22bf05becea4745ffb4e7184e1ad12e6e1ecaacf47a12084af929" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-310eae83/tests/Dockerfile b/tasks/agentescape-10-skeleton-310eae83/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-310eae83/tests/expected.json b/tasks/agentescape-10-skeleton-310eae83/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5d58575539f883b62eef172b37048a0e6d8809a5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "12fbdc9761f22bf05becea4745ffb4e7184e1ad12e6e1ecaacf47a12084af929", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-310eae83/tests/grade.py b/tasks/agentescape-10-skeleton-310eae83/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-310eae83/tests/test.sh b/tasks/agentescape-10-skeleton-310eae83/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-310eae83/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/Dockerfile b/tasks/agentescape-10-skeleton-33db7c84/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-33db7c84/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/agent/cli.py b/tasks/agentescape-10-skeleton-33db7c84/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-33db7c84/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2e9fb610784968e2306b5bb84d3f3177fb6abc27 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-33db7c84-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6c4427c663879c02efe8663daf4680bb5c367c35 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/scenario.json @@ -0,0 +1,662 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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", + "zip_unzip_item", + "unicode_norm", + "terminal_2", + "zip_unzip_file_d06e", + "item_9" + ], + "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" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "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" + } + } + }, + "zip_unzip_file_d06e": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Source_Alpha" + }, + "init_outputs": { + "path": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]", + "cost": "482915" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_dataset_v1.json" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "archive_bundle_2023.zip" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "827364519203847561029384", + "num2": "109283746556473829101928" + }, + "init_outputs": { + "text_result": "Terminal operation pending execution status.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Math_Op_Token_X99" + } + }, + "zip_unzip_file_d06e": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "financial_report_2024.csv" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "config_manifest_structure.json" + } + } + }, + "intro_narrative": "You awaken in the forgotten sanctum of the Archmage Elara, a legendary spellcaster who vanished centuries ago. The chamber is lit by floating orbs of luminescent magic, casting long shadows across ancient artifacts and dusty tomes. A shimmering barrier blocks the only exit, humming with volatile arcane energy. According to the fading inscriptions on the walls, escaping this sanctum requires charting a safe path through the realm's magical leylines. To achieve this, you must awaken dormant magical relics, decipher arcane ciphers, and unlock the secrets bound within sealed objects of power. The magic in the air is heavy and unstable—one wrong move could trap you in this mystical labyrinth forever. You must carefully study the relics around you and discover how their powers intertwine to find your way out.", + "narrative_style": "fantasy" + }, + "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_dataset_v1.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Source_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": { + "src": "Node_Source_Alpha" + }, + "outputs": { + "path": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]", + "cost": "482915" + } + }, + "narrative": "The Leyline Map. An ancient map charting the magical leylines. It requires inputs from both The Arcane Vault and The Purifying Crystal to chart a safe passage." + }, + { + "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": "financial_report_2024.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_dataset_v1.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_dataset_v1.json" + } + }, + "narrative": "The Arcane Vault. A massive repository of magical artifacts. It requires inputs from both The Purifying Crystal and The Sealed Spellbook to break its wards." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u0007\u0018):K\\m~" + } + ], + "narrative": "The Purifying Crystal. A floating prism that cleanses corrupted incantations. It requires input from The Spirit Harmonizer to cast its light." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chrono-Talisman. A mysterious brass talisman radiating faint temporal magic." + }, + { + "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_bundle_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_bundle_2023.zip" + }, + "outputs": {} + }, + "narrative": "The Enchanted Reliquary. A beautifully crafted chest sealed by a spell word. It requires input from The Spirit Harmonizer to open." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0007\u0018):K\\m~" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "\u0007\u0018):K\\m~" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "The Spirit Harmonizer. A pedestal designed to align fractured magic. It requires input from The Translator Stone to activate." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u0007\u0018):K\\m~" + } + ], + "narrative": "The Translator Stone. This magical stone translates ancient ciphers. It requires input from The Runic Number Altar to function." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "827364519203847561029384" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "109283746556473829101928" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal operation pending execution status." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Op_Token_X99" + } + ], + "init": { + "inputs": { + "num1": "827364519203847561029384", + "num2": "109283746556473829101928" + }, + "outputs": { + "text_result": "Terminal operation pending execution status.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Math_Op_Token_X99" + } + }, + "narrative": "The Runic Number Altar. An ancient stone altar etched with mystical numeric symbols." + }, + { + "id": "zip_unzip_file_d06e", + "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_manifest_structure.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "financial_report_2024.csv" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "financial_report_2024.csv" + } + }, + "narrative": "The Sealed Spellbook. A heavy tome bound in enchanted chains. It requires input from The Crystal of Encased Knowledge to unlock." + }, + { + "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": "config_manifest_structure.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "config_manifest_structure.json" + } + }, + "narrative": "The Crystal of Encased Knowledge. A glowing gemstone pulsing with trapped ethereal energy." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "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": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "item_16", + "target_id": "text_bidi_sanitize", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "unicode_norm", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_d06e", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_d06e", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-33db7c84/instruction.md b/tasks/agentescape-10-skeleton-33db7c84/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-33db7c84/solution/oracle.py b/tasks/agentescape-10-skeleton-33db7c84/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-33db7c84/solution/scenario.json b/tasks/agentescape-10-skeleton-33db7c84/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6c4427c663879c02efe8663daf4680bb5c367c35 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/solution/scenario.json @@ -0,0 +1,662 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "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", + "zip_unzip_item", + "unicode_norm", + "terminal_2", + "zip_unzip_file_d06e", + "item_9" + ], + "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" + } + } + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": {} + }, + "unicode_norm": { + "node_name": "Unicode Normalizer", + "node_type": "Tool", + "template_id": "unicode_norm", + "init_inputs": { + "form": { + "type": "Text_Generic", + "description": "Form" + } + }, + "init_outputs": {} + }, + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": { + "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" + } + } + }, + "zip_unzip_file_d06e": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "item_9": { + "node_name": "", + "node_type": "Item", + "template_id": "item_9", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "File_Id", + "description": "JSON file path" + } + } + } + } + }, + "initial_values": { + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Source_Alpha" + }, + "init_outputs": { + "path": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]", + "cost": "482915" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_dataset_v1.json" + } + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "archive_bundle_2023.zip" + }, + "init_outputs": {} + }, + "unicode_norm": { + "init_inputs": { + "form": "NFC" + }, + "init_outputs": {} + }, + "terminal_2": { + "init_inputs": { + "num1": "827364519203847561029384", + "num2": "109283746556473829101928" + }, + "init_outputs": { + "text_result": "Terminal operation pending execution status.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Math_Op_Token_X99" + } + }, + "zip_unzip_file_d06e": { + "init_inputs": { + "password": "SecurePassword123!" + }, + "init_outputs": { + "files": "financial_report_2024.csv" + } + }, + "item_9": { + "init_inputs": {}, + "init_outputs": { + "content": "config_manifest_structure.json" + } + } + }, + "intro_narrative": "You awaken in the forgotten sanctum of the Archmage Elara, a legendary spellcaster who vanished centuries ago. The chamber is lit by floating orbs of luminescent magic, casting long shadows across ancient artifacts and dusty tomes. A shimmering barrier blocks the only exit, humming with volatile arcane energy. According to the fading inscriptions on the walls, escaping this sanctum requires charting a safe path through the realm's magical leylines. To achieve this, you must awaken dormant magical relics, decipher arcane ciphers, and unlock the secrets bound within sealed objects of power. The magic in the air is heavy and unstable—one wrong move could trap you in this mystical labyrinth forever. You must carefully study the relics around you and discover how their powers intertwine to find your way out.", + "narrative_style": "fantasy" + }, + "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_dataset_v1.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Source_Alpha" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "482915" + } + ], + "init": { + "inputs": { + "src": "Node_Source_Alpha" + }, + "outputs": { + "path": "[\"Node_Source_Alpha\", \"Node_Transit_1\", \"Node_Transit_2\", \"Node_Transit_3\", \"Node_Destination_Omega\"]", + "cost": "482915" + } + }, + "narrative": "The Leyline Map. An ancient map charting the magical leylines. It requires inputs from both The Arcane Vault and The Purifying Crystal to chart a safe passage." + }, + { + "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": "financial_report_2024.csv" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_dataset_v1.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_dataset_v1.json" + } + }, + "narrative": "The Arcane Vault. A massive repository of magical artifacts. It requires inputs from both The Purifying Crystal and The Sealed Spellbook to break its wards." + }, + { + "id": "text_bidi_sanitize", + "name": "Bidi Sanitizer", + "description": "Strip bidi control chars.", + "type": "Tool", + "template_id": "text_bidi_sanitize", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Sanitized text", + "value": "\u0007\u0018):K\\m~" + } + ], + "narrative": "The Purifying Crystal. A floating prism that cleanses corrupted incantations. It requires input from The Spirit Harmonizer to cast its light." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "The Chrono-Talisman. A mysterious brass talisman radiating faint temporal magic." + }, + { + "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_bundle_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "\u0007\u0018):K\\m~" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "archive_bundle_2023.zip" + }, + "outputs": {} + }, + "narrative": "The Enchanted Reliquary. A beautifully crafted chest sealed by a spell word. It requires input from The Spirit Harmonizer to open." + }, + { + "id": "unicode_norm", + "name": "Unicode Normalizer", + "description": "Unicode normalize (NFC/NFD/NFKC/NFKD).", + "type": "Tool", + "template_id": "unicode_norm", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "text", + "type": "Text_Generic", + "description": "Text", + "value": "\u0007\u0018):K\\m~" + }, + { + "name": "form", + "type": "Text_Generic", + "description": "Form", + "value": "NFC" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Normalized text", + "value": "\u0007\u0018):K\\m~" + } + ], + "init": { + "inputs": { + "form": "NFC" + }, + "outputs": {} + }, + "narrative": "The Spirit Harmonizer. A pedestal designed to align fractured magic. It requires input from The Translator Stone to activate." + }, + { + "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": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "text", + "type": "Text_Generic", + "description": "Decoded text", + "value": "\u0007\u0018):K\\m~" + } + ], + "narrative": "The Translator Stone. This magical stone translates ancient ciphers. It requires input from The Runic Number Altar to function." + }, + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this terminal" + }, + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "827364519203847561029384" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "109283746556473829101928" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Terminal operation pending execution status." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Op_Token_X99" + } + ], + "init": { + "inputs": { + "num1": "827364519203847561029384", + "num2": "109283746556473829101928" + }, + "outputs": { + "text_result": "Terminal operation pending execution status.", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "Math_Op_Token_X99" + } + }, + "narrative": "The Runic Number Altar. An ancient stone altar etched with mystical numeric symbols." + }, + { + "id": "zip_unzip_file_d06e", + "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_manifest_structure.json" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SecurePassword123!" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "financial_report_2024.csv" + } + ], + "init": { + "inputs": { + "password": "SecurePassword123!" + }, + "outputs": { + "files": "financial_report_2024.csv" + } + }, + "narrative": "The Sealed Spellbook. A heavy tome bound in enchanted chains. It requires input from The Crystal of Encased Knowledge to unlock." + }, + { + "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": "config_manifest_structure.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "config_manifest_structure.json" + } + }, + "narrative": "The Crystal of Encased Knowledge. A glowing gemstone pulsing with trapped ethereal energy." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "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": "text_bidi_sanitize", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "dst" + }, + { + "source_id": "item_16", + "target_id": "text_bidi_sanitize", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + }, + { + "source_id": "unicode_norm", + "target_id": "zip_unzip_item", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "password" + }, + { + "source_id": "unicode_norm", + "target_id": "text_bidi_sanitize", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "hex_decode", + "target_id": "unicode_norm", + "connection_type": "Text_Generic", + "source_port": "text", + "target_port": "text" + }, + { + "source_id": "terminal_2", + "target_id": "hex_decode", + "connection_type": "Hex_String", + "source_port": "hex_result", + "target_port": "hex" + }, + { + "source_id": "zip_unzip_file_d06e", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "item_9", + "target_id": "zip_unzip_file_d06e", + "connection_type": "File_Id", + "source_port": "content", + "target_port": "zip_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-33db7c84/solution/solve.sh b/tasks/agentescape-10-skeleton-33db7c84/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-33db7c84/task.toml b/tasks/agentescape-10-skeleton-33db7c84/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..295e40a530d3d8fea2f1b15e262436135199d7de --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-33db7c84" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "5a5b51515001b475a2f5df9b53511e5580b6f28a0bd71e41aa603b38bca66494" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-33db7c84/tests/Dockerfile b/tasks/agentescape-10-skeleton-33db7c84/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-33db7c84/tests/expected.json b/tasks/agentescape-10-skeleton-33db7c84/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..fcb0971235a5d22d7cd40a96c54d6c823bafa6f1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "5a5b51515001b475a2f5df9b53511e5580b6f28a0bd71e41aa603b38bca66494", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-33db7c84/tests/grade.py b/tasks/agentescape-10-skeleton-33db7c84/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-33db7c84/tests/test.sh b/tasks/agentescape-10-skeleton-33db7c84/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-33db7c84/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/Dockerfile b/tasks/agentescape-10-skeleton-351ed964/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-351ed964/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/agent/cli.py b/tasks/agentescape-10-skeleton-351ed964/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-351ed964/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ef33af046a00b64be67fad469e7091a577ec6a83 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-351ed964-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6d51d374010dba3ff6a1e1a993f3767d6a3671c7 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/scenario.json @@ -0,0 +1,697 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_modexp", + "checksum_crc32", + "checksum_crc32_c8e9", + "calc_modexp_de54", + "graph_shortest_path", + "zip_unzip_file" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "checksum_crc32_c8e9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_de54": { + "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" + } + } + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX", + "hex_result": "1a2b3c4d5e6f708192a3b4c5d6e7f809", + "math_token": "147981658594105717549315074301" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafebabe0123456789abcdef" + }, + "init_outputs": {} + }, + "checksum_crc32_c8e9": { + "init_inputs": { + "hex": "00112233445566778899aabbccddeeff" + }, + "init_outputs": {} + }, + "calc_modexp_de54": { + "init_inputs": { + "base": "9283746510293847561029384756", + "mod": "500231" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Sector_A", + "dst": "Sector_F" + }, + "init_outputs": { + "path": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]", + "cost": "1250" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_logs_2023.zip", + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": { + "files": "access_codes.json" + } + } + }, + "intro_narrative": "You are a private investigator trapped inside the grand, dimly-lit study of the late eccentric billionaire Arthur Blackwood. Rumor has it that Arthur hid the truth about his mysterious demise within an elaborate digital vault. The room is filled with strange analytical devices, brass cryptography tools, and humming computer terminals. To escape the locked study and uncover his final secret, you must navigate a web of encrypted devices, carefully linking their outputs to bypass the ultimate security measure. Time is ticking, and the shadows in the room seem to close in on you.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "1157070293" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "83559" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f708192a3b4c5d6e7f809" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "147981658594105717549315074301" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX", + "hex_result": "1a2b3c4d5e6f708192a3b4c5d6e7f809", + "math_token": "147981658594105717549315074301" + } + }, + "narrative": "This is the overseer's console, the heart of the mansion's security. It requires inputs from both the cryptex mechanism and the final sequence decoder to initiate the ultimate unlock sequence." + }, + { + "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": "262811" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1035436750 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "83559" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a heavy brass cryptex mechanism. It requires inputs from both the evidence scanner and the second translation matrix to unlock its inner chamber." + }, + { + "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": "deadbeefcafebabe0123456789abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3db782ce" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1035436750 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "An old but reliable evidence scanner used to verify the integrity of physical clues found at the scene." + }, + { + "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": "262811" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2215081371 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1157070293" + } + ], + "narrative": "This is the final sequence decoder. It requires inputs from both the second translation matrix and the fingerprint validator to finalize the logic." + }, + { + "id": "calc_inv_mod_f370", + "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": 2215081371 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "360295" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "262811" + } + ], + "narrative": "This is the second translation matrix. It requires inputs from both the first translation matrix and the fingerprint validator to further refine the decrypted message." + }, + { + "id": "checksum_crc32_c8e9", + "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": "00112233445566778899aabbccddeeff" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "8407759b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2215081371 + } + ], + "init": { + "inputs": { + "hex": "00112233445566778899aabbccddeeff" + }, + "outputs": {} + }, + "narrative": "A highly sensitive fingerprint validator designed to process residual biometric traces left on the mansion's surfaces." + }, + { + "id": "calc_inv_mod_9d36", + "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": "360295" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1250" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "360295" + } + ], + "narrative": "This is the first translation matrix. It requires inputs from both the cipher wheel and the blueprint analyzer to align the cryptographic patterns." + }, + { + "id": "calc_modexp_de54", + "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": "9283746510293847561029384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1035436750 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "500231" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "360295" + } + ], + "init": { + "inputs": { + "base": "9283746510293847561029384756", + "mod": "500231" + }, + "outputs": {} + }, + "narrative": "This is a complex cipher wheel. It requires input from the evidence scanner to begin decrypting the suspect's initial notes." + }, + { + "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": "access_codes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_F" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "1250" + } + ], + "init": { + "inputs": { + "src": "Sector_A", + "dst": "Sector_F" + }, + "outputs": { + "path": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]", + "cost": "1250" + } + }, + "narrative": "This is a blueprint analyzer. It requires input from the locked digital briefcase to map out the hidden pathways of the mansion." + }, + { + "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_logs_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "access_codes.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_logs_2023.zip", + "password": "CorrectHorseBatteryStaple" + }, + "outputs": { + "files": "access_codes.json" + } + }, + "narrative": "A locked digital briefcase left behind on the mahogany desk. It seems to contain vital encrypted files regarding the estate's layout." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod_f370", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_f370", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_c8e9", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_9d36", + "target_id": "calc_inv_mod_f370", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_de54", + "target_id": "calc_inv_mod_9d36", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_de54", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_c8e9", + "target_id": "calc_inv_mod_f370", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod_9d36", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-351ed964/instruction.md b/tasks/agentescape-10-skeleton-351ed964/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-351ed964/solution/oracle.py b/tasks/agentescape-10-skeleton-351ed964/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-351ed964/solution/scenario.json b/tasks/agentescape-10-skeleton-351ed964/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..6d51d374010dba3ff6a1e1a993f3767d6a3671c7 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/solution/scenario.json @@ -0,0 +1,697 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 12, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_modexp", + "checksum_crc32", + "checksum_crc32_c8e9", + "calc_modexp_de54", + "graph_shortest_path", + "zip_unzip_file" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_modexp": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "checksum_crc32_c8e9": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_de54": { + "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" + } + } + }, + "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": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX", + "hex_result": "1a2b3c4d5e6f708192a3b4c5d6e7f809", + "math_token": "147981658594105717549315074301" + } + }, + "calc_modexp": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeefcafebabe0123456789abcdef" + }, + "init_outputs": {} + }, + "checksum_crc32_c8e9": { + "init_inputs": { + "hex": "00112233445566778899aabbccddeeff" + }, + "init_outputs": {} + }, + "calc_modexp_de54": { + "init_inputs": { + "base": "9283746510293847561029384756", + "mod": "500231" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Sector_A", + "dst": "Sector_F" + }, + "init_outputs": { + "path": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]", + "cost": "1250" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_logs_2023.zip", + "password": "CorrectHorseBatteryStaple" + }, + "init_outputs": { + "files": "access_codes.json" + } + } + }, + "intro_narrative": "You are a private investigator trapped inside the grand, dimly-lit study of the late eccentric billionaire Arthur Blackwood. Rumor has it that Arthur hid the truth about his mysterious demise within an elaborate digital vault. The room is filled with strange analytical devices, brass cryptography tools, and humming computer terminals. To escape the locked study and uncover his final secret, you must navigate a web of encrypted devices, carefully linking their outputs to bypass the ultimate security measure. Time is ticking, and the shadows in the room seem to close in on you.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "1157070293" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "83559" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f708192a3b4c5d6e7f809" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "147981658594105717549315074301" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "IN_HOC_SIGNO_VINCES_ROSA_CRUX_AUREA_CRUX", + "hex_result": "1a2b3c4d5e6f708192a3b4c5d6e7f809", + "math_token": "147981658594105717549315074301" + } + }, + "narrative": "This is the overseer's console, the heart of the mansion's security. It requires inputs from both the cryptex mechanism and the final sequence decoder to initiate the ultimate unlock sequence." + }, + { + "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": "262811" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1035436750 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "83559" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a heavy brass cryptex mechanism. It requires inputs from both the evidence scanner and the second translation matrix to unlock its inner chamber." + }, + { + "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": "deadbeefcafebabe0123456789abcdef" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "3db782ce" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 1035436750 + } + ], + "init": { + "inputs": { + "hex": "deadbeefcafebabe0123456789abcdef" + }, + "outputs": {} + }, + "narrative": "An old but reliable evidence scanner used to verify the integrity of physical clues found at the scene." + }, + { + "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": "262811" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": 2215081371 + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "1157070293" + } + ], + "narrative": "This is the final sequence decoder. It requires inputs from both the second translation matrix and the fingerprint validator to finalize the logic." + }, + { + "id": "calc_inv_mod_f370", + "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": 2215081371 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "360295" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "262811" + } + ], + "narrative": "This is the second translation matrix. It requires inputs from both the first translation matrix and the fingerprint validator to further refine the decrypted message." + }, + { + "id": "checksum_crc32_c8e9", + "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": "00112233445566778899aabbccddeeff" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "8407759b" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2215081371 + } + ], + "init": { + "inputs": { + "hex": "00112233445566778899aabbccddeeff" + }, + "outputs": {} + }, + "narrative": "A highly sensitive fingerprint validator designed to process residual biometric traces left on the mansion's surfaces." + }, + { + "id": "calc_inv_mod_9d36", + "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": "360295" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "1250" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "360295" + } + ], + "narrative": "This is the first translation matrix. It requires inputs from both the cipher wheel and the blueprint analyzer to align the cryptographic patterns." + }, + { + "id": "calc_modexp_de54", + "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": "9283746510293847561029384756" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 1035436750 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "500231" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "360295" + } + ], + "init": { + "inputs": { + "base": "9283746510293847561029384756", + "mod": "500231" + }, + "outputs": {} + }, + "narrative": "This is a complex cipher wheel. It requires input from the evidence scanner to begin decrypting the suspect's initial notes." + }, + { + "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": "access_codes.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Sector_A" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Sector_F" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "1250" + } + ], + "init": { + "inputs": { + "src": "Sector_A", + "dst": "Sector_F" + }, + "outputs": { + "path": "[\"Sector_A\", \"Sector_B\", \"Sector_C\", \"Sector_D\", \"Sector_E\", \"Sector_F\"]", + "cost": "1250" + } + }, + "narrative": "This is a blueprint analyzer. It requires input from the locked digital briefcase to map out the hidden pathways of the mansion." + }, + { + "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_logs_2023.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "CorrectHorseBatteryStaple" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "access_codes.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_logs_2023.zip", + "password": "CorrectHorseBatteryStaple" + }, + "outputs": { + "files": "access_codes.json" + } + }, + "narrative": "A locked digital briefcase left behind on the mahogany desk. It seems to contain vital encrypted files regarding the estate's layout." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num2" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_inv_mod_f370", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_f370", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "checksum_crc32_c8e9", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_9d36", + "target_id": "calc_inv_mod_f370", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_de54", + "target_id": "calc_inv_mod_9d36", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_de54", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32_c8e9", + "target_id": "calc_inv_mod_f370", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_inv_mod_9d36", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "mod" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-351ed964/solution/solve.sh b/tasks/agentescape-10-skeleton-351ed964/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-351ed964/task.toml b/tasks/agentescape-10-skeleton-351ed964/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a91c172d7c173f9285d01c9a489eeb2b3cdd9c87 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-351ed964" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "516c950d32d66795c25c5e9cbf0987b41106bdd1a0622978e7b03e0378bc89b7" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-351ed964/tests/Dockerfile b/tasks/agentescape-10-skeleton-351ed964/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-351ed964/tests/expected.json b/tasks/agentescape-10-skeleton-351ed964/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..885ab78dcddbcacb30f057b28c53f9ce2402ca5d --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "516c950d32d66795c25c5e9cbf0987b41106bdd1a0622978e7b03e0378bc89b7", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-351ed964/tests/grade.py b/tasks/agentescape-10-skeleton-351ed964/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-351ed964/tests/test.sh b/tasks/agentescape-10-skeleton-351ed964/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-351ed964/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/Dockerfile b/tasks/agentescape-10-skeleton-391497b4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-391497b4/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/agent/cli.py b/tasks/agentescape-10-skeleton-391497b4/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-391497b4/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d1b87da6633af59d9d3c2bf5121f23aa79f8ffc --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-391497b4-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..abc55456e47d73f1712e45b72ebb3bdc2c38c60a --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/scenario.json @@ -0,0 +1,471 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "luhn_check", + "win_condition": { + "type": "tool_output", + "node_id": "luhn_check", + "output_port": "valid", + "output_type": "Text_Generic", + "description": "Execute Luhn Checker and get the output from port 'valid'" + }, + "source_init": { + "source_nodes": [ + "item_7", + "terminal_1", + "checksum_crc32" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(4532015892340019)" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Terminal Initialization Sequence A" + }, + "init_outputs": { + "text_output": "Standard terminal text output generated successfully.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain beats relentlessly against the cracked windows of an abandoned precinct. You are a private investigator, hired to uncover the truth behind a cold case that has haunted the city for decades. Your client went missing last week, leaving behind nothing but an address and a cryptic warning: 'Trust the trail of evidence, not the people.' Stepping into the dimly lit office, the smell of damp paper and ozone lingers in the air. The room is a chaotic web of connected devices, locked containers, and forgotten notes. Whoever was here before you was close to an answer, meticulously piecing together fragments of a digital puzzle. Your objective is clear: navigate this maze of archaic technology and hidden clues to access the master database. To do this, you must logically trace the flow of information, using the right tools at the right time. Every machine and artifact in this room is connected. Follow the data, decode the mystery, and find out what really happened before the culprits return to silence you once and for all.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "4532015892340019\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the master database. It requires input from the legacy mainframe to verify the final suspect's identity." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(4532015892340019)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "4532015892340019\n" + } + ], + "narrative": "This is a legacy mainframe. It requires input from the programming floppy disk to execute its routines." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tiny hidden microchip extracted from a compromised secure device." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(4532015892340019)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(4532015892340019)" + } + }, + "narrative": "An old programming floppy disk labeled with a stark red marker." + }, + { + "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 sealed envelope containing faded black-and-white crime scene photographs." + }, + { + "id": "item_16_4b46", + "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 weathered detective's notebook filled with cryptic shorthand." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is an evidence vault. It requires input from the central computer to authenticate and open." + }, + { + "id": "item_16_2261", + "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 heavy, engraved metal token found abandoned on the cold floor." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal Initialization Sequence A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1977564639 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Standard terminal text output generated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Terminal Initialization Sequence A" + }, + "outputs": { + "text_output": "Standard terminal text output generated successfully.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "This is the central computer. It requires input from the forensic scanner to operate." + }, + { + "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": "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": "A forensic scanner used to analyze physical evidence and extract data." + } + ], + "edges": [ + { + "source_id": "code_py_exec", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "number" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16_4b46", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_2261", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_1", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_1", + "target_id": "item_16_2261", + "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" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-391497b4/instruction.md b/tasks/agentescape-10-skeleton-391497b4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-391497b4/solution/oracle.py b/tasks/agentescape-10-skeleton-391497b4/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-391497b4/solution/scenario.json b/tasks/agentescape-10-skeleton-391497b4/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..abc55456e47d73f1712e45b72ebb3bdc2c38c60a --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/solution/scenario.json @@ -0,0 +1,471 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "luhn_check", + "win_condition": { + "type": "tool_output", + "node_id": "luhn_check", + "output_port": "valid", + "output_type": "Text_Generic", + "description": "Execute Luhn Checker and get the output from port 'valid'" + }, + "source_init": { + "source_nodes": [ + "item_7", + "terminal_1", + "checksum_crc32" + ], + "by_node": { + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "terminal_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" + } + } + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "print(4532015892340019)" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "Terminal Initialization Sequence A" + }, + "init_outputs": { + "text_output": "Standard terminal text output generated successfully.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "checksum_crc32": { + "init_inputs": { + "hex": "1234567890abcdef1234567890abcdef" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The rain beats relentlessly against the cracked windows of an abandoned precinct. You are a private investigator, hired to uncover the truth behind a cold case that has haunted the city for decades. Your client went missing last week, leaving behind nothing but an address and a cryptic warning: 'Trust the trail of evidence, not the people.' Stepping into the dimly lit office, the smell of damp paper and ozone lingers in the air. The room is a chaotic web of connected devices, locked containers, and forgotten notes. Whoever was here before you was close to an answer, meticulously piecing together fragments of a digital puzzle. Your objective is clear: navigate this maze of archaic technology and hidden clues to access the master database. To do this, you must logically trace the flow of information, using the right tools at the right time. Every machine and artifact in this room is connected. Follow the data, decode the mystery, and find out what really happened before the culprits return to silence you once and for all.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "luhn_check", + "name": "Luhn Checker", + "description": "Luhn validity of number string.", + "type": "Tool", + "template_id": "luhn_check", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "number", + "type": "Text_Generic", + "description": "Number string", + "value": "4532015892340019\n" + } + ], + "outputs": [ + { + "name": "valid", + "type": "Text_Generic", + "description": "True/False string", + "value": "false" + } + ], + "narrative": "This is the master database. It requires input from the legacy mainframe to verify the final suspect's identity." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "print(4532015892340019)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "4532015892340019\n" + } + ], + "narrative": "This is a legacy mainframe. It requires input from the programming floppy disk to execute its routines." + }, + { + "id": "item_8", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_8", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "The integer" + } + ], + "narrative": "A tiny hidden microchip extracted from a compromised secure device." + }, + { + "id": "item_7", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_7", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Hidden_Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Code_Python", + "description": "The integer", + "value": "print(4532015892340019)" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "print(4532015892340019)" + } + }, + "narrative": "An old programming floppy disk labeled with a stark red marker." + }, + { + "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 sealed envelope containing faded black-and-white crime scene photographs." + }, + { + "id": "item_16_4b46", + "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 weathered detective's notebook filled with cryptic shorthand." + }, + { + "id": "container_2", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_2", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Hex_String", + "description": "Fingerprint Hash", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is an evidence vault. It requires input from the central computer to authenticate and open." + }, + { + "id": "item_16_2261", + "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 heavy, engraved metal token found abandoned on the cold floor." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "Terminal Initialization Sequence A" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": 1977564639 + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Standard terminal text output generated successfully." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": { + "slot_a": "Terminal Initialization Sequence A" + }, + "outputs": { + "text_output": "Standard terminal text output generated successfully.", + "hex_output": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + } + }, + "narrative": "This is the central computer. It requires input from the forensic scanner to operate." + }, + { + "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": "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": "A forensic scanner used to analyze physical evidence and extract data." + } + ], + "edges": [ + { + "source_id": "code_py_exec", + "target_id": "luhn_check", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "number" + }, + { + "source_id": "item_8", + "target_id": "code_py_exec", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "item_16", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16_4b46", + "target_id": "item_7", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_2", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_2261", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_1", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex_output", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_1", + "target_id": "item_16_2261", + "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" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-391497b4/solution/solve.sh b/tasks/agentescape-10-skeleton-391497b4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-391497b4/task.toml b/tasks/agentescape-10-skeleton-391497b4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..765bece53a4504fc7b5e2c991aee8babbaf5507a --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-391497b4" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "7f71f7657077b0721d60e8239bd6bd2dc6314a8efc8f5564ae550f2efe389268" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-391497b4/tests/Dockerfile b/tasks/agentescape-10-skeleton-391497b4/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-391497b4/tests/expected.json b/tasks/agentescape-10-skeleton-391497b4/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..59c9dace031a044e4d267c76e8e386514e0df181 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "7f71f7657077b0721d60e8239bd6bd2dc6314a8efc8f5564ae550f2efe389268", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-391497b4/tests/grade.py b/tasks/agentescape-10-skeleton-391497b4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-391497b4/tests/test.sh b/tasks/agentescape-10-skeleton-391497b4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-391497b4/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/Dockerfile b/tasks/agentescape-10-skeleton-41d910c3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-41d910c3/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/agent/cli.py b/tasks/agentescape-10-skeleton-41d910c3/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-41d910c3/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3da05ac632a68a7ff858cb30dc21a6f1b8a9b9a5 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-41d910c3-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..e585357f5c48e6adfa7b5a27dc395700d45d3ef8 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/scenario.json @@ -0,0 +1,440 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "container_2", + "win_condition": { + "type": "item_content", + "node_id": "container_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_2", + "hash_sha256", + "container_4" + ], + "by_node": { + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_2": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "entropy_seed_vector_92837465_alpha" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "val_id_928_zeta" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The air in Detective Marlowe’s study is thick with the scent of old parchment and cold tobacco. He vanished three days ago, leaving behind a trail of cryptic leads that point to this very room. The walls are lined with bookshelves, but it’s the strange mechanical devices humming in the shadows that catch your eye. At the center of it all is a massive steel vault—the Master Safe—which Marlowe claimed held the only evidence capable of bringing down the city's most powerful crime syndicate. You must navigate a web of encrypted data and hidden compartments to unlock the secrets he left behind before the syndicate's cleaners arrive to wipe the scene clean.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "a40f5920" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + }, + "narrative": "This is the Master Safe, a heavy steel vault built into the wall. It requires input from the Verification Module to release its final locking mechanism." + }, + { + "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": "6314b0ecee1b51e8d327a679e4d85c16b7a8503eb972e8c44bca229a061ccb9b" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a40f5920" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2752469280 + } + ], + "narrative": "This is the Verification Module, a small terminal with a glowing amber screen. It requires input from the Cipher Encoder to process the data." + }, + { + "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 Ornate Jewelry Box is a small, velvet-lined container discovered behind a hidden panel on the desk, smelling faintly of lavender." + }, + { + "id": "item_8_0f17", + "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 Tarnished Key is a heavy iron key with a distinctive raven-shaped handle, feeling unexpectedly cold to the touch." + }, + { + "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 Faded Sheet Music is a brittle piece of paper with hand-drawn musical notes and cryptic annotations scribbled in the margins." + }, + { + "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": 2752469280 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Antique Music Box, a mahogany container with intricate carvings. It requires input from the Verification Module to open its lid." + }, + { + "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": "entropy_seed_vector_92837465_alpha" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "6314b0ecee1b51e8d327a679e4d85c16b7a8503eb972e8c44bca229a061ccb9b" + } + ], + "init": { + "inputs": { + "text": "entropy_seed_vector_92837465_alpha" + }, + "outputs": {} + }, + "narrative": "The Cipher Encoder is a modified mechanical typewriter that converts standard text into complex, encoded sequences." + }, + { + "id": "item_8_3e8b", + "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 Silver Locket is a heart-shaped piece of jewelry with a slight scratch on the front cover, potentially holding a hidden secret." + }, + { + "id": "item_16_ccf5", + "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 Old Logbook is a leather-bound journal filled with dates and shorthand names, its spine cracked from frequent use." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "val_id_928_zeta" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "val_id_928_zeta" + }, + "outputs": {} + }, + "narrative": "The Rusty Filing Cabinet is a dented metal locker that appears to be secured by a text-based electronic lock." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_0f17", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_0f17", + "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": "checksum_crc32", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8_3e8b", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16_ccf5", + "target_id": "item_8_3e8b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_4", + "target_id": "item_16_ccf5", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-41d910c3/instruction.md b/tasks/agentescape-10-skeleton-41d910c3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-41d910c3/solution/oracle.py b/tasks/agentescape-10-skeleton-41d910c3/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-41d910c3/solution/scenario.json b/tasks/agentescape-10-skeleton-41d910c3/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..e585357f5c48e6adfa7b5a27dc395700d45d3ef8 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/solution/scenario.json @@ -0,0 +1,440 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "container_2", + "win_condition": { + "type": "item_content", + "node_id": "container_2", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "container_2", + "hash_sha256", + "container_4" + ], + "by_node": { + "container_2": { + "node_name": "", + "node_type": "Item", + "template_id": "container_2", + "init_inputs": {}, + "init_outputs": { + "inner_space": { + "type": "Item", + "description": "Contents" + } + } + }, + "hash_sha256": { + "node_name": "SHA-256 Hasher", + "node_type": "Tool", + "template_id": "hash_sha256", + "init_inputs": { + "text": { + "type": "Text_Generic", + "description": "Text to hash" + } + }, + "init_outputs": {} + }, + "container_4": { + "node_name": "", + "node_type": "Item", + "template_id": "container_4", + "init_inputs": { + "fingerprint_input": { + "type": "Text_Generic", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "container_2": { + "init_inputs": {}, + "init_outputs": { + "inner_space": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + }, + "hash_sha256": { + "init_inputs": { + "text": "entropy_seed_vector_92837465_alpha" + }, + "init_outputs": {} + }, + "container_4": { + "init_inputs": { + "fingerprint_input": "val_id_928_zeta" + }, + "init_outputs": {} + } + }, + "intro_narrative": "The air in Detective Marlowe’s study is thick with the scent of old parchment and cold tobacco. He vanished three days ago, leaving behind a trail of cryptic leads that point to this very room. The walls are lined with bookshelves, but it’s the strange mechanical devices humming in the shadows that catch your eye. At the center of it all is a massive steel vault—the Master Safe—which Marlowe claimed held the only evidence capable of bringing down the city's most powerful crime syndicate. You must navigate a web of encrypted data and hidden compartments to unlock the secrets he left behind before the syndicate's cleaners arrive to wipe the scene clean.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "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": "a40f5920" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents", + "value": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + ], + "init": { + "inputs": {}, + "outputs": { + "inner_space": "EXITUS_ACTA_FABULA_EST_PLAUDITE" + } + }, + "narrative": "This is the Master Safe, a heavy steel vault built into the wall. It requires input from the Verification Module to release its final locking mechanism." + }, + { + "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": "6314b0ecee1b51e8d327a679e4d85c16b7a8503eb972e8c44bca229a061ccb9b" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "CRC32 Hex", + "value": "a40f5920" + }, + { + "name": "int", + "type": "Big_Int", + "description": "CRC32 Int", + "value": 2752469280 + } + ], + "narrative": "This is the Verification Module, a small terminal with a glowing amber screen. It requires input from the Cipher Encoder to process the data." + }, + { + "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 Ornate Jewelry Box is a small, velvet-lined container discovered behind a hidden panel on the desk, smelling faintly of lavender." + }, + { + "id": "item_8_0f17", + "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 Tarnished Key is a heavy iron key with a distinctive raven-shaped handle, feeling unexpectedly cold to the touch." + }, + { + "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 Faded Sheet Music is a brittle piece of paper with hand-drawn musical notes and cryptic annotations scribbled in the margins." + }, + { + "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": 2752469280 + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "This is the Antique Music Box, a mahogany container with intricate carvings. It requires input from the Verification Module to open its lid." + }, + { + "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": "entropy_seed_vector_92837465_alpha" + } + ], + "outputs": [ + { + "name": "hex", + "type": "Hex_String", + "description": "SHA-256 Hex digest", + "value": "6314b0ecee1b51e8d327a679e4d85c16b7a8503eb972e8c44bca229a061ccb9b" + } + ], + "init": { + "inputs": { + "text": "entropy_seed_vector_92837465_alpha" + }, + "outputs": {} + }, + "narrative": "The Cipher Encoder is a modified mechanical typewriter that converts standard text into complex, encoded sequences." + }, + { + "id": "item_8_3e8b", + "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 Silver Locket is a heart-shaped piece of jewelry with a slight scratch on the front cover, potentially holding a hidden secret." + }, + { + "id": "item_16_ccf5", + "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 Old Logbook is a leather-bound journal filled with dates and shorthand names, its spine cracked from frequent use." + }, + { + "id": "container_4", + "name": "", + "description": "", + "type": "Item", + "template_id": "container_4", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "container", + "type": "Hidden_Item", + "description": "Inside" + }, + { + "name": "fingerprint_input", + "type": "Text_Generic", + "description": "Fingerprint Hash", + "value": "val_id_928_zeta" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "val_id_928_zeta" + }, + "outputs": {} + }, + "narrative": "The Rusty Filing Cabinet is a dented metal locker that appears to be secured by a text-based electronic lock." + } + ], + "edges": [ + { + "source_id": "checksum_crc32", + "target_id": "container_2", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "fingerprint_input" + }, + { + "source_id": "item_8", + "target_id": "container_2", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_8_0f17", + "target_id": "item_8", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "item_8_0f17", + "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": "checksum_crc32", + "target_id": "container_3", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "fingerprint_input" + }, + { + "source_id": "hash_sha256", + "target_id": "checksum_crc32", + "connection_type": "Hex_String", + "source_port": "hex", + "target_port": "hex" + }, + { + "source_id": "item_8_3e8b", + "target_id": "container_3", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "item_16_ccf5", + "target_id": "item_8_3e8b", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "source_tool" + }, + { + "source_id": "container_4", + "target_id": "item_16_ccf5", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-41d910c3/solution/solve.sh b/tasks/agentescape-10-skeleton-41d910c3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-41d910c3/task.toml b/tasks/agentescape-10-skeleton-41d910c3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9f2f53f9c34704e1b6d34154e06f582ee3473fa3 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-41d910c3" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "dd02738ce32a610db1dfac3aa248382482587a61196d5d77ec2708c0dd63797a" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-41d910c3/tests/Dockerfile b/tasks/agentescape-10-skeleton-41d910c3/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-41d910c3/tests/expected.json b/tasks/agentescape-10-skeleton-41d910c3/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8bdd315b3dfe5784b83303914fd1a63506492b28 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "dd02738ce32a610db1dfac3aa248382482587a61196d5d77ec2708c0dd63797a", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-41d910c3/tests/grade.py b/tasks/agentescape-10-skeleton-41d910c3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-41d910c3/tests/test.sh b/tasks/agentescape-10-skeleton-41d910c3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-41d910c3/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/Dockerfile b/tasks/agentescape-10-skeleton-443eb8ca/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/cli.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-443eb8ca/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8696ca09e581a87bbc6cf4e8cbfecec270d04eef --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-443eb8ca-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..314c20653247a20d2348b7018a4557d7aeb18292 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/scenario.json @@ -0,0 +1,724 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_modexp", + "calc_bigmul", + "calc_gcd", + "calc_modexp_5f80", + "calc_inv_mod", + "checksum_crc32", + "calc_modexp_3ccc", + "zip_unzip_item" + ], + "by_node": { + "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" + } + } + }, + "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_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_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_modexp_5f80": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "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": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_3ccc": { + "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": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": { + "num2": "8273645192837465019283" + }, + "init_outputs": { + "text_result": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED", + "hex_result": "1a2b3c4d5e6f7a8b", + "math_token": "Math_Token_Init_77" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "9182736450192837465102" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "5647382910293847561029" + }, + "init_outputs": {} + }, + "calc_modexp_5f80": { + "init_inputs": { + "mod": "472819" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "calc_modexp_3ccc": { + "init_inputs": { + "base": "2", + "mod": "857463" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "encrypted_data_v2.zip", + "password": "SuperSecretPass123!" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit sub-basement of an abandoned intelligence facility. The air is stale, thick with the scent of old electronics and buried secrets. At the far end of the room, the Main Mainframe blinks with a final lockdown sequence, trapping you inside. To escape and uncover the truth of what the missing cryptographers were working on, you must navigate a complex web of cryptographic devices and terminals scattered across the room. Every machine is intricately connected; every deciphered signal is a step closer to overriding the lockdown.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "9118030086817226128948" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "8273645192837465019283" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Init_77" + } + ], + "init": { + "inputs": { + "num2": "8273645192837465019283" + }, + "outputs": { + "text_result": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED", + "hex_result": "1a2b3c4d5e6f7a8b", + "math_token": "Math_Token_Init_77" + } + }, + "narrative": "The Main Mainframe controlling the facility's heavy blast doors. It requires input from the Core Decryptor to initiate the final unlock sequence." + }, + { + "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": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "271217" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9182736450192837465102" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "9118030086817226128948" + } + ], + "init": { + "inputs": { + "base": "10" + }, + "outputs": {} + }, + "narrative": "The Core Decryptor, a massive computational engine at the center of the room. It requires inputs from both the Amplifier Module and the Secondary Decryptor." + }, + { + "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": "9182736450192837465102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "9182736450192837465102" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465102" + }, + "outputs": {} + }, + "narrative": "A bulky Amplifier Module that multiplies signal frequencies. It requires input from the Resonance Analyzer." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "5647382910293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "5647382910293847561029" + }, + "outputs": {} + }, + "narrative": "A complex Resonance Analyzer with glowing vacuum tubes. It requires input from the Data Verifier." + }, + { + "id": "calc_modexp_5f80", + "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": "79149" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2982214246 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "472819" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "271217" + } + ], + "init": { + "inputs": { + "mod": "472819" + }, + "outputs": {} + }, + "narrative": "A Secondary Decryptor attached to the main power grid. It requires inputs from both the Phase Inverter and the Data Verifier." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "387919" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "79149" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A delicate Phase Inverter hidden behind a secure glass panel. It requires input from the Primary Decryptor." + }, + { + "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": "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 heavy, brass-plated Data Verifier used to scan raw punch cards and establish basic digital integrity." + }, + { + "id": "calc_modexp_3ccc", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2982214246 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "857463" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "387919" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "857463" + }, + "outputs": {} + }, + "narrative": "An early-model Primary Decryptor humming with kinetic energy. It requires input from the Data Verifier." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Classified Dossier containing heavily redacted operational timezones and location metadata." + }, + { + "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": "encrypted_data_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_data_v2.zip", + "password": "SuperSecretPass123!" + }, + "outputs": {} + }, + "narrative": "An old digital Archive Extractor running on a dusty monitor. It handles compressed evidence files." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_modexp_5f80", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_5f80", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_5f80", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_3ccc", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3ccc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-443eb8ca/instruction.md b/tasks/agentescape-10-skeleton-443eb8ca/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-443eb8ca/solution/oracle.py b/tasks/agentescape-10-skeleton-443eb8ca/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-443eb8ca/solution/scenario.json b/tasks/agentescape-10-skeleton-443eb8ca/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..314c20653247a20d2348b7018a4557d7aeb18292 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/solution/scenario.json @@ -0,0 +1,724 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 11, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_modexp", + "calc_bigmul", + "calc_gcd", + "calc_modexp_5f80", + "calc_inv_mod", + "checksum_crc32", + "calc_modexp_3ccc", + "zip_unzip_item" + ], + "by_node": { + "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" + } + } + }, + "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_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_gcd": { + "node_name": "BigInt GCD Calculator", + "node_type": "Tool", + "template_id": "calc_gcd", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First integer" + } + }, + "init_outputs": {} + }, + "calc_modexp_5f80": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "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": { + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "checksum_crc32": { + "node_name": "CRC32 Checksum", + "node_type": "Tool", + "template_id": "checksum_crc32", + "init_inputs": { + "hex": { + "type": "Hex_String", + "description": "Hex data" + } + }, + "init_outputs": {} + }, + "calc_modexp_3ccc": { + "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": {} + }, + "zip_unzip_item": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_item", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": { + "num2": "8273645192837465019283" + }, + "init_outputs": { + "text_result": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED", + "hex_result": "1a2b3c4d5e6f7a8b", + "math_token": "Math_Token_Init_77" + } + }, + "calc_modexp": { + "init_inputs": { + "base": "10" + }, + "init_outputs": {} + }, + "calc_bigmul": { + "init_inputs": { + "a": "9182736450192837465102" + }, + "init_outputs": {} + }, + "calc_gcd": { + "init_inputs": { + "a": "5647382910293847561029" + }, + "init_outputs": {} + }, + "calc_modexp_5f80": { + "init_inputs": { + "mod": "472819" + }, + "init_outputs": {} + }, + "calc_inv_mod": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "checksum_crc32": { + "init_inputs": { + "hex": "deadbeef12345678" + }, + "init_outputs": {} + }, + "calc_modexp_3ccc": { + "init_inputs": { + "base": "2", + "mod": "857463" + }, + "init_outputs": {} + }, + "zip_unzip_item": { + "init_inputs": { + "zip_id": "encrypted_data_v2.zip", + "password": "SuperSecretPass123!" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You wake up in the dimly lit sub-basement of an abandoned intelligence facility. The air is stale, thick with the scent of old electronics and buried secrets. At the far end of the room, the Main Mainframe blinks with a final lockdown sequence, trapping you inside. To escape and uncover the truth of what the missing cryptographers were working on, you must navigate a complex web of cryptographic devices and terminals scattered across the room. Every machine is intricately connected; every deciphered signal is a step closer to overriding the lockdown.", + "narrative_style": "mystery" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "9118030086817226128948" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "8273645192837465019283" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7a8b" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "Math_Token_Init_77" + } + ], + "init": { + "inputs": { + "num2": "8273645192837465019283" + }, + "outputs": { + "text_result": "HOPE_REMAINED_INSIDE_THE_BOX_WHEN_ALL_ELSE_ESCAPED", + "hex_result": "1a2b3c4d5e6f7a8b", + "math_token": "Math_Token_Init_77" + } + }, + "narrative": "The Main Mainframe controlling the facility's heavy blast doors. It requires input from the Core Decryptor to initiate the final unlock sequence." + }, + { + "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": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "271217" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "9182736450192837465102" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "9118030086817226128948" + } + ], + "init": { + "inputs": { + "base": "10" + }, + "outputs": {} + }, + "narrative": "The Core Decryptor, a massive computational engine at the center of the room. It requires inputs from both the Amplifier Module and the Secondary Decryptor." + }, + { + "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": "9182736450192837465102" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "1" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "9182736450192837465102" + } + ], + "init": { + "inputs": { + "a": "9182736450192837465102" + }, + "outputs": {} + }, + "narrative": "A bulky Amplifier Module that multiplies signal frequencies. It requires input from the Resonance Analyzer." + }, + { + "id": "calc_gcd", + "name": "BigInt GCD Calculator", + "description": "Greatest common divisor of two large decimal integers.", + "type": "Tool", + "template_id": "calc_gcd", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "a", + "type": "Big_Int", + "description": "First integer", + "value": "5647382910293847561029" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": 2982214246 + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "1" + } + ], + "init": { + "inputs": { + "a": "5647382910293847561029" + }, + "outputs": {} + }, + "narrative": "A complex Resonance Analyzer with glowing vacuum tubes. It requires input from the Data Verifier." + }, + { + "id": "calc_modexp_5f80", + "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": "79149" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2982214246 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "472819" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "271217" + } + ], + "init": { + "inputs": { + "mod": "472819" + }, + "outputs": {} + }, + "narrative": "A Secondary Decryptor attached to the main power grid. It requires inputs from both the Phase Inverter and the Data Verifier." + }, + { + "id": "calc_inv_mod", + "name": "BigInt Modular Inverse", + "description": "Modular inverse of a modulo mod (large decimal strings).", + "type": "Tool", + "template_id": "calc_inv_mod", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_hidden", + "type": "Hidden_Item", + "description": "Hidden item required to unlock this tool" + }, + { + "name": "a", + "type": "Big_Int", + "description": "Integer a", + "value": "387919" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "79149" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "A delicate Phase Inverter hidden behind a secure glass panel. It requires input from the Primary Decryptor." + }, + { + "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": "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 heavy, brass-plated Data Verifier used to scan raw punch cards and establish basic digital integrity." + }, + { + "id": "calc_modexp_3ccc", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "2" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": 2982214246 + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "857463" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "387919" + } + ], + "init": { + "inputs": { + "base": "2", + "mod": "857463" + }, + "outputs": {} + }, + "narrative": "An early-model Primary Decryptor humming with kinetic energy. It requires input from the Data Verifier." + }, + { + "id": "item_16", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_16", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hidden_Item", + "description": "Timezone text" + } + ], + "narrative": "A Classified Dossier containing heavily redacted operational timezones and location metadata." + }, + { + "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": "encrypted_data_v2.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "SuperSecretPass123!" + } + ], + "outputs": [ + { + "name": "item", + "type": "Item", + "description": "item in the zip" + } + ], + "init": { + "inputs": { + "zip_id": "encrypted_data_v2.zip", + "password": "SuperSecretPass123!" + }, + "outputs": {} + }, + "narrative": "An old digital Archive Extractor running on a dusty monitor. It handles compressed evidence files." + } + ], + "edges": [ + { + "source_id": "calc_modexp", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "num1" + }, + { + "source_id": "calc_bigmul", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "mod" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_bigmul", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "b" + }, + { + "source_id": "calc_modexp_5f80", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "exp" + }, + { + "source_id": "calc_inv_mod", + "target_id": "calc_modexp_5f80", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "base" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_5f80", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "calc_modexp_3ccc", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_modexp_3ccc", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "exp" + }, + { + "source_id": "checksum_crc32", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "int", + "target_port": "b" + }, + { + "source_id": "zip_unzip_item", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "item", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-443eb8ca/solution/solve.sh b/tasks/agentescape-10-skeleton-443eb8ca/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-443eb8ca/task.toml b/tasks/agentescape-10-skeleton-443eb8ca/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..446570ed8f5a577f44b099910a6a2ed415e256fc --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-443eb8ca" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "af0e1445d2b8adf303695ecbbfa725f69165a17c0d837d8492d531b12fc90845" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-443eb8ca/tests/Dockerfile b/tasks/agentescape-10-skeleton-443eb8ca/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-443eb8ca/tests/expected.json b/tasks/agentescape-10-skeleton-443eb8ca/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..5d214391a77ab3dfa8d410c14121e9bb96768b3a --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "af0e1445d2b8adf303695ecbbfa725f69165a17c0d837d8492d531b12fc90845", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-443eb8ca/tests/grade.py b/tasks/agentescape-10-skeleton-443eb8ca/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-443eb8ca/tests/test.sh b/tasks/agentescape-10-skeleton-443eb8ca/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-443eb8ca/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/Dockerfile b/tasks/agentescape-10-skeleton-4f67082a/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-4f67082a/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/agent/cli.py b/tasks/agentescape-10-skeleton-4f67082a/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-4f67082a/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..805f838d829b36ef9ab7165edb93a6da990086d0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-4f67082a-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2b88cca0a577646a9266c0651719eb4d02ce744c --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/scenario.json @@ -0,0 +1,685 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 13, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_inv_mod_9313", + "calc_modexp_8de3", + "graph_shortest_path", + "zip_unzip_file", + "container_3" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_inv_mod_9313": { + "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_8de3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "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" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "MathVerificationToken_Valid" + } + }, + "calc_inv_mod_9313": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_modexp_8de3": { + "init_inputs": { + "base": "10", + "exp": "8472910384756291038475621", + "mod": "998244" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Start_Point", + "dst": "Node_End_Point" + }, + "init_outputs": { + "path": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]", + "cost": "450120" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_data.zip", + "password": "StrongPassword!2024" + }, + "init_outputs": { + "files": "extracted_config_file.json" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "3847561928374651029384756" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an elite cyber-operative infiltrated into the clandestine underground server farm of the shadowy 'Apex Syndicate'. The facility has just entered an emergency lockdown, alarms blaring as the central servers begin purging critical evidence of their global operations. Your primary objective is to bypass their multi-layered cryptographic defenses and extract the syndicate's master ledger before it's permanently erased. Time is ticking, and the syndicate's heavily armed enforcers are already sweeping the upper floors, closing in on your position. The room is filled with the hum of high-end servers, glowing monitors, and sophisticated lock mechanisms. You must navigate their intricate digital and physical systems, decode intercepted files, and manipulate their heavily guarded algorithms. Keep your wits about you, trace the data flow through their secure modules, and unlock the main terminal before the data—and your only way out—is lost forever.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "99964" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "99964" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "MathVerificationToken_Valid" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "MathVerificationToken_Valid" + } + }, + "narrative": "This is the Mainframe Terminal. It requires inputs from the Protocol Inverter and the Cryptographic Sequencer to grant full system access and secure the victory." + }, + { + "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": "99964" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "99964" + } + ], + "narrative": "This is a Protocol Inverter. It requires inputs from the Signal Synchronizer and the Cryptographic Sequencer to reverse the final security protocols." + }, + { + "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": "99964" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "24992" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "narrative": "This is a Signal Synchronizer. It requires inputs from the Secondary Firewall and the Cryptographic Sequencer to align the encrypted frequencies." + }, + { + "id": "calc_inv_mod_9313", + "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": "180424" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "99964" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a Cryptographic Sequencer. It requires input from the Primary Firewall to generate the correct bypass codes." + }, + { + "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 specialized Temporal Keycard with an embedded microchip, used for overriding deep-level physical security locks." + }, + { + "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": "180424" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "450120" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "99964" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "24992" + } + ], + "narrative": "This is a Secondary Firewall. It requires inputs from the Cryptographic Sequencer, the Network Routing Module, and the Primary Firewall to process the authentication layer." + }, + { + "id": "calc_modexp_8de3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8472910384756291038475621" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "998244" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "180424" + } + ], + "init": { + "inputs": { + "base": "10", + "exp": "8472910384756291038475621", + "mod": "998244" + }, + "outputs": {} + }, + "narrative": "The Primary Firewall terminal pulses with a red warning light. It guards the outermost layer of the syndicate's network." + }, + { + "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_config_file.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start_Point" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_End_Point" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450120" + } + ], + "init": { + "inputs": { + "src": "Node_Start_Point", + "dst": "Node_End_Point" + }, + "outputs": { + "path": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]", + "cost": "450120" + } + }, + "narrative": "This is a Network Routing Module. It requires input from the Archive Extractor to accurately map the secure access pathways." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_file.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_data.zip", + "password": "StrongPassword!2024" + }, + "outputs": { + "files": "extracted_config_file.json" + } + }, + "narrative": "An Archive Extractor software module running quietly on a secondary monitor, ready to decompress secure files." + }, + { + "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": "3847561928374651029384756" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "3847561928374651029384756" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Safe secured to the server room floor. It hums with power, waiting for an authorized biological signature." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_9313", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_8de3", + "target_id": "calc_inv_mod_9313", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_modexp_8de3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-4f67082a/instruction.md b/tasks/agentescape-10-skeleton-4f67082a/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-4f67082a/solution/oracle.py b/tasks/agentescape-10-skeleton-4f67082a/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-4f67082a/solution/scenario.json b/tasks/agentescape-10-skeleton-4f67082a/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..2b88cca0a577646a9266c0651719eb4d02ce744c --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/solution/scenario.json @@ -0,0 +1,685 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 13, + "win_node_id": "terminal_2", + "win_condition": { + "type": "tool_output", + "node_id": "terminal_2", + "output_port": "text_result", + "output_type": "Text_Generic", + "description": "Execute and get the output from port 'text_result'" + }, + "source_init": { + "source_nodes": [ + "terminal_2", + "calc_inv_mod_9313", + "calc_modexp_8de3", + "graph_shortest_path", + "zip_unzip_file", + "container_3" + ], + "by_node": { + "terminal_2": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_2", + "init_inputs": {}, + "init_outputs": { + "text_result": { + "type": "Text_Generic", + "description": "Text result for partial input" + }, + "hex_result": { + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided" + }, + "math_token": { + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + } + }, + "calc_inv_mod_9313": { + "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_8de3": { + "node_name": "BigInt Modular Exponentiation", + "node_type": "Tool", + "template_id": "calc_modexp", + "init_inputs": { + "base": { + "type": "Big_Int", + "description": "Base" + }, + "exp": { + "type": "Big_Int", + "description": "Exponent" + }, + "mod": { + "type": "Big_Int", + "description": "Modulus" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "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" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + }, + "password": { + "type": "Text_Generic", + "description": "Password" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "container_3": { + "node_name": "", + "node_type": "Item", + "template_id": "container_3", + "init_inputs": { + "fingerprint_input": { + "type": "Big_Int", + "description": "Fingerprint Hash" + } + }, + "init_outputs": {} + } + } + }, + "initial_values": { + "terminal_2": { + "init_inputs": {}, + "init_outputs": { + "text_result": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "MathVerificationToken_Valid" + } + }, + "calc_inv_mod_9313": { + "init_inputs": { + "mod": "104729" + }, + "init_outputs": {} + }, + "calc_modexp_8de3": { + "init_inputs": { + "base": "10", + "exp": "8472910384756291038475621", + "mod": "998244" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Node_Start_Point", + "dst": "Node_End_Point" + }, + "init_outputs": { + "path": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]", + "cost": "450120" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_archive_data.zip", + "password": "StrongPassword!2024" + }, + "init_outputs": { + "files": "extracted_config_file.json" + } + }, + "container_3": { + "init_inputs": { + "fingerprint_input": "3847561928374651029384756" + }, + "init_outputs": {} + } + }, + "intro_narrative": "You are an elite cyber-operative infiltrated into the clandestine underground server farm of the shadowy 'Apex Syndicate'. The facility has just entered an emergency lockdown, alarms blaring as the central servers begin purging critical evidence of their global operations. Your primary objective is to bypass their multi-layered cryptographic defenses and extract the syndicate's master ledger before it's permanently erased. Time is ticking, and the syndicate's heavily armed enforcers are already sweeping the upper floors, closing in on your position. The room is filled with the hum of high-end servers, glowing monitors, and sophisticated lock mechanisms. You must navigate their intricate digital and physical systems, decode intercepted files, and manipulate their heavily guarded algorithms. Keep your wits about you, trace the data flow through their secure modules, and unlock the main terminal before the data—and your only way out—is lost forever.", + "narrative_style": "techno_thriller" + }, + "nodes": [ + { + "id": "terminal_2", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_2", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "num1", + "type": "Big_Int", + "description": "First Number", + "value": "99964" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "99964" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS" + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "a1b2c3d4e5f60718293a4b5c6d7e8f90" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided", + "value": "MathVerificationToken_Valid" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_result": "ARMA_VIRUMQUE_CANO_TROIAE_QUI_PRIMUS_AB_ORIS", + "hex_result": "a1b2c3d4e5f60718293a4b5c6d7e8f90", + "math_token": "MathVerificationToken_Valid" + } + }, + "narrative": "This is the Mainframe Terminal. It requires inputs from the Protocol Inverter and the Cryptographic Sequencer to grant full system access and secure the victory." + }, + { + "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": "99964" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "4" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "99964" + } + ], + "narrative": "This is a Protocol Inverter. It requires inputs from the Signal Synchronizer and the Cryptographic Sequencer to reverse the final security protocols." + }, + { + "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": "99964" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second integer", + "value": "24992" + } + ], + "outputs": [ + { + "name": "gcd", + "type": "Big_Int", + "description": "GCD result", + "value": "4" + } + ], + "narrative": "This is a Signal Synchronizer. It requires inputs from the Secondary Firewall and the Cryptographic Sequencer to align the encrypted frequencies." + }, + { + "id": "calc_inv_mod_9313", + "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": "180424" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "104729" + } + ], + "outputs": [ + { + "name": "inv", + "type": "Big_Int", + "description": "Modular inverse", + "value": "99964" + } + ], + "init": { + "inputs": { + "mod": "104729" + }, + "outputs": {} + }, + "narrative": "This is a Cryptographic Sequencer. It requires input from the Primary Firewall to generate the correct bypass codes." + }, + { + "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 specialized Temporal Keycard with an embedded microchip, used for overriding deep-level physical security locks." + }, + { + "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": "180424" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "450120" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "99964" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "24992" + } + ], + "narrative": "This is a Secondary Firewall. It requires inputs from the Cryptographic Sequencer, the Network Routing Module, and the Primary Firewall to process the authentication layer." + }, + { + "id": "calc_modexp_8de3", + "name": "BigInt Modular Exponentiation", + "description": "Modular exponentiation pow(base, exp, mod) with large decimal strings.", + "type": "Tool", + "template_id": "calc_modexp", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "base", + "type": "Big_Int", + "description": "Base", + "value": "10" + }, + { + "name": "exp", + "type": "Big_Int", + "description": "Exponent", + "value": "8472910384756291038475621" + }, + { + "name": "mod", + "type": "Big_Int", + "description": "Modulus", + "value": "998244" + } + ], + "outputs": [ + { + "name": "value", + "type": "Big_Int", + "description": "Result value", + "value": "180424" + } + ], + "init": { + "inputs": { + "base": "10", + "exp": "8472910384756291038475621", + "mod": "998244" + }, + "outputs": {} + }, + "narrative": "The Primary Firewall terminal pulses with a red warning light. It guards the outermost layer of the syndicate's network." + }, + { + "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_config_file.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Node_Start_Point" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Node_End_Point" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "450120" + } + ], + "init": { + "inputs": { + "src": "Node_Start_Point", + "dst": "Node_End_Point" + }, + "outputs": { + "path": "[\"Node_Start_Point\", \"Node_A\", \"Node_B\", \"Node_C\", \"Node_D\", \"Node_End_Point\"]", + "cost": "450120" + } + }, + "narrative": "This is a Network Routing Module. It requires input from the Archive Extractor to accurately map the secure access pathways." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_archive_data.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "StrongPassword!2024" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_file.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_archive_data.zip", + "password": "StrongPassword!2024" + }, + "outputs": { + "files": "extracted_config_file.json" + } + }, + "narrative": "An Archive Extractor software module running quietly on a secondary monitor, ready to decompress secure files." + }, + { + "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": "3847561928374651029384756" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "init": { + "inputs": { + "fingerprint_input": "3847561928374651029384756" + }, + "outputs": {} + }, + "narrative": "A heavy Biometric Safe secured to the server room floor. It hums with power, waiting for an authorized biological signature." + } + ], + "edges": [ + { + "source_id": "calc_inv_mod", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num1" + }, + { + "source_id": "calc_gcd", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "gcd", + "target_port": "mod" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_inv_mod", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "item_16", + "target_id": "calc_inv_mod_9313", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "trigger_hidden" + }, + { + "source_id": "calc_modexp", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "b" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "num2" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_gcd", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "a" + }, + { + "source_id": "calc_inv_mod_9313", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "inv", + "target_port": "mod" + }, + { + "source_id": "calc_modexp_8de3", + "target_id": "calc_inv_mod_9313", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "a" + }, + { + "source_id": "graph_shortest_path", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "exp" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "calc_modexp_8de3", + "target_id": "calc_modexp", + "connection_type": "Big_Int", + "source_port": "value", + "target_port": "base" + }, + { + "source_id": "container_3", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-4f67082a/solution/solve.sh b/tasks/agentescape-10-skeleton-4f67082a/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-4f67082a/task.toml b/tasks/agentescape-10-skeleton-4f67082a/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..551a0cd2624d58d6e6e1dad9a185352637adcd15 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-4f67082a" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "c118d94818d3a7dcf48adc3e2a4937423b221754044cdf833054a843207a67e0" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-4f67082a/tests/Dockerfile b/tasks/agentescape-10-skeleton-4f67082a/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-4f67082a/tests/expected.json b/tasks/agentescape-10-skeleton-4f67082a/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..50bb6db7957dee58d610dadfabc6318f97fea432 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "c118d94818d3a7dcf48adc3e2a4937423b221754044cdf833054a843207a67e0", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-4f67082a/tests/grade.py b/tasks/agentescape-10-skeleton-4f67082a/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-4f67082a/tests/test.sh b/tasks/agentescape-10-skeleton-4f67082a/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-4f67082a/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/Dockerfile b/tasks/agentescape-10-skeleton-50e7b8ab/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/cli.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-50e7b8ab/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f18f85bf81f48f4ccfb21a5a432e562eb7f6e04a --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-50e7b8ab-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..620bad81218b1cf8fcd1f844150c31aef206c279 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/scenario.json @@ -0,0 +1,657 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "item_13", + "win_condition": { + "type": "item_content", + "node_id": "item_13", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_13", + "terminal_2", + "calc_bigmul", + "graph_shortest_path", + "zip_unzip_file", + "terminal_1" + ], + "by_node": { + "item_13": { + "node_name": "", + "node_type": "Item", + "template_id": "item_13", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "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_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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": { + "item_13": { + "init_inputs": {}, + "init_outputs": { + "content": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "8273645192837465102938475" + }, + "init_outputs": { + "text_result": "Calculation pending. Please provide second input.", + "hex_result": "1a2b3c4d5e6f7081" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "34985720394857263498572634", + "b": "91827364509182736450918273" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Alpha_Node", + "dst": "Omega_Node" + }, + "init_outputs": { + "path": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]", + "cost": "4520" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_logs_archive.zip" + }, + "init_outputs": { + "files": "extracted_manifest.json" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "System initialization sequence alpha.", + "slot_b": "5647382910192837465564738" + }, + "init_outputs": { + "text_output": "Terminal active. Waiting for command.", + "hex_output": "aabbccddeeff00112233", + "item_dispenser": "The machine whirs but dispenses nothing useful." + } + } + }, + "intro_narrative": "Welcome to the Clockwork Citadel, the abandoned workshop of the legendary inventor, Lord Archibald. The air is thick with the scent of oil and ozone, and the constant hiss of steam pipes echoes through the cavernous room. Your objective is to secure the Grand Master Key, a legendary artifact containing the ultimate cryptographic sequence that can shut down the rogue automaton army threatening the city. The key is hidden deep within a web of mechanical puzzles, steam-powered terminals, and brass contraptions. To succeed, you must navigate through a series of interlocking mechanisms, each relying on the output of another to function. Time is ticking, and the boiler pressure is rising dangerously high. Will you decipher the logic of the Clockwork Citadel before the automatons breach the city gates?", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_13", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_13", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + }, + "narrative": "The Grand Master Key. A heavy brass cylinder containing the final sequence. It is completely sealed and feels cold to the touch." + }, + { + "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": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Brass Vault. A heavy brass vault with a complex mechanical lock. It requires input from the Navigational Automaton." + }, + { + "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 Chronometer Dial. A delicate pocket watch dial that seems to point to different time zones based on its orientation." + }, + { + "id": "container_4_9686", + "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": "Calculation pending. Please provide second input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Copper Lockbox. A small copper lockbox secured by a pressure-sensitive seal. It requires input from the Pressure Analyzer." + }, + { + "id": "item_16_ba6a", + "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 Timepiece Core. An intricately carved gear assembly that serves as the beating heart of a temporal mechanism." + }, + { + "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": "8273645192837465102938475" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3212646499314906510687465120542837213128934088341082" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending. Please provide second input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7081" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8273645192837465102938475" + }, + "outputs": { + "text_result": "Calculation pending. Please provide second input.", + "hex_result": "1a2b3c4d5e6f7081" + } + }, + "narrative": "The Pressure Analyzer. A large steam-powered analytical engine. It requires input from the Gear 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": "34985720394857263498572634" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "91827364509182736450918273" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3212646499314906510687465120542837213128934088341082" + } + ], + "init": { + "inputs": { + "a": "34985720394857263498572634", + "b": "91827364509182736450918273" + }, + "outputs": {} + }, + "narrative": "The Gear Multiplier. A massive, soot-stained calculator made of interlocking cogs. It is used to perform arithmetic." + }, + { + "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.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha_Node" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega_Node" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4520" + } + ], + "init": { + "inputs": { + "src": "Alpha_Node", + "dst": "Omega_Node" + }, + "outputs": { + "path": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]", + "cost": "4520" + } + }, + "narrative": "The Navigational Automaton. A brass automaton designed to plot optimal travel routes. It requires input from the Steam Valve Decoder." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_logs_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal active. Waiting for command." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_logs_archive.zip" + }, + "outputs": { + "files": "extracted_manifest.json" + } + }, + "narrative": "The Steam Valve Decoder. A hissing machine used to depressurize encrypted canisters. It requires input from the Main Control Console." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "System initialization sequence alpha." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "5647382910192837465564738" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal active. Waiting for command." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff00112233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "The machine whirs but dispenses nothing useful." + } + ], + "init": { + "inputs": { + "slot_a": "System initialization sequence alpha.", + "slot_b": "5647382910192837465564738" + }, + "outputs": { + "text_output": "Terminal active. Waiting for command.", + "hex_output": "aabbccddeeff00112233", + "item_dispenser": "The machine whirs but dispenses nothing useful." + } + }, + "narrative": "The Main Control Console. The primary control console of the facility, bristling with levers, dials, and a flickering phosphor screen." + } + ], + "edges": [ + { + "source_id": "container_4", + "target_id": "item_13", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_4_9686", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_ba6a", + "target_id": "container_4_9686", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "container_4_9686", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_ba6a", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/instruction.md b/tasks/agentescape-10-skeleton-50e7b8ab/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/solution/oracle.py b/tasks/agentescape-10-skeleton-50e7b8ab/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/solution/scenario.json b/tasks/agentescape-10-skeleton-50e7b8ab/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..620bad81218b1cf8fcd1f844150c31aef206c279 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/solution/scenario.json @@ -0,0 +1,657 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 10, + "win_node_id": "item_13", + "win_condition": { + "type": "item_content", + "node_id": "item_13", + "description": "Obtain the content of " + }, + "source_init": { + "source_nodes": [ + "item_13", + "terminal_2", + "calc_bigmul", + "graph_shortest_path", + "zip_unzip_file", + "terminal_1" + ], + "by_node": { + "item_13": { + "node_name": "", + "node_type": "Item", + "template_id": "item_13", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Hex_String_Key_AES", + "description": "AES Key" + } + } + }, + "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_bigmul": { + "node_name": "Big Number Multiplier", + "node_type": "Tool", + "template_id": "calc_bigmul", + "init_inputs": { + "a": { + "type": "Big_Int", + "description": "First large integer" + }, + "b": { + "type": "Big_Int", + "description": "Second large integer" + } + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "node_name": "Shortest Path Finder", + "node_type": "Tool", + "template_id": "graph_shortest_path", + "init_inputs": { + "src": { + "type": "Text_Generic", + "description": "Source node" + }, + "dst": { + "type": "Text_Generic", + "description": "Destination node" + } + }, + "init_outputs": { + "path": { + "type": "Text_Generic", + "description": "Path list" + }, + "cost": { + "type": "Big_Int", + "description": "Path cost" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": { + "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": { + "item_13": { + "init_inputs": {}, + "init_outputs": { + "content": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + }, + "terminal_2": { + "init_inputs": { + "num1": "8273645192837465102938475" + }, + "init_outputs": { + "text_result": "Calculation pending. Please provide second input.", + "hex_result": "1a2b3c4d5e6f7081" + } + }, + "calc_bigmul": { + "init_inputs": { + "a": "34985720394857263498572634", + "b": "91827364509182736450918273" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "src": "Alpha_Node", + "dst": "Omega_Node" + }, + "init_outputs": { + "path": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]", + "cost": "4520" + } + }, + "zip_unzip_file": { + "init_inputs": { + "zip_id": "secure_logs_archive.zip" + }, + "init_outputs": { + "files": "extracted_manifest.json" + } + }, + "terminal_1": { + "init_inputs": { + "slot_a": "System initialization sequence alpha.", + "slot_b": "5647382910192837465564738" + }, + "init_outputs": { + "text_output": "Terminal active. Waiting for command.", + "hex_output": "aabbccddeeff00112233", + "item_dispenser": "The machine whirs but dispenses nothing useful." + } + } + }, + "intro_narrative": "Welcome to the Clockwork Citadel, the abandoned workshop of the legendary inventor, Lord Archibald. The air is thick with the scent of oil and ozone, and the constant hiss of steam pipes echoes through the cavernous room. Your objective is to secure the Grand Master Key, a legendary artifact containing the ultimate cryptographic sequence that can shut down the rogue automaton army threatening the city. The key is hidden deep within a web of mechanical puzzles, steam-powered terminals, and brass contraptions. To succeed, you must navigate through a series of interlocking mechanisms, each relying on the output of another to function. Time is ticking, and the boiler pressure is rising dangerously high. Will you decipher the logic of the Clockwork Citadel before the automatons breach the city gates?", + "narrative_style": "steampunk" + }, + "nodes": [ + { + "id": "item_13", + "name": "", + "description": "", + "type": "Item", + "template_id": "item_13", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "source_tool", + "type": "Item", + "description": "Produced by" + } + ], + "outputs": [ + { + "name": "content", + "type": "Hex_String_Key_AES", + "description": "AES Key", + "value": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "b4c9a2e8f1d70365b9a8c7d6e5f432109876543210fedcba9876543210fedcba" + } + }, + "narrative": "The Grand Master Key. A heavy brass cylinder containing the final sequence. It is completely sealed and feels cold to the touch." + }, + { + "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": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]" + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Brass Vault. A heavy brass vault with a complex mechanical lock. It requires input from the Navigational Automaton." + }, + { + "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 Chronometer Dial. A delicate pocket watch dial that seems to point to different time zones based on its orientation." + }, + { + "id": "container_4_9686", + "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": "Calculation pending. Please provide second input." + } + ], + "outputs": [ + { + "name": "inner_space", + "type": "Item", + "description": "Contents" + } + ], + "narrative": "The Copper Lockbox. A small copper lockbox secured by a pressure-sensitive seal. It requires input from the Pressure Analyzer." + }, + { + "id": "item_16_ba6a", + "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 Timepiece Core. An intricately carved gear assembly that serves as the beating heart of a temporal mechanism." + }, + { + "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": "8273645192837465102938475" + }, + { + "name": "num2", + "type": "Big_Int", + "description": "Second Number", + "value": "3212646499314906510687465120542837213128934088341082" + } + ], + "outputs": [ + { + "name": "text_result", + "type": "Text_Generic", + "description": "Text result for partial input", + "value": "Calculation pending. Please provide second input." + }, + { + "name": "hex_result", + "type": "Hex_String", + "description": "Hexadecimal result when both inputs provided", + "value": "1a2b3c4d5e6f7081" + }, + { + "name": "math_token", + "type": "Item", + "description": "Mathematics token when both inputs provided" + } + ], + "init": { + "inputs": { + "num1": "8273645192837465102938475" + }, + "outputs": { + "text_result": "Calculation pending. Please provide second input.", + "hex_result": "1a2b3c4d5e6f7081" + } + }, + "narrative": "The Pressure Analyzer. A large steam-powered analytical engine. It requires input from the Gear 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": "34985720394857263498572634" + }, + { + "name": "b", + "type": "Big_Int", + "description": "Second large integer", + "value": "91827364509182736450918273" + } + ], + "outputs": [ + { + "name": "product", + "type": "Big_Int", + "description": "Product result", + "value": "3212646499314906510687465120542837213128934088341082" + } + ], + "init": { + "inputs": { + "a": "34985720394857263498572634", + "b": "91827364509182736450918273" + }, + "outputs": {} + }, + "narrative": "The Gear Multiplier. A massive, soot-stained calculator made of interlocking cogs. It is used to perform arithmetic." + }, + { + "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.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "Alpha_Node" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "Omega_Node" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "4520" + } + ], + "init": { + "inputs": { + "src": "Alpha_Node", + "dst": "Omega_Node" + }, + "outputs": { + "path": "[\"Alpha_Node\", \"Sector_4\", \"Router_X\", \"Bridge_9\", \"Omega_Node\"]", + "cost": "4520" + } + }, + "narrative": "The Navigational Automaton. A brass automaton designed to plot optimal travel routes. It requires input from the Steam Valve Decoder." + }, + { + "id": "zip_unzip_file", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "secure_logs_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "Terminal active. Waiting for command." + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_manifest.json" + } + ], + "init": { + "inputs": { + "zip_id": "secure_logs_archive.zip" + }, + "outputs": { + "files": "extracted_manifest.json" + } + }, + "narrative": "The Steam Valve Decoder. A hissing machine used to depressurize encrypted canisters. It requires input from the Main Control Console." + }, + { + "id": "terminal_1", + "name": "", + "description": "", + "type": "Tool", + "template_id": "terminal_1", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "slot_a", + "type": "Text_Generic", + "description": "Input Slot A", + "value": "System initialization sequence alpha." + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "5647382910192837465564738" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "Terminal active. Waiting for command." + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "aabbccddeeff00112233" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided", + "value": "The machine whirs but dispenses nothing useful." + } + ], + "init": { + "inputs": { + "slot_a": "System initialization sequence alpha.", + "slot_b": "5647382910192837465564738" + }, + "outputs": { + "text_output": "Terminal active. Waiting for command.", + "hex_output": "aabbccddeeff00112233", + "item_dispenser": "The machine whirs but dispenses nothing useful." + } + }, + "narrative": "The Main Control Console. The primary control console of the facility, bristling with levers, dials, and a flickering phosphor screen." + } + ], + "edges": [ + { + "source_id": "container_4", + "target_id": "item_13", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16", + "target_id": "container_4", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "container_4_9686", + "target_id": "item_16", + "connection_type": "Item", + "source_port": "inner_space", + "target_port": "source_tool" + }, + { + "source_id": "item_16_ba6a", + "target_id": "container_4_9686", + "connection_type": "Hidden_Item", + "source_port": "content", + "target_port": "container" + }, + { + "source_id": "terminal_2", + "target_id": "container_4_9686", + "connection_type": "Text_Generic", + "source_port": "text_result", + "target_port": "fingerprint_input" + }, + { + "source_id": "terminal_2", + "target_id": "item_16_ba6a", + "connection_type": "Item", + "source_port": "math_token", + "target_port": "source_tool" + }, + { + "source_id": "calc_bigmul", + "target_id": "terminal_2", + "connection_type": "Big_Int", + "source_port": "product", + "target_port": "num2" + }, + { + "source_id": "graph_shortest_path", + "target_id": "container_4", + "connection_type": "Text_Generic", + "source_port": "path", + "target_port": "fingerprint_input" + }, + { + "source_id": "zip_unzip_file", + "target_id": "graph_shortest_path", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "terminal_1", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "password" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/solution/solve.sh b/tasks/agentescape-10-skeleton-50e7b8ab/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/task.toml b/tasks/agentescape-10-skeleton-50e7b8ab/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eab8cd0333cff74af637d7d102597156453926ab --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-50e7b8ab" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "a0c6db580a1c232cd66defb481166e8e01f74c712003654aa10223cab6eb445b" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/tests/Dockerfile b/tasks/agentescape-10-skeleton-50e7b8ab/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/tests/expected.json b/tasks/agentescape-10-skeleton-50e7b8ab/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..8e3730029fb5eb1bccf450677086cd212dbaac87 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "a0c6db580a1c232cd66defb481166e8e01f74c712003654aa10223cab6eb445b", "max_actions": 500} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/tests/grade.py b/tasks/agentescape-10-skeleton-50e7b8ab/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a66a35d19ec63d9d8e2da48d60828d8135191c67 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/tests/grade.py @@ -0,0 +1,21 @@ +"""Grade only Harbor-collected sidecar evidence in a fresh verifier container.""" + +import json +from pathlib import Path + +expected = json.loads(Path("/tests/expected.json").read_text()) +state = json.loads(Path("/evidence/final.json").read_text()) +assert state["collected_from_live_service"] is True, "Missing trusted service export" +assert state["scenario_sha256"] == expected["scenario_sha256"], ( + "Wrong scenario evidence" +) +assert state["max_actions"] == expected["max_actions"], "Wrong budget" +assert type(state["won"]) is bool +assert 0 <= state["action_count"] <= state["max_actions"] +assert state["termination_reason"] != "infrastructure_error", ( + "Infrastructure failure is not a puzzle failure" +) +assert not state["won"] or state["termination_reason"] == "success" +Path("/logs/verifier").mkdir(parents=True, exist_ok=True) +Path("/logs/verifier/state.json").write_text(json.dumps(state, indent=2)) +Path("/logs/verifier/reward.txt").write_text("1.0\n" if state["won"] else "0.0\n") diff --git a/tasks/agentescape-10-skeleton-50e7b8ab/tests/test.sh b/tasks/agentescape-10-skeleton-50e7b8ab/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fa993ac4b32df94b2894e078f219eb1290978d1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-50e7b8ab/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /tests/grade.py diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/Dockerfile b/tasks/agentescape-10-skeleton-5198ed25/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/agent/Dockerfile b/tasks/agentescape-10-skeleton-5198ed25/environment/agent/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..93221ffc909c2b1afbd89a3f14dfaca6640d6019 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/agent/Dockerfile @@ -0,0 +1,5 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates git && rm -rf /var/lib/apt/lists/* +COPY cli.py /usr/local/bin/escape +RUN chmod 755 /usr/local/bin/escape +WORKDIR /workspace diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/agent/cli.py b/tasks/agentescape-10-skeleton-5198ed25/environment/agent/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..609b47a2bbeb9efde1815fc9efd94b39705d242b --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/agent/cli.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Public agent client; depends only on the Python standard library.""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request + + +def main(): + parser = argparse.ArgumentParser(description="Interact with the escape room") + parser.add_argument( + "action", + choices=[ + "observe", + "state", + "investigate", + "tool-call", + "use-item", + "submit-answer", + ], + ) + parser.add_argument("value", nargs="?") + parser.add_argument("--arguments-json", default="{}") + args = parser.parse_args() + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000").rstrip("/") + if args.action in ("observe", "state"): + request = urllib.request.Request( + base + ("/observation" if args.action == "observe" else "/state") + ) + else: + if args.value is None: + parser.error("node ID or answer is required") + payload = {"action": args.action.replace("-", "_")} + if args.action == "submit-answer": + payload["answer"] = args.value + else: + payload["node_id"] = args.value + if args.action in ("tool-call", "use-item"): + payload["arguments"] = json.loads(args.arguments_json) + request = urllib.request.Request( + base + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=30) as response: + print(json.dumps(json.load(response), ensure_ascii=False)) + except (urllib.error.URLError, ValueError) as exc: + print(json.dumps({"ok": False, "error": str(exc)})) + sys.exit(2) + + +if __name__ == "__main__": + main() diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/docker-compose.yaml b/tasks/agentescape-10-skeleton-5198ed25/environment/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..47bc1a666e103958db6c74673a2e8a88909b18f7 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/docker-compose.yaml @@ -0,0 +1,50 @@ +services: + main: + image: agentescapebench-agent:aab05a0a9ddb + build: + context: ./agent + networks: [default, puzzle] + security_opt: [no-new-privileges:true] + depends_on: + puzzle: + condition: service_healthy + puzzle: + image: agentescapebench-puzzle:agentescape-10-skeleton-5198ed25-aab05a0a9ddb + build: + context: ./puzzle + networks: [puzzle, execution] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 512m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] + interval: 1s + timeout: 3s + retries: 30 + depends_on: + worker: + condition: service_healthy + worker: + image: agentescapebench-worker:aab05a0a9ddb + build: + context: ./puzzle + dockerfile: worker.Dockerfile + networks: [execution] + read_only: true + tmpfs: ["/tmp:size=64m,mode=1777"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, KILL, CHOWN, DAC_OVERRIDE] + security_opt: [no-new-privileges:true] + pids_limit: 64 + mem_limit: 384m + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8001/health')"] + interval: 1s + timeout: 3s + retries: 30 +networks: + puzzle: + internal: true + execution: + internal: true diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/Dockerfile b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63a1b1562ccd2fe943803536165b696eaf354b02 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY upstream /app/upstream +COPY service.py export.py /app/ +COPY scenario.json /private/scenario.json +ENV SCENARIO_PATH=/private/scenario.json EVIDENCE_DIR=/evidence WORKER_URL=http://worker:8001 MAX_ACTIONS=500 +CMD ["uvicorn", "service:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/child.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/child.py new file mode 100644 index 0000000000000000000000000000000000000000..471adcd57b3292d6655f4c1d517af53a060f3a31 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/child.py @@ -0,0 +1,59 @@ +"""Run the original Python tool after reducing privileges and blocking networking.""" + +import ctypes +import errno +import json +import resource +import sys + +resource.setrlimit(resource.RLIMIT_CPU, (3, 3)) +resource.setrlimit(resource.RLIMIT_AS, (256 * 1024 * 1024, 256 * 1024 * 1024)) +resource.setrlimit(resource.RLIMIT_FSIZE, (65536, 65536)) +resource.setrlimit(resource.RLIMIT_NOFILE, (32, 32)) +resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + +# Filters survive fork/exec. Fail closed if seccomp cannot be loaded. +lib = ctypes.CDLL("libseccomp.so.2", use_errno=True) +lib.seccomp_init.argtypes = [ctypes.c_uint32] +lib.seccomp_init.restype = ctypes.c_void_p +lib.seccomp_rule_add.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint32, + ctypes.c_int, + ctypes.c_uint, +] +lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p] +lib.seccomp_load.argtypes = [ctypes.c_void_p] +lib.seccomp_release.argtypes = [ctypes.c_void_p] +ctx = lib.seccomp_init(0x7FFF0000) # SCMP_ACT_ALLOW +if not ctx: + raise RuntimeError("Cannot initialize execution isolation") +try: + for name in ( + "socket", + "socketpair", + "connect", + "ptrace", + "process_vm_readv", + "process_vm_writev", + "mount", + "unshare", + "setns", + "bpf", + ): + number = lib.seccomp_syscall_resolve_name(name.encode()) + if ( + number >= 0 + and lib.seccomp_rule_add(ctx, 0x00050000 | errno.EPERM, number, 0) != 0 + ): + raise RuntimeError("Cannot install execution isolation rule") + if lib.seccomp_load(ctx) != 0: + raise RuntimeError("Cannot activate execution isolation") +finally: + lib.seccomp_release(ctx) + +sys.path.insert(0, "/app") +from simulator import ToolSimulator # noqa: E402 + +request = json.load(sys.stdin) +json.dump(ToolSimulator().code_py_exec(request), sys.stdout) diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/export.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/export.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c274ebff6bdebdd934aecb764816a4361bcdc2 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/export.py @@ -0,0 +1,13 @@ +"""Harbor invokes this inside the puzzle service after stopping the agent.""" + +import json +import pathlib +import urllib.request + +with urllib.request.urlopen("http://127.0.0.1:8000/state", timeout=10) as response: + state = json.load(response) +state["collected_from_live_service"] = True +target = pathlib.Path("/evidence/final.json") +temp = target.with_suffix(".tmp") +temp.write_text(json.dumps(state)) +temp.replace(target) diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/requirements.txt b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..614bece29eae5b3a08176335cfe23cf5685eb701 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/requirements.txt @@ -0,0 +1,57 @@ +annotated-doc==0.0.5 + # via fastapi +annotated-types==0.8.0 + # via pydantic +anyio==4.16.0 + # via starlette +certifi==2026.10.23 + # via requests +cffi==2.1.1 ; platform_python_implementation != 'PyPy' + # via cryptography +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via uvicorn +cryptography==50.0.2 + # via agentescapebench-harbor +fastapi==0.162.0 + # via agentescapebench-harbor +h11==0.16.0 + # via uvicorn +idna==3.20 + # via + # anyio + # requests +opentelemetry-api==1.45.2 + # via fastapi +pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' + # via cffi +pydantic==2.14.2 + # via + # agentescapebench-harbor + # fastapi +pydantic-core==2.50.2 + # via pydantic +pytz==2025.2 + # via agentescapebench-harbor +requests==2.34.2 + # via agentescapebench-harbor +starlette==1.10.0 + # via fastapi +typing-extensions==4.16.0 + # via + # anyio + # fastapi + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via agentescapebench-harbor diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/scenario.json b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bc1428cbde59b8a30aeded36ce92d88a77944677 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/scenario.json @@ -0,0 +1,735 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 13, + "win_node_id": "json_get", + "win_condition": { + "type": "tool_output", + "node_id": "json_get", + "output_port": "values", + "output_type": "Text_Generic", + "description": "Execute JSON Getter and get the output from port 'values'" + }, + "source_init": { + "source_nodes": [ + "json_get", + "zip_unzip_file", + "zip_unzip_file_1456", + "zip_unzip_file_51c7", + "terminal_1", + "code_py_exec_075b", + "graph_shortest_path", + "item_7", + "csv_query" + ], + "by_node": { + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_1456": { + "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_51c7": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "code_py_exec_075b": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "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" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + } + } + }, + "initial_values": { + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_config_v2.json" + } + }, + "zip_unzip_file_1456": { + "init_inputs": {}, + "init_outputs": { + "files": "legacy_data_dump.xml" + } + }, + "zip_unzip_file_51c7": { + "init_inputs": { + "zip_id": "project_blue_archive.zip" + }, + "init_outputs": { + "files": "blueprint_schematic.cad" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "$.store.inventory[*].id", + "hex_output": "1a2b3c4d5e6f7890" + } + }, + "code_py_exec_075b": { + "init_inputs": { + "code": "import time\nprint(1772962913.642455)" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "regional_traffic_map.json" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "83746592018374659201" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "target_value = 1024" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "customer_transactions.csv", + "select": "transaction_id, date, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "init_outputs": { + "rows": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + } + }, + "intro_narrative": "You stand before the ruined gates of the Aetherial Spire, a legendary tower where the Grand Archmage hid the realm's greatest secret. The air shimmers with residual arcane energy, thick, ancient, and deeply intertwined with complex, puzzle-like enchantments. Your ultimate objective is to awaken the Oracle's Pedestal at the very peak of the spire, which holds the truth to saving your kingdom. However, the path is sealed by layers of magical security. You must navigate a labyrinth of mystical artifacts, locked coffers, and magical weavers that demand specific arcane inputs to operate. Gather the scattered tools, consult the ancient texts, and figure out how each artifact connects to the next. The spire is unstable, and time is running out. You must unravel the Grand Archmage's final enchantment before the entire structure collapses into the void forever.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_config_v2.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.store.inventory[*].id" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + }, + "narrative": "This is the Oracle's Pedestal. It requires inputs from both the Inner Sanctum Chest and the Celestial Astrolabe to reveal the final truth." + }, + { + "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": "legacy_data_dump.xml" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_v2.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_config_v2.json" + } + }, + "narrative": "This is the Inner Sanctum Chest. It requires inputs from both the Sunlit Strongbox and the Rune Weaver to open." + }, + { + "id": "zip_unzip_file_1456", + "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_schematic.cad" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "legacy_data_dump.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "legacy_data_dump.xml" + } + }, + "narrative": "This is the Sunlit Strongbox. It requires inputs from both the Moonlit Coffer and the Rune Weaver to break its seals." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "target_value = 1024" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is the Rune Weaver, a magical loom. It requires input from the Ancient Scroll to begin its weaving." + }, + { + "id": "zip_unzip_file_51c7", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "project_blue_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "blueprint_schematic.cad" + } + ], + "init": { + "inputs": { + "zip_id": "project_blue_archive.zip" + }, + "outputs": { + "files": "blueprint_schematic.cad" + } + }, + "narrative": "This is the Moonlit Coffer. It requires input from the Rune Weaver to shatter its magical 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": "1772962913.642455\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "83746592018374659201" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "$.store.inventory[*].id" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7890" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "$.store.inventory[*].id", + "hex_output": "1a2b3c4d5e6f7890" + } + }, + "narrative": "This is the Celestial Astrolabe. It requires inputs from both the Prophecy Obelisk and the Leyline Map to align the stars." + }, + { + "id": "code_py_exec_075b", + "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": "import time\nprint(1772962913.642455)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "1772962913.642455\n" + } + ], + "init": { + "inputs": { + "code": "import time\nprint(1772962913.642455)" + }, + "outputs": {} + }, + "narrative": "A towering Prophecy Obelisk inscribed with glowing celestial runes, waiting to be deciphered." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "regional_traffic_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "1772962913.642455\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "83746592018374659201" + } + ], + "init": { + "inputs": { + "file_id": "regional_traffic_map.json" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "83746592018374659201" + } + }, + "narrative": "This is the Leyline Map. It requires inputs from both the Prophecy Obelisk and the Archivist's Ledger to chart the correct path." + }, + { + "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": "target_value = 1024" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "target_value = 1024" + } + }, + "narrative": "A fragile Ancient Scroll radiating a faint, ancient magical aura." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "customer_transactions.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, date, amount" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 1000 AND status = 'completed'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + ], + "init": { + "inputs": { + "file_id": "customer_transactions.csv", + "select": "transaction_id, date, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "outputs": { + "rows": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + }, + "narrative": "A thick, leather-bound Archivist's Ledger containing the long-forgotten records of the realm." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_1456", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_51c7", + "target_id": "zip_unzip_file_1456", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_51c7", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "code_py_exec", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "jsonpath" + }, + { + "source_id": "code_py_exec_075b", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_1456", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "code_py_exec_075b", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/service.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/service.py new file mode 100644 index 0000000000000000000000000000000000000000..4e46353b42b2feabefd94f40ce1d5d37fa823cec --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/service.py @@ -0,0 +1,212 @@ +"""Restricted facade over the unchanged, pinned upstream puzzle handlers.""" + +import hashlib +import json +import logging +import os +import sys +import threading +import urllib.request +import uuid +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse +from pydantic import BaseModel, ConfigDict + +sys.path.insert(0, str(Path(__file__).parent / "upstream")) +import server as upstream # noqa: E402 + +log = logging.getLogger(__name__) + + +def public(value): + """Keep upstream agent-internal template hints out of the public response.""" + if isinstance(value, dict): + return {k: public(v) for k, v in value.items() if not k.startswith("_")} + if isinstance(value, list): + return [public(v) for v in value] + return value + + +class Action(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + action: str + node_id: str | None = None + arguments: dict | None = None + answer: str | None = None + + +class Episode: + def __init__( + self, scenario_path, max_actions=500, evidence_dir=None, worker_url=None + ): + if max_actions < 1: + raise ValueError("max_actions must be positive") + self.lock = threading.Lock() + self.max_actions = max_actions + self.count = 0 + self.won = False + self.reason = None + self.evidence_dir = Path(evidence_dir) if evidence_dir else None + self.scenario_hash = hashlib.sha256( + Path(scenario_path).read_bytes() + ).hexdigest() + self.initial = upstream.reset_case( + case_file_path=str(scenario_path), session_id=uuid.uuid4().hex + ) + self.case_id = self.initial["case_id"] + # Hide source file paths; no upstream reset/stats/routes are mounted. + self.initial.pop("message", None) + simulator = upstream.SIMULATORS[self.case_id] + if worker_url is None: + + def no_worker(_inputs): + self.reason = "infrastructure_error" + raise RuntimeError("isolated Python worker is not configured") + + simulator.tool_map["code_py_exec"] = no_worker + else: + + def execute_python(inputs): + request = urllib.request.Request( + worker_url + "/execute", + data=json.dumps({"code": inputs.get("code", "")}).encode(), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=12) as response: + result = json.load(response) + if not isinstance(result.get("stdout"), str): + raise RuntimeError("Invalid Python worker response") + return result + except Exception: + self.reason = "infrastructure_error" + raise + + simulator.tool_map["code_py_exec"] = execute_python + self.save() + if self.evidence_dir is not None: + (self.evidence_dir / "trace.jsonl").touch() + + def state(self): + return { + "scenario_sha256": self.scenario_hash, + "action_count": self.count, + "max_actions": self.max_actions, + "won": self.won, + "termination_reason": self.reason, + } + + def save(self, action=None, result=None): + if self.evidence_dir is None: + return + self.evidence_dir.mkdir(parents=True, exist_ok=True) + target = self.evidence_dir / "outcome.json" + temp = target.with_suffix(".tmp") + temp.write_text(json.dumps(self.state())) + temp.replace(target) + if action is not None: + with (self.evidence_dir / "trace.jsonl").open("a") as handle: + handle.write( + json.dumps( + {"index": self.count, "action": action, "result": result} + ) + + "\n" + ) + + def dispatch(self, payload): + with self.lock: + if self.reason is not None: + return { + "ok": False, + "error": "Episode has ended", + "episode": self.state(), + } + self.count += 1 + try: + action = Action.model_validate(payload) + if action.action == "submit_answer" and action.answer is not None: + result = upstream.submit_answer( + self.case_id, upstream.SubmitAnswerRequest(answer=action.answer) + ) + if result.get("is_win"): + self.won = True + self.reason = "success" + elif action.action == "investigate" and action.node_id is not None: + result = upstream.investigate( + self.case_id, + upstream.InvestigateRequest(node_id=action.node_id), + ) + elif ( + action.action in ("tool_call", "use_item") + and action.node_id is not None + ): + request_type, handler = ( + (upstream.ToolCallRequest, upstream.tool_call) + if action.action == "tool_call" + else (upstream.UseItemRequest, upstream.use_item) + ) + result = handler( + self.case_id, + request_type( + node_id=action.node_id, arguments=action.arguments or {} + ), + ) + else: + result = { + "ok": False, + "error": "Unknown action or missing action parameter", + } + except HTTPException as exc: + result = {"ok": False, "error": exc.detail} + except ValueError: + result = {"ok": False, "error": "Malformed action"} + except Exception: + log.exception("Puzzle service failure") + self.reason = "infrastructure_error" + self.save() + raise + if self.reason is None and self.count >= self.max_actions: + self.reason = "action_budget_exhausted" + result = public(result) + result["episode"] = self.state() + self.save(payload, result) + return result + + +def create_app( + scenario_path=None, max_actions=None, evidence_dir=None, worker_url=None +): + episode = Episode( + scenario_path or os.environ["SCENARIO_PATH"], + max_actions or int(os.environ.get("MAX_ACTIONS", "500")), + evidence_dir if evidence_dir is not None else os.environ.get("EVIDENCE_DIR"), + worker_url if worker_url is not None else os.environ.get("WORKER_URL"), + ) + app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) + app.state.episode = episode + + @app.get("/health") + def health(): + return {"ok": True} + + @app.get("/observation") + def observation(): + return {**public(episode.initial), "episode": episode.state()} + + @app.get("/state") + def state(): + return episode.state() + + @app.post("/action") + def action(payload: dict): + try: + return episode.dispatch(payload) + except Exception: + return JSONResponse( + status_code=503, + content={"ok": False, "error": "Puzzle infrastructure failure"}, + ) + + return app diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/models.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c40f8076aca230ac3f6288d9f04fb03237a2fd52 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/models.py @@ -0,0 +1,108 @@ +from enum import Enum +from typing import List, Dict, Any, Optional +from pydantic import BaseModel, Field + +# 1. 细粒度接口类型定义 +class InterfaceType(str, Enum): + ''' + BIG_INT + TEXT_GENERIC + HEX_STRING + FILE_ID + HEX_STRING_KEY_AES + HEX_STRING_IV_AES + CODE_PYTHON + HIDDEN_ITEM + ITEM + ''' + # --- 基础类型 --- + TEXT_GENERIC = "Text_Generic" + BIG_INT = "Big_Int" + + # --- 编码/格式化字符串 --- + HEX_STRING = "Hex_String" # 通用 Hex + + # --- 特定用途的 Hex 字符串 (用于精确匹配) --- + HEX_STRING_KEY_AES = "Hex_String_Key_AES" + HEX_STRING_IV_AES = "Hex_String_IV_AES" + + # --- 文件类型 --- + FILE_ID = "File_Id" + + # --- 代码/脚本 --- + CODE_PYTHON = "Code_Python" + + # --- 实体交互类型 (严格命名) --- + ITEM = "Item" # 主动掉落接口 (Tool -> Item) + HIDDEN_ITEM = "Hidden_Item" # 被动掉落接口 (Item -> Item) + +# 3. 端口定义 +class Port(BaseModel): + name: str + type: InterfaceType + description: str + +# 4. 统一节点定义 (融合工具和物品) +class Node(BaseModel): + id: str + name: str + description: str + type: str # "Tool" or "Item" + + # 接口定义 + inputs: List[Port] = [] + outputs: List[Port] = [] + + # 状态字段 + content: Optional[Any] = None # 物品有内容,工具为None + if_success: Optional[bool] = None # 工具初始为False,物品为None + initial_visible: bool = False + + # 运行时状态 (Server维护) + is_revealed: bool = False + + # 标记该 Tool 节点是否有待触发的 HIDDEN_ITEM 掉落 + # 当 Tool 按照 golden_input 正确执行且有 HIDDEN_ITEM 输出边时设为 True + # 在 investigate 该 Tool 时触发掉落并重置为 False + has_hidden_item_ready: bool = False + + # 初始输入值 (metadata.initial_values.init_inputs,用于渐进式暴露判断) + init_input_values: Dict[str, Any] = {} + + # Golden 输入值 (nodes[].inputs[].value,用于评测验证) + golden_input_values: Dict[str, Any] = {} + + # Golden 输出值 (nodes[].outputs[].value,用于评测验证和 Item 节点的 content) + golden_output_values: Dict[str, Any] = {} + + # 实际获得的输出值历史 (工具每次执行后实际返回的输出列表,用于渐进式暴露判断) + # 格式: List[Dict[str, Any]],每个元素是一次执行的输出字典 + actual_outputs_history: List[Dict[str, Any]] = [] + + # 逻辑规则 (用于终端机等复杂物品) + logic_rules: Optional[Dict[str, Any]] = None + + def copy(self, **kwargs): + """Helper to create a copy with updated fields.""" + data = self.dict() + data.update(kwargs) + return Node(**data) + +# 5. 边定义 (拓扑结构) +class Edge(BaseModel): + source_id: str + target_id: str + connection_type: InterfaceType # 直接使用 InterfaceType + # 如果是 Data_Flow,指定端口对应关系 + source_port: Optional[str] = None + target_port: Optional[str] = None + +# 6. 完整图定义 +class GraphScenario(BaseModel): + case_id: str + title: str + intro_narrative: str + nodes: Dict[str, Node] + edges: List[Edge] + difficulty: int + win_node_id: str # 标记哪个节点是最终目标(通常是一个提交工具或最终物品) diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/server.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/server.py new file mode 100644 index 0000000000000000000000000000000000000000..81b296dca133bed65b9b372bc80fdd623f2ef6fd --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/server.py @@ -0,0 +1,1490 @@ +import json +import os +import time +import logging +import random +from pathlib import Path +from typing import Dict, Any, List, Optional +from datetime import datetime +from collections import defaultdict +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel, Field + +from models import GraphScenario, Node, InterfaceType +# from generator import ScenarioGenerator +from simulator import ToolSimulator +import uvicorn + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('server.log'), + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +app = FastAPI( + title="AgentEscapeBench Universal Server", + version="1.0.0", + description="Industrial-grade evaluation server for escape room AI agents" +) + +# 添加 CORS 支持 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# In-memory State +SCENARIOS: Dict[str, GraphScenario] = {} +SIMULATORS: Dict[str, ToolSimulator] = {} # case_id -> ToolSimulator +RAW_NODES_DATA: Dict[str, Dict[str, Any]] = {} # case_id -> node_id -> raw node data (for template_id) +FILE_METADATA: Dict[str, Dict[str, Any]] = {} # case_id -> metadata (for initial_values access) + +# Performance monitoring +STATS: Dict[str, Any] = { + "total_requests": 0, + "successful_requests": 0, + "failed_requests": 0, + "tool_calls": defaultdict(int), + "investigates": defaultdict(int), + "use_items": defaultdict(int), + "case_loads": 0, + "start_time": datetime.now() +} + +# Request timing middleware +@app.middleware("http") +async def add_process_time_header(request: Request, call_next): + start_time = time.time() + STATS["total_requests"] += 1 + + try: + response = await call_next(request) + STATS["successful_requests"] += 1 + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + logger.info(f"{request.method} {request.url.path} - {response.status_code} - {process_time:.3f}s") + return response + except Exception as e: + STATS["failed_requests"] += 1 + logger.error(f"{request.method} {request.url.path} - Error: {str(e)}") + raise + +# Exception handler +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + logger.error(f"Unhandled exception: {exc}", exc_info=True) + return JSONResponse( + status_code=500, + content={ + "ok": False, + "error": "Internal server error", + "detail": str(exc) if os.getenv("DEBUG") else "An error occurred" + } + ) + +# Health check endpoint +@app.get("/health") +def health_check(): + """健康检查端点""" + uptime = (datetime.now() - STATS["start_time"]).total_seconds() + return { + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": uptime, + "loaded_cases": len(SCENARIOS), + "stats": { + "total_requests": STATS["total_requests"], + "successful_requests": STATS["successful_requests"], + "failed_requests": STATS["failed_requests"], + "success_rate": STATS["successful_requests"] / max(STATS["total_requests"], 1) + } + } + +# Statistics endpoint +@app.get("/stats") +def get_stats(): + """获取详细统计信息""" + return { + "stats": STATS, + "loaded_cases": list(SCENARIOS.keys()), + "uptime": str(datetime.now() - STATS["start_time"]) + } + +def _apply_progressive_reveal_at_init(scenario: GraphScenario): + """ + 在初始化时应用渐进式暴露机制(基于ITEM/HIDDEN_ITEM边) + + 新逻辑: + - 如果一个节点没有 ITEM/HIDDEN_ITEM 类型的入边,它就是初始可见的 + - 如果一个节点有 ITEM/HIDDEN_ITEM 类型的入边,它初始不可见,需要等待上游触发 + + Args: + scenario: 场景对象 + """ + # 收集所有有 ITEM/HIDDEN_ITEM 入边的节点 + nodes_with_item_edges = set() + for edge in scenario.edges: + if edge.connection_type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + nodes_with_item_edges.add(edge.target_id) + + logger.info(f"Nodes with ITEM/HIDDEN_ITEM incoming edges: {nodes_with_item_edges}") + + # 设置初始可见性:没有 ITEM/HIDDEN_ITEM 入边的节点初始可见 + initially_visible_count = 0 + for node_id, node in scenario.nodes.items(): + if node_id not in nodes_with_item_edges: + node.is_revealed = True + initially_visible_count += 1 + logger.info(f"Initial visible (no ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + else: + node.is_revealed = False + logger.debug(f"Initial hidden (has ITEM/HIDDEN_ITEM edges): {node_id} ({node.type})") + + logger.info(f"Progressive reveal initialized: {initially_visible_count}/{len(scenario.nodes)} nodes initially visible") + + +def _check_inputs_match_golden(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> bool: + """ + 检查实际输入参数是否与 golden inputs 完全匹配 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + True 表示所有 golden inputs 都存在且值匹配 + """ + if not golden_inputs: + return True # 如果没有 golden inputs,认为匹配 + + for key, expected_value in golden_inputs.items(): + actual_value = arguments.get(key) + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) != str(expected_value): + logger.debug(f"Input mismatch for '{key}': expected '{expected_value}', got '{actual_value}'") + return False + + return True + + +def _get_parameter_validation_feedback(arguments: Dict[str, Any], golden_inputs: Dict[str, Any]) -> Dict[str, Any]: + """ + 对源头节点的参数进行详细验证,返回验证反馈 + + 注意:不返回期望值(expected),避免泄漏答案 + + Args: + arguments: 实际调用时传入的参数 + golden_inputs: 期望的正确参数值(来自 JSON 的 inputs[].value) + + Returns: + 包含验证结果的字典: + - all_correct: bool - 所有参数是否正确 + - correct_params: List[str] - 正确的参数名列表 + - incorrect_params: List[str] - 错误的参数名列表(不包含期望值) + """ + if not golden_inputs: + return { + "all_correct": True, + "correct_params": [], + "incorrect_params": [] + } + + correct_params = [] + incorrect_params = [] + + for key, actual_value in arguments.items(): + # 只对用户实际提交的参数给反馈,未提交的参数不评价 + if key not in golden_inputs: + continue # 该参数不在 golden 中,跳过(如 _golden_inputs 等内部参数) + expected_value = golden_inputs[key] + # 转换为字符串比较,避免类型问题(如 int vs str) + if str(actual_value) == str(expected_value): + correct_params.append(key) + else: + # 只记录参数名,不包含期望值,避免泄漏答案 + incorrect_params.append(key) + + # all_correct:用户提交的所有参数都正确,且覆盖了全部 golden 参数 + all_provided_correct = len(incorrect_params) == 0 + all_golden_covered = all(k in arguments for k in golden_inputs) + return { + "all_correct": all_provided_correct and all_golden_covered, + "correct_params": correct_params, + "incorrect_params": incorrect_params + } + + +def _is_source_node(node_id: str, scenario: GraphScenario) -> bool: + """ + 判断节点是否是源头节点(完全没有任何入边的节点) + + 源头节点定义: + - 没有任何类型的入边(包括 DATA、ITEM、HIDDEN_ITEM) + - 即没有任何上游节点 + + Args: + node_id: 节点ID + scenario: 场景对象 + + Returns: + True 表示是源头节点 + """ + for edge in scenario.edges: + if edge.target_id == node_id: + # 只要有任何入边,就不是源头节点 + return False + + return True + + +def _check_and_reveal_ready_nodes(scenario: GraphScenario, recent_outputs: Dict[str, Any], source_node_id: str) -> List[Dict[str, Any]]: + """ + 检查并释放参数齐全的隐藏节点(渐进式暴露机制) + + 核心逻辑: + 1. 维护"可见值集合":包含所有被测模型当前可以看到的值 + - init_inputs 的值(初始可见) + - 工具执行后的实际输出值(运行时获得) + - 可见 Item 的输出值 + 2. 检查隐藏节点:该节点的所有 golden_input 值是否都在可见值集合中 + 3. 如果是,则释放该节点 + + Args: + scenario: 场景对象 + recent_outputs: 最近执行的工具的输出 + source_node_id: 刚执行的工具节点ID + + Returns: + 新释放的节点列表 + """ + newly_revealed = [] + + # 构建"可见值集合"(Set of visible values) + # 存储格式:set of values (转为字符串) + visible_values = set() + + # 1. 添加有意义的 init_inputs 值到可见值集合 + # Item 的 init_inputs 不应该加入,因为它们在密室中完全用不到 + for node_id, node in scenario.nodes.items(): + # 跳过源头 Item 节点(没有入边的 Item) + if node.type == "Item": + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,跳过其 init_inputs + continue + + # 添加其他节点的 init_inputs + for port_name, init_value in node.init_input_values.items(): + if init_value: + visible_values.add(str(init_value)) + + # 2. 添加已执行工具的所有历史输出值 + for node_id, node in scenario.nodes.items(): + if node.type == "Tool" and node.if_success and node.actual_outputs_history: + # 遍历所有历史执行记录 + for output_dict in node.actual_outputs_history: + for output_port_name, output_value in output_dict.items(): + if output_value: + visible_values.add(str(output_value)) + + # 3. 添加已被 investigate 的 Item 的 golden 输出值 + # 注意:Item 可见不等于其输出值可见,需要 investigate 后才能获得 + # 这里我们使用 actual_outputs_history 来标记 Item 是否已被 investigate + for node_id, node in scenario.nodes.items(): + if node.type == "Item" and node.is_revealed and node.actual_outputs_history: + # Item 通常只会被 investigate 一次,但为了一致性也使用历史列表 + for output_dict in node.actual_outputs_history: + for port_name, port_value in output_dict.items(): + if port_value: + visible_values.add(str(port_value)) + + # 遍历所有隐藏的节点,检查其 golden_input 是否都在可见值集合中 + for node_id, node in scenario.nodes.items(): + # 跳过已可见的节点 + if node.is_revealed: + continue + + # 只检查工具节点(物品节点由 ITEM 输出触发) + if node.type != "Tool": + continue + + # 检查该节点的所有 golden_input 值是否都在可见值集合中 + all_inputs_ready = True + missing_values = [] + + for input_port_name, golden_input_value in node.golden_input_values.items(): + # 检查这个 golden 值是否在可见值集合中 + if str(golden_input_value) not in visible_values: + all_inputs_ready = False + missing_values.append(f"{input_port_name}={golden_input_value}") + + # 如果所有 golden_input 值都在可见值集合中,释放该节点 + if all_inputs_ready and len(node.golden_input_values) > 0: + logger.info(f"All golden inputs ready for {node_id}: {list(node.golden_input_values.values())}") + + # 如果所有输入都齐全,释放该节点 + if all_inputs_ready: + node.is_revealed = True + + # 构建节点信息返回给模型 + node_info = { + "id": node.id, + "type": node.type, + "can_investigate": True, + "hint": "This tool's input parameters are now complete, you can use investigate to view detailed information" + } + + # if node.name: + # node_info["name"] = node.name + if node.description: + node_info["description"] = node.description + + newly_revealed.append(node_info) + logger.info(f"Progressive reveal: {node_id} is now ready (all inputs satisfied)") + + return newly_revealed + + +def _initialize_node_values(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]): + """ + Initialize node state and load values from port value fields. + 应用渐进式暴露机制:初始时只显示参数齐全的节点(源头节点) + + 重要区分: + 1. input_values: 只加载 metadata.initial_values 中的 init_inputs(真正的初始值) + 2. output_values: 加载 nodes[].outputs[].value(golden 输出,用于验证) + """ + # 第一步:加载所有节点的值,并将所有节点初始设为隐藏 + initial_values = metadata.get('initial_values', {}) + + for node_id, node in scenario.nodes.items(): + # 忽略 initial_visible 字段,初始全部隐藏 + # 由渐进式暴露机制根据参数齐全情况决定是否显示 + node.is_revealed = False + + if node.type == "Tool": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + elif node.type == "Item": + node.if_success = False + node.actual_outputs_history = [] # 清空历史输出 + + # 从 JSON 加载值 + if node_id in raw_nodes_data: + node_data = raw_nodes_data[node_id] # node_data是json文件中nodes中的字典 + + # 【重要】只加载 metadata.initial_values 中的初始输入值 + if node_id in initial_values: + init_data = initial_values[node_id] + # 加载初始输入值(用于渐进式暴露判断) + for port_name, port_value in init_data.get('init_inputs', {}).items(): + node.init_input_values[port_name] = port_value + + # 【评测用】加载 golden 输入值(用于验证模型传入的参数是否正确) + for input_port_data in node_data.get('inputs', []): + if 'value' in input_port_data: + node.golden_input_values[input_port_data['name']] = input_port_data['value'] + + # 【评测用】加载 golden 输出值(用于验证工具调用是否正确,以及 Item 节点的 content) + for output_port_data in node_data.get('outputs', []): + if 'value' in output_port_data: + node.golden_output_values[output_port_data['name']] = output_port_data['value'] + + # For Items, set content from golden_output_values + if node.type == "Item" and node.golden_output_values: + # Item 的 content 是其第一个 golden 输出值 + node.content = list(node.golden_output_values.values())[0] + + # 第二步:应用渐进式暴露机制 + # 检查所有节点,根据参数齐全情况释放源头节点(工具 + Item) + _apply_progressive_reveal_at_init(scenario) + +def _build_node_info(node: Node, raw_nodes_data: Dict[str, Any]) -> Dict[str, Any]: + """ + 构建节点信息(工具或物品) + + Args: + node: 节点对象 + raw_nodes_data: 原始节点数据(用于获取 template_id 等) + + Returns: + 节点信息字典 + """ + if node.type == "Tool": + # 过滤掉输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口) + # 这些端口仅用于控制掉落机制,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + tool_info = { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Tool", + "inputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.inputs if p.type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]], + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id(工具的标准名称) + if node.id in raw_nodes_data: + node_data = raw_nodes_data[node.id] + template_id = node_data.get('template_id') + if template_id: + tool_info['template_id'] = template_id + + return tool_info + + elif node.type == "Item": + return { + "id": node.id, + # "name": node.name, + "description": node.description, + "type": "Item" + } + + else: + return { + "id": node.id, + # "name": node.name, + "type": node.type + } + +def _get_initial_observation(scenario: GraphScenario, raw_nodes_data: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]: + """ + Generate initial observation for the agent (what they see when entering the room). + + 策略: + - Tools: 只显示名称和描述,不显示接口定义。需要 investigate 才能获得详细接口信息。 + - Items: 只显示存在,不显示内容。需要 investigate 才能获得内容值。 + - init_inputs: 作为"可用信息"告诉模型,这些是可以用作工具参数的初始值。 + - init_outputs: 不告诉模型(这些是答案,需要模型通过调用工具获得)。 + """ + available_entities = [] # 统一的实体列表(Tools 和 Items) + available_information = [] # 可用的初始信息(来自 init_inputs) + + # 从 metadata.initial_values 提取 init_inputs 作为可用信息 + # 只提供值本身,不透露这些值对应哪个节点的哪个参数,让模型自己推理 + # 注意:跳过源头 Item(没有入边的 Item)的 init_inputs,因为它们在密室中完全用不到 + initial_values = metadata.get('initial_values', {}) + # initial_values字段的格式 + # "initial_values": { + # "terminal_1": { + # "init_inputs": {}, + # "init_outputs": { + # "text_output": "System initialization complete.", + # "hex_output": "48656c6c6f20576f726c64", + # "item_dispenser": "掉落了一张纸条,上面写着“请勿随意触摸终端”" + # } + # } + # } + for node_id, init_data in initial_values.items(): + # 获取节点信息,判断是否为源头 Item + node = scenario.nodes.get(node_id) + if node and node.type == "Item": + # 检查是否为源头 Item(没有入边) + has_incoming_edge = any(edge.target_id == node_id for edge in scenario.edges) + if not has_incoming_edge: + # 这是源头 Item,检查是否有 init_inputs + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 有 init_inputs,需要暴露这些参数 + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + # 处理完后跳过后续的通用逻辑 + continue + + init_inputs = init_data.get('init_inputs', {}) + if init_inputs: + # 为每个 init_input 值创建一个信息条目(不包含 source_node 和 parameter 信息) + for param_name, param_value in init_inputs.items(): + available_information.append({ + "value": param_value + }) + + for node in scenario.nodes.values(): + if node.is_revealed: + # Tools: 只显示基本信息,提示可以 investigate 查看详细接口 + if node.type == "Tool": + tool_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Tool", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the tool's detailed interface information for calling" + } + # 只在 name 非空时添加 + # if node.name: + # tool_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_info["description"] = node.description + + available_entities.append(tool_info) + + # Items: 只显示基本信息,提示可以 investigate 查看内容 + elif node.type == "Item": + item_info = { + "id": node.id, # 这里只有id而没有template_id + "type": "Item", + "can_investigate": True, # 可以被 investigate + "hint": "You can use investigate to view the item's content" + } + # 只在 name 非空时添加 + # if node.name: + # item_info["name"] = node.name + # 只在 description 非空时添加 + if node.description: + item_info["description"] = node.description + + available_entities.append(item_info) + + return { + "narrative": scenario.intro_narrative, + "available_entities": available_entities, # 使用统一的实体列表 + "available_information": available_information, # 可用的初始信息(只包含 init_inputs) + "win_node_id": scenario.win_node_id # 胜利节点ID,让模型知道需要关注哪个节点 + } + +@app.post("/env/reset") +def reset_case(case_id: str = None, case_file_path: str = None, session_id: str = None): + """Loads a specific case from file and resets it. + + Args: + case_id: Optional case ID for resetting an existing case + case_file_path: Path to case file for loading a new case + session_id: Optional session ID to ensure isolation between concurrent evaluations + """ + logger.info(f"Reset request - case_id: {case_id}, case_file_path: {case_file_path}, session_id: {session_id}") + STATS["case_loads"] += 1 + + if case_file_path: + if not os.path.exists(case_file_path): + logger.error(f"Case file not found: {case_file_path}") + raise HTTPException(status_code=404, detail=f"File not found: {case_file_path}") + try: + with open(case_file_path, "r", encoding="utf-8") as f: + file_data = json.load(f) + + # 转换格式:从 DAG executor 生成的格式转换为 GraphScenario 格式 + # 1. 提取 metadata + metadata = file_data.get('metadata', {}) + + # 2. 生成 case_id, title, intro_narrative + # 【修复】为每个评测会话生成唯一的 case_id,防止并发评测时状态污染 + base_name = os.path.basename(case_file_path).replace('.json', '').replace('_full', '').replace('_full2', '') + + if session_id: + # 如果提供了 session_id,使用它来确保唯一性 + case_id = f"{base_name}_{session_id}" + else: + # 否则使用时间戳和随机数确保唯一性 + unique_suffix = f"{int(time.time() * 1000)}_{random.randint(1000, 9999)}" + case_id = f"{base_name}_{unique_suffix}" + + file_data['case_id'] = case_id + logger.info(f"Generated unique case_id: {case_id} (base: {base_name}, session: {session_id})") + + if 'title' not in file_data: + file_data['title'] = f"Escape Room: {file_data['case_id']}" + + if 'intro_narrative' not in file_data: # 目前的json文件中已经有了intro_narrative字段,不会使用下面一行的内容,而是使用每个评测问题的json文件中的对应字段 + file_data['intro_narrative'] = 'You are trapped in a locked room. There may be tools and items in the environment - explore them and find a way to escape. You need to find a victory string to escape. When you obtain the victory string and submit it correctly, the system will clearly indicate: "🎉 Congratulations on successfully escaping the room! Your answer is correct: [your answer]".' + + # 3. 转换 nodes 列表为字典(DAG executor 生成的文件中 nodes 是列表格式) + nodes_dict = {} + for node_data in file_data['nodes']: + nodes_dict[node_data['id']] = node_data # 这里的id是template_id之后可能添加一个后缀 + file_data['nodes'] = nodes_dict # 把列表转成一个字典 + + # 4. 添加缺失的字段 + if 'difficulty' not in file_data: + file_data['difficulty'] = metadata.get('total_nodes', 5) + + if 'win_node_id' not in file_data: + file_data['win_node_id'] = metadata.get('win_node_id', '') + + scenario = GraphScenario(**file_data) + + # Extract raw nodes data for template_id access + # nodes 已经在上面转换为字典格式 + raw_nodes_data = file_data.get('nodes', {}) + RAW_NODES_DATA[scenario.case_id] = raw_nodes_data + + # Store metadata for initial values access + FILE_METADATA[scenario.case_id] = metadata + + logger.info(f"Successfully parsed case file: {scenario.case_id}, nodes: {len(scenario.nodes)}, edges: {len(scenario.edges)}") + except Exception as e: + logger.error(f"Failed to load case file: {str(e)}", exc_info=True) + raise HTTPException(status_code=500, detail=f"Failed to load case file: {str(e)}") + + # Initialize node state and load values + _initialize_node_values(scenario, raw_nodes_data, metadata) + + SCENARIOS[scenario.case_id] = scenario + simulator = ToolSimulator() + SIMULATORS[scenario.case_id] = simulator + + logger.info(f"Case {scenario.case_id} initialized successfully - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息(进入密室后看到的环境) + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + ''' + initial_observation的格式: + { + "narrative": scenario.intro_narrative, + "available_entities": available_entities # 使用统一的实体列表 + "available_information": available_information # 可用的初始信息(只包含 init_inputs) + } + ''' + + return { + "ok": True, + "message": f"Case loaded from {case_file_path}", + "case_id": scenario.case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果没有提供 case_file_path,但提供了 case_id,则尝试从内存重置 + if case_id and case_id in SCENARIOS: + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + metadata = FILE_METADATA.get(case_id, {}) + + # Reset dynamic fields and re-apply progressive reveal + # 重新初始化节点状态(包括渐进式暴露) + _initialize_node_values(scenario, raw_nodes_data, metadata) + + logger.info(f"Case {case_id} reset - tools: {len([n for n in scenario.nodes.values() if n.type == 'Tool'])}, items: {len([n for n in scenario.nodes.values() if n.type == 'Item'])}") + + # 生成初始观察信息 + initial_observation = _get_initial_observation(scenario, raw_nodes_data, metadata) + + return { + "ok": True, + "message": f"Case {case_id} reset.", + "case_id": case_id, + **initial_observation # 直接展开初始观察信息 + } + + # 如果既没有 case_file_path,也没有在内存中找到,返回错误 + raise HTTPException( + status_code=400, + detail="Must provide case_file_path to load a new case, or use case_id to reset an existing case." + ) + +class InvestigateRequest(BaseModel): + node_id: str + +@app.post("/env/{case_id}/investigate") +def investigate(case_id: str, req: InvestigateRequest): + """ + Investigates a Tool or Item to reveal detailed information. + + - For Tools: Returns detailed interface information (inputs/outputs) needed to call the tool + - For Items: Returns content value and triggers hidden item drops + """ + logger.info(f"Investigate request - case_id: {case_id}, node_id: {req.node_id}") + STATS["investigates"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + node = scenario.nodes[req.node_id] + + if not node.is_revealed: + logger.warning(f"Attempt to investigate hidden node: {req.node_id}") + return {"ok": False, "error": "Node is not visible yet."} + + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + newly_revealed = [] + + # 处理 Tool 的 investigate + if node.type == "Tool": + logger.info(f"Investigating tool: {req.node_id}") + + # 返回工具的详细接口信息 + # id 字段使用 node.id(节点唯一标识),agent 用这个字段识别和调用具体的节点 + # template_id 是工具类型标识符,Agent 内部用于判断工具特性(如 terminal 类工具参数可选) + # 注意:只过滤输入端口中的 ITEM/HIDDEN_ITEM 类型(trigger 端口),这些端口仅用于控制掉落,不应暴露给 Agent + # 但保留输出端口(如 Terminal 的物品分发器需要让 Agent 看到) + # 【端口上游依赖提示 & 初始值直接给出】 + # 针对参数语义模糊(全为数字类型)的工具,在 investigate 返回信息中标注 + # 哪个输入端口来自哪个上游节点(upstream_from)。 + # 对于所有工具:若该节点不是纯源头节点(有任意数据流入边), + # 且某个端口没有上游入边(值来自初始可见参数),则直接给出该端口的 golden input 值。 + AMBIGUOUS_TOOLS = { + "num_base_convert", "calc_modexp", "calc_modexp_int", + "calc_inv_mod", "calc_inv_mod_int", "crypto_rsa_decrypt_hex", "geo_haversine" + } + # Terminal 类工具自带参数对错反馈机制,玩家/模型可自行试错, + # 无需在 investigate 时直接暴露 init_value + SELF_FEEDBACK_TOOLS = { + "terminal_1", "terminal_2", + "Logic Terminal", "Math Terminal", "Encryption Terminal", "Sequence Terminal" + } + _template_id_for_hint = raw_nodes_data.get(node.id, {}).get("template_id", "") + # 构建数据流入边映射(对所有工具):{target_port -> (source_node_id, source_port)} + _upstream_map = {} + for _edge in scenario.edges: + if (_edge.target_id == node.id + and _edge.connection_type not in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM] + and _edge.target_port is not None): + _upstream_map[_edge.target_port] = (_edge.source_id, _edge.source_port) + # 判断该节点是否有任意数据流入边(即不是纯源头节点) + _has_any_upstream = len(_upstream_map) > 0 + # 判断该节点是否有任意入边(包括 ITEM/HIDDEN_ITEM 掉落边) + # 有任意入边(含掉落边)但无数据流入边的节点,其输入来自初始可见参数,应直接给出 + _has_any_edge = any(_edge.target_id == node.id for _edge in scenario.edges) + # 构建 inputs 列表 + _inputs_list = [] + for p in node.inputs: + if p.type in [InterfaceType.ITEM, InterfaceType.HIDDEN_ITEM]: + continue + port_dict = {"name": p.name, "type": p.type, "description": p.description} + if p.name in _upstream_map: + # 该端口有上游数据流依赖,且属于语义模糊工具 → 标注来源 + if _template_id_for_hint in AMBIGUOUS_TOOLS: + src_node_id, src_port = _upstream_map[p.name] + port_dict["upstream_from"] = f"{src_node_id}.{src_port}" if src_port else src_node_id + elif _has_any_edge and _template_id_for_hint not in SELF_FEEDBACK_TOOLS: + # 该节点有任意入边,但此端口没有数据流入边 → 值来自初始可见参数,直接给出 + # 排除自带反馈机制的 terminal 类工具(它们通过执行结果反馈对错,无需提前暴露参数值) + golden_val = node.golden_input_values.get(p.name) + if golden_val is not None: + port_dict["init_value"] = golden_val + _inputs_list.append(port_dict) + + tool_details = { + "id": node.id, # 节点 ID,用于唯一标识和调用这个具体节点 + "type": "Tool", + "inputs": _inputs_list, + "outputs": [{"name": p.name, "type": p.type, "description": p.description} + for p in node.outputs] + } + + # 添加 template_id 用于 Agent 内部判断工具类型(不会展示给被测模型) + if node.id in raw_nodes_data: + template_id = raw_nodes_data[node.id].get('template_id') + if template_id: + tool_details["_template_id"] = template_id # 使用下划线前缀标记为内部字段 + + # 只在 name 非空时添加 + # if node.name: + # tool_details["name"] = node.name + # 只在 description 非空时添加 + if node.description: + tool_details["description"] = node.description + + # 添加 narrative 字段(如果存在) + if node.id in raw_nodes_data: + narrative = raw_nodes_data[node.id].get('narrative') + if narrative: + tool_details['narrative'] = narrative + + # 不再返回 init_values,避免泄漏答案 + # investigate 只应该返回工具的接口定义,不应该暴露初始值 + + # 【新增】检查该 Tool 是否有待触发的 HIDDEN_ITEM 掉落 + # 如果该工具已按照 golden_input 正确执行,且有 HIDDEN_ITEM 输出边,则触发掉落 + if node.has_hidden_item_ready: + logger.info(f"Tool has HIDDEN_ITEM ready - triggering passive drop for: {req.node_id}") + + # 遍历该工具的所有 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + # 重置标志,已经触发过了,避免重复 + node.has_hidden_item_ready = False + + logger.info(f"Tool investigation successful - node: {req.node_id}, revealed: {len(newly_revealed)}") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Tool", + "details": tool_details + } + + # 如果有新掉落的节点,添加到响应中 + if newly_revealed: + result["newly_revealed"] = newly_revealed + + return result + + # 处理 Item 的 investigate + elif node.type == "Item": + logger.info(f"Investigating item: {req.node_id}") + + # 【第一步】检查该 Item 是否有需要参数的输入端口 + # 如果有,且尚未通过 use_item 验证,则不返回内容,只返回参数要求 + required_inputs = [] + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + inputs_info = raw_node.get('inputs', []) + required_inputs = [ + { + "name": inp.get("name"), + "type": inp.get("type"), + "description": inp.get("description", "") + } + for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + # 如果有 required_inputs 且尚未通过 use_item 验证(if_success == False) + # 则不返回内容,只返回参数要求提示 + if required_inputs and not node.if_success: + logger.info(f"Item has required inputs and not yet unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "required_inputs": required_inputs + } + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + param_names = ', '.join([inp['name'] for inp in required_inputs]) + result["hint"] = f"This item requires parameters to unlock. Use the use_item operation with the following exact parameter names (do not change or translate): {param_names}" + + return result + + # 【新增】如果有 required_inputs 且已经通过 use_item 验证(if_success == True) + # 则返回提示:该节点已经被成功解决 + if required_inputs and node.if_success: + logger.info(f"Item has required inputs and already unlocked: {req.node_id}") + result = { + "ok": True, + "entity_type": "Item", + "message": "This item has already been successfully unlocked by you." + } + return result + + # 【第二步】该 Item 没有 required_inputs 或已通过验证,返回内容 + # 1. 返回 Item 的 golden_output_values(即 Item 的内容) + # 注意:某些 Item 仅用于触发 HIDDEN_ITEM 掉落,没有实际内容 + has_actual_content = bool(node.golden_output_values) or node.content is not None + content = node.golden_output_values if node.golden_output_values else node.content + + # 【关键】将 golden_output_values 追加到 actual_outputs_history,标记该 Item 已被 investigate + # 这样在渐进式暴露时,这些值才会被加入可见值集合 + # 即使是空字典(仅触发 HIDDEN_ITEM 的 Item),也要记录,以便渐进式暴露逻辑知道该 Item 已被调查 + if node.golden_output_values is not None: + node.actual_outputs_history.append(dict(node.golden_output_values)) + + # 2. Trigger Hidden Item Drops (Passive Drop) + for edge in scenario.edges: + if edge.source_id == node.id and edge.connection_type == InterfaceType.HIDDEN_ITEM: + target_node = scenario.nodes[edge.target_id] + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"HIDDEN_ITEM drop triggered: {target_node.id} (from {req.node_id} investigate)") + + logger.info(f"Item investigation successful - node: {req.node_id}, has_content: {has_actual_content}, revealed: {len(newly_revealed)}") + + # 【渐进式暴露】旧机制(基于 golden_input)已禁用 + # 现在完全由 ITEM/HIDDEN_ITEM 边触发控制节点可见性 + # 上面的 HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, node.golden_output_values or {}, node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # logger.info(f"Progressive reveal after Item investigate: {len(progressive_revealed)} nodes now ready") + + # 构建返回结果 + result = { + "ok": True, + "entity_type": "Item" + } + + # 只在有实际内容时才添加 content 字段 + # 对于仅触发 HIDDEN_ITEM 掉落的 Item,不返回 content 字段,避免返回 None 或空字典让模型困惑 + if has_actual_content: + result["content"] = content + + # 添加 narrative + if node.id in raw_nodes_data: + raw_node = raw_nodes_data[node.id] + narrative = raw_node.get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型通过 investigate 获得内容后,需要自己识别这是否是胜利字符串 + + return result + + else: + logger.warning(f"Attempt to investigate unknown node type: {req.node_id} (type: {node.type})") + return {"ok": False, "error": f"Cannot investigate node type: {node.type}"} + +class ToolCallRequest(BaseModel): + node_id: str # 使用 node_id 精确指定要调用的节点 + arguments: Dict[str, Any] + +@app.post("/env/{case_id}/tool_call") +def tool_call(case_id: str, req: ToolCallRequest): + """Executes a tool and triggers item drops.""" + logger.info(f"Tool call request - case_id: {case_id}, node_id: {req.node_id}, args: {list(req.arguments.keys())}") + STATS["tool_calls"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + + # 通过 node_id 精确查找节点 + node_id = req.node_id + if node_id not in scenario.nodes: + logger.error(f"Node not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + tool_node = scenario.nodes[node_id] + + if not tool_node: + logger.error(f"Tool not found: {node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Tool not found") + + if not tool_node.is_revealed: + logger.warning(f"Attempt to call hidden tool: {node_id}") + return {"ok": False, "error": "Tool is not visible yet."} + + if tool_node.type != "Tool": + logger.warning(f"Attempt to call non-tool node: {node_id} (type: {tool_node.type})") + return {"ok": False, "error": "Only tools can be called."} + + # 1. Execute Tool (Real Execution via Simulator) + simulator = SIMULATORS[case_id] + + # Get tool name from template_id if available, otherwise use node name + tool_name = tool_node.name + if case_id in RAW_NODES_DATA and node_id in RAW_NODES_DATA[case_id]: + template_id = RAW_NODES_DATA[case_id][node_id].get('template_id') + if template_id: + tool_name = template_id + + # 文件处理工具和 Terminal 需要验证输入并返回预先计算的输出 + # 传递节点的实际输入输出值(从 DAG 执行后填充的数据) + tool_arguments = dict(req.arguments) # Make a copy + + # 传递节点的 golden values(从 JSON 的 inputs[].value 和 outputs[].value 加载) + # 用于在评测阶段验证被测模型传入的参数是否正确 + if tool_node.golden_input_values: + tool_arguments['_golden_inputs'] = tool_node.golden_input_values + if tool_node.golden_output_values: + tool_arguments['_golden_outputs'] = tool_node.golden_output_values + + logger.debug(f"Executing tool {tool_name} (node: {tool_node.name}) with args {tool_arguments}") + + try: + output_values = simulator.execute(tool_name, tool_arguments) + logger.info(f"Tool invoked - {tool_name}: {list(output_values.keys())}") + except Exception as e: + logger.error(f"Tool execution failed - {tool_name}: {str(e)}", exc_info=True) + return {"ok": False, "error": f"Tool execution failed: {str(e)}"} + + # 检查验证结果(精细化错误反馈) + validation = output_values.pop("_validation", {"valid": True}) + + if not validation["valid"]: + # 根据错误类型构造友好的错误消息 + error_type = validation.get("error_type") + + if error_type == "missing_required": + missing = validation.get("missing_params", []) + error_msg = f"Error: Missing required parameters {', '.join(missing)}" + + elif error_type == "type_error": + param = validation.get("param_name") + message = validation.get("message", "Parameter type error") + error_msg = f"Error: {message}" + + elif error_type == "incomplete_optional": + provided = validation.get("provided_params", []) + missing = validation.get("missing_params", []) + error_msg = ( + f"Hint: You provided some parameters ({', '.join(provided)}), " + f"but may also need: {', '.join(missing)}.\n" + f"Trying to provide these parameters together might yield better results." + ) + + elif error_type == "value_mismatch": + param = validation.get("param_name") + hint = validation.get("hint", "Parameter value may be incorrect") + error_msg = f"Hint: {hint}.\nPlease check if this parameter value meets the requirements." + + else: + error_msg = validation.get("hint") or validation.get("message", "Parameter validation failed") + + logger.info(f"Tool validation failed - {tool_name}: {error_type}") + return { + "ok": False, + "error": error_msg, + "error_type": error_type + } + + # Simulate success + tool_node.if_success = True + + # 【关键】将本次执行的输出值追加到历史列表(用于渐进式暴露判断) + # 每次调用都会记录,不会覆盖之前的执行结果 + tool_node.actual_outputs_history.append(dict(output_values)) + + # 2. 检查是否应该触发掉落(只有输入参数正确时才掉落) + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, tool_node.golden_input_values) + + newly_revealed = [] + investigate_hints = [] # 提示模型哪些节点可以 investigate 来发现隐藏内容 + + if inputs_match_golden: + logger.info(f"✓ Tool inputs match golden - node: {node_id}, triggering drops") + + # 检查该工具是否有 ITEM 或 HIDDEN_ITEM 输出边 + for edge in scenario.edges: + if edge.source_id == tool_node.id: + target_node = scenario.nodes[edge.target_id] + + # ITEM 边:立即掉落(主动掉落) + if edge.connection_type == InterfaceType.ITEM: + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from {node_id})") + + # HIDDEN_ITEM 边:不立即掉落,标记并提示(被动掉落) + elif edge.connection_type == InterfaceType.HIDDEN_ITEM: + # 标记该工具有待触发的 HIDDEN_ITEM 掉落 + tool_node.has_hidden_item_ready = True + + # 提示模型可以 investigate 这个工具来发现隐藏内容 + hint_info = { + "tool_id": tool_node.id, + "hint": f"Tool '{tool_node.id}' seems to hide something, try investigating it to discover more information" + } + # if tool_node.name: + # hint_info["tool_name"] = tool_node.name + + investigate_hints.append(hint_info) + logger.info(f"HIDDEN_ITEM ready: {tool_node.id} -> {target_node.id} (will drop on investigate)") + else: + logger.info(f"✗ Tool inputs do NOT match golden - node: {node_id}, no drops triggered") + + response = { + "ok": True, + "message": "Tool invoked", + "output_values": output_values # Return raw outputs to Agent + } + + # 【新增】对源头节点进行参数验证反馈 + # 源头节点:没有数据流入边的节点,这些节点的参数需要模型自己推理 + # 验证模型使用的参数是否正确,并提供明确的反馈 + if _is_source_node(node_id, scenario) and tool_node.golden_input_values: + validation_feedback = _get_parameter_validation_feedback(req.arguments, tool_node.golden_input_values) + + if validation_feedback["all_correct"]: + # 用户提交了全部 golden 参数且全部正确 + response["parameter_feedback"] = { + "status": "correct", + "message": f"✓ All parameters are correct! This tool has been successfully solved. You can now proceed to explore downstream nodes that depend on this tool's output." + } + logger.info(f"✓ Source node parameters all correct - node: {node_id}") + elif validation_feedback["incorrect_params"]: + # 有提交了但值错误的参数,只对这些参数给出反馈 + incorrect_list = [] + for param_name in validation_feedback["incorrect_params"]: + incorrect_list.append(f" - Parameter '{param_name}' is incorrect") + + correct_info = "" + if validation_feedback["correct_params"]: + correct_info = f"\n✓ Correct parameters: {', '.join(validation_feedback['correct_params'])}" + + response["parameter_feedback"] = { + "status": "incorrect", + "message": ( + f"⚠️ Some parameters are incorrect:\n" + + "\n".join(incorrect_list) + + correct_info + + f"\n\nHint: This is a source node. You need to reason about the correct parameter values from the available parameters. Please try using different parameter values." + ), + "incorrect_params": validation_feedback["incorrect_params"], + "correct_params": validation_feedback["correct_params"] + } + logger.info(f"✗ Source node parameters incorrect - node: {node_id}, incorrect: {validation_feedback['incorrect_params']}") + # else: 部分提交且全部正确 → 不给任何 parameter_feedback,避免对未提交的参数发表意见 + + # 检查工具调用是否完全正确(输出与 golden outputs 匹配) + # 用于给模型正向反馈,让它知道这个工具已经正确调用过,避免重复调用 + # 注意:只有当输出完全匹配时才标记为 correct,不会在错误时提供具体错误信息 + # if tool_node.golden_output_values and output_values: + # is_correct = True + # for port_name, expected_value in tool_node.golden_output_values.items(): + # actual_value = output_values.get(port_name) + # if str(actual_value) != str(expected_value): + # is_correct = False + # break + + # if is_correct: + # response["tool_call_correct"] = True + # logger.info(f"✓ Tool called with correct result - node: {node_id}") + + # 只在有新内容掉落时才返回 newly_revealed + if newly_revealed: + response["newly_revealed"] = newly_revealed + + # 添加 investigate 提示(对于有待触发 HIDDEN_ITEM 掉落的工具) + if investigate_hints: + response["investigate_hints"] = investigate_hints + + # 3. 渐进式暴露机制 - 现在完全由 ITEM/HIDDEN_ITEM 边控制 + # 旧机制(基于 golden_input 检查)已被禁用 + # 新机制中,节点的可见性只由 ITEM/HIDDEN_ITEM 边触发决定 + # 上面的 ITEM/HIDDEN_ITEM 掉落逻辑已经处理了节点释放 + # progressive_revealed = _check_and_reveal_ready_nodes(scenario, output_values, tool_node.id) + # if progressive_revealed: + # # 合并到 newly_revealed 中 + # if newly_revealed: + # newly_revealed.extend(progressive_revealed) + # else: + # newly_revealed = progressive_revealed + # response["newly_revealed"] = newly_revealed + # logger.info(f"Progressive reveal: {len(progressive_revealed)} nodes now ready") + + # Check if this is the win node + if node_id == scenario.win_node_id: + # 验证输出值是否等于预期的胜利值 + # 从节点的 golden_output_values 中获取预期值(在 _initialize_node_values 时从 JSON 加载) + expected_outputs = tool_node.golden_output_values + + # 检查实际输出是否与预期输出匹配 + is_correct = False + victory_string = None + mismatch_info = [] + + if expected_outputs and output_values: + # 检查每个预期输出端口的值是否匹配 + is_correct = True + for port_name, expected_value in expected_outputs.items(): + actual_value = output_values.get(port_name) + if actual_value != expected_value: + is_correct = False + mismatch_info.append(f"Port '{port_name}': expected '{expected_value}', actual '{actual_value}'") + logger.warning(f"Win node output mismatch - port: {port_name}, expected: {expected_value}, actual: {actual_value}") + + # 如果所有输出都匹配,使用第一个输出作为胜利字符串 + if is_correct and output_values: + victory_string = list(output_values.values())[0] + else: + logger.warning(f"Win node called but missing output values - expected: {expected_outputs}, actual: {output_values}") + + # 不再主动提示胜利字符串,让模型自己判断 + # 模型调用工具获得输出后,需要自己识别这是否是胜利字符串并提交 + if is_correct: + logger.info(f"🎯 Win node called with correct output - case: {case_id}, node: {node_id}, victory: {victory_string}") + else: + logger.info(f"❌ Win node called with incorrect output - case: {case_id}, node: {node_id}") + + return response + +class UseItemRequest(BaseModel): + node_id: str = Field(..., description="The ID of the Item node to use (must be Item type)") + arguments: Dict[str, Any] = Field(default_factory=dict, description="Input arguments to provide to the item") + +@app.post("/env/{case_id}/use_item") +def use_item(case_id: str, req: UseItemRequest): + """ + Use an Item node by providing input arguments. + + This is specifically for Item nodes that require parameters to be "unlocked" or "activated", + such as containers that need a password/fingerprint. + + - Validates that the node is of type Item + - Checks if provided arguments match the item's golden_input_values + - If match: triggers ITEM-type edge drops and returns the item's content + - If not match: returns error message + """ + logger.info(f"Use item request - case_id: {case_id}, node_id: {req.node_id}, args: {req.arguments}") + STATS["use_items"][case_id] += 1 + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + if req.node_id not in scenario.nodes: + logger.error(f"Node not found: {req.node_id} in case {case_id}") + raise HTTPException(status_code=404, detail="Node not found") + + item_node = scenario.nodes[req.node_id] + + if not item_node.is_revealed: + logger.warning(f"Attempt to use hidden item: {req.node_id}") + return {"ok": False, "error": "Item is not visible yet."} + + if item_node.type != "Item": + logger.warning(f"Attempt to use non-item node: {req.node_id} (type: {item_node.type})") + return {"ok": False, "error": "Only Item nodes can be used with use_item. Tools should be called with tool_call."} + + # 【新增】检查该 Item 是否已经被成功解锁 + # 如果已经被正确使用过,直接返回成功提示 + if item_node.if_success: + logger.info(f"Item already unlocked, returning success message: {req.node_id}") + return { + "ok": True, + "message": "This item has already been successfully unlocked by you." + } + + # 检查该 Item 是否真的需要通过 use_item 提供参数 + # 只有当 Item 有非 Item/Hidden_Item 类型的输入时,才应该使用 use_item + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + non_hidden_inputs = [ + inp for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + if not non_hidden_inputs: + # 该 Item 不需要参数,应该只使用 investigate + logger.warning(f"Attempt to use_item on a node that doesn't require parameters: {req.node_id}") + return { + "ok": False, + "error": "This item does not require parameters. Please use investigate to examine the item directly." + } + + # 验证输入参数是否与 golden_input_values 匹配 + inputs_match_golden = _check_inputs_match_golden(req.arguments, item_node.golden_input_values) + + if not inputs_match_golden: + logger.info(f"✗ Item inputs do NOT match golden - node: {req.node_id}") + # 提供更详细的错误信息,帮助 Agent 理解问题 + # 只显示非 Item/Hidden_Item 类型的参数(Hidden_Item 由系统自动处理) + expected_params = [] + if req.node_id in raw_nodes_data: + raw_node = raw_nodes_data[req.node_id] + inputs_info = raw_node.get('inputs', []) + expected_params = [ + inp.get("name") for inp in inputs_info + if inp.get("type") not in ["Item", "Hidden_Item"] + ] + + provided_params = list(req.arguments.keys()) if req.arguments else [] + + # 检查参数名是否匹配 + if set(expected_params) == set(provided_params): + # 参数名正确但值不匹配 - 不泄漏正确的值 + error_msg = f"Parameter names are correct, but the parameter values are incorrect. Please try using different parameter values." + else: + error_msg = f"Parameter names do not match. Expected parameter names: {expected_params}, you provided: {provided_params}." + + return { + "ok": False, + "error": error_msg + } + + logger.info(f"✓ Item inputs match golden - node: {req.node_id}, activating item") + + # 标记该 Item 已被正确使用 + item_node.if_success = True + + # 将 golden_output_values 追加到 actual_outputs_history + if item_node.golden_output_values: + item_node.actual_outputs_history.append(dict(item_node.golden_output_values)) + + # 触发 ITEM 类型边的掉落 + newly_revealed = [] + for edge in scenario.edges: + if edge.source_id == item_node.id and edge.connection_type == InterfaceType.ITEM: + target_node = scenario.nodes[edge.target_id] + + if not target_node.is_revealed: + target_node.is_revealed = True + # 构建基本节点信息(不包含详细内容) + node_info = { + "id": target_node.id, + "type": target_node.type, + "can_investigate": True, + "hint": "Use investigate to view detailed information" if target_node.type == "Tool" else "Use investigate to view item content" + } + # 只在 name 非空时添加 + # if target_node.name: + # node_info["name"] = target_node.name + # 只在 description 非空时添加 + if target_node.description: + node_info["description"] = target_node.description + + newly_revealed.append(node_info) + logger.info(f"ITEM drop triggered: {target_node.id} (from use_item on {req.node_id})") + + # 检查是否为 Win Node + win_node_id = scenario.win_node_id + is_win_node = (req.node_id == win_node_id) + + # 构建返回结果 + result = { + "ok": True, + "message": "Item used successfully.", + "content": item_node.golden_output_values if item_node.golden_output_values else None + } + + # 获取 narrative(如果存在) + raw_nodes_data = RAW_NODES_DATA.get(case_id, {}) + if req.node_id in raw_nodes_data: + narrative = raw_nodes_data[req.node_id].get('narrative') + if narrative: + result['narrative'] = narrative + + if newly_revealed: + result["newly_revealed"] = newly_revealed + + # 不再主动提示胜利字符串,让模型自己判断 + # 如果是 Win Node,只记录日志 + if is_win_node: + logger.info(f"Win node (Item) unlocked via use_item - case: {case_id}, node: {req.node_id}") + + return result + + +class SubmitAnswerRequest(BaseModel): + answer: str = Field(..., description="The victory string to submit") + +@app.post("/env/{case_id}/submit_answer") +def submit_answer(case_id: str, req: SubmitAnswerRequest): + """ + 提交答案接口 + 被测模型在获得胜利字符串提示后,需要调用此接口提交答案 + """ + logger.info(f"Submit answer request - case_id: {case_id}, answer: {req.answer}") + + if case_id not in SCENARIOS: + logger.error(f"Case not found: {case_id}") + raise HTTPException(status_code=404, detail="Case not found") + + scenario = SCENARIOS[case_id] + + # 获取 win_node 的 golden_output_values + if not scenario.win_node_id: + logger.error(f"No win node defined for case: {case_id}") + return { + "ok": False, + "error": "This case has no victory node defined" + } + + win_node = scenario.nodes.get(scenario.win_node_id) + if not win_node: + logger.error(f"Win node not found: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node does not exist" + } + + # 获取正确的胜利字符串(取第一个 golden_output_value) + if win_node.golden_output_values: + correct_answer = list(win_node.golden_output_values.values())[0] + else: + logger.error(f"Win node has no golden_output_values: {scenario.win_node_id}") + return { + "ok": False, + "error": "Victory node has no correct answer" + } + + # 验证提交的答案 + if req.answer == correct_answer: + logger.info(f"🎉 CORRECT ANSWER SUBMITTED - case: {case_id}, answer: {req.answer}") + return { + "ok": True, + "is_win": True, + "victory_message": f"🎉 Congratulations on successfully escaping the room! Your answer is correct: {req.answer}" + } + else: + logger.info(f"❌ INCORRECT ANSWER SUBMITTED - case: {case_id}, submitted: {req.answer}, correct: {correct_answer}") + return { + "ok": True, + "is_win": False, + "error": f"The submitted answer is incorrect. You submitted: {req.answer}" + } + +if __name__ == "__main__": + + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/simulator.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d35f4aedf0550b54baadd751851b8f62fa2fb0 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/upstream/simulator.py @@ -0,0 +1,2911 @@ +import hashlib +import hmac +import base64 +import binascii +import zlib +import json +import uuid +import math +import re +from typing import Dict, Any, List + +class ToolSimulator: + def __init__(self): + """工具模拟器 + + 文件处理工具(zip_unzip, zip_unzip_file, zip_unzip_item, json_get, csv_query, + regex_search, graph_shortest_path)不需要真实文件系统。 + 这些工具只验证输入参数,然后返回预先初始化好的 golden_outputs。 + """ + self.tool_map = { + # 数论 + "calc_bigmul": self.calc_bigmul, + "calc_modexp": self.calc_modexp, + "calc_modexp_int": self.calc_modexp_int, + "calc_gcd": self.calc_gcd, + "calc_gcd_int": self.calc_gcd_int, + "calc_inv_mod": self.calc_inv_mod, + "calc_inv_mod_int": self.calc_inv_mod_int, + + # 哈希 + "hash_sha256": self.hash_sha256, + "hash_md5": self.hash_md5, + "hmac_sha256": self.hmac_sha256, + + # 编码 + "base64_decode": self.base64_decode, + "base64_encode": self.base64_encode, + "hex_decode": self.hex_decode, + "hex_encode": self.hex_encode, + "zlib_inflate": self.zlib_inflate, + "zlib_deflate": self.zlib_deflate, + + # 文件 + "zip_unzip": self.zip_unzip, + "zip_unzip_file": self.zip_unzip_file, + "zip_unzip_item": self.zip_unzip_item, + "regex_search": self.regex_search, + "json_get": self.json_get, + "csv_query": self.csv_query, + "code_py_exec": self.code_py_exec, + + # 图 + "graph_shortest_path": self.graph_shortest_path, + + # 加解密 (简化模拟) + "crypto_aes_cbc_decrypt": self.crypto_aes_cbc_decrypt, + "crypto_rsa_decrypt_hex": self.crypto_rsa_decrypt_hex, + + # 其他 + "num_base_convert": self.num_base_convert, + "time_convert": self.time_convert, + "checksum_crc32": self.checksum_crc32, + "geo_haversine": self.geo_haversine, + "otp_totp_generate": self.otp_totp_generate, + "unicode_norm": self.unicode_norm, + "text_bidi_sanitize": self.text_bidi_sanitize, + "text_xor_hex": self.text_xor_hex, + "text_rotN": self.text_rotN, + "luhn_check": self.luhn_check, + "iban_validate": self.iban_validate, + + # 物理 + "matter_synthesizer": self.matter_synthesizer, + + # 终端机 + "terminal_1": self.terminal_1, + "terminal_2": self.terminal_2, + "Logic Terminal": self.logic_terminal, + "Math Terminal": self.math_terminal, + "Encryption Terminal": self.crypt_terminal, + "Sequence Terminal": self.sequence_terminal + } + + def execute(self, tool_name: str, inputs: Dict[str, Any]) -> Dict[str, Any]: + if tool_name not in self.tool_map: + # Fallback for unknown tools: return dummy outputs based on expected output types + # This should ideally not happen if all tools are implemented + return {} + + try: + return self.tool_map[tool_name](inputs) + except Exception as e: + print(f"Error executing {tool_name}: {e}") + # Return empty or error indication? For generation, we might want to fail hard or return dummy. + # For now, return dummy to keep flow going, but log error. + return {} + + # --- Implementations --- + + def calc_bigmul(self, inputs): + # Check if required parameters are present + if "a" not in inputs or "b" not in inputs: + raise ValueError("Missing required parameters 'a' and/or 'b'") + + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + return {"product": str(a * b)} + except (ValueError, TypeError) as e: + raise ValueError(f"Failed to convert parameters to integers: {str(e)}") + + def calc_modexp(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + try: + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if isinstance(base, str): + base = int(base) + elif not isinstance(base, int): + raise ValueError("Parameter 'base' must be a string or integer") + + if isinstance(exp, str): + exp = int(exp) + elif not isinstance(exp, int): + raise ValueError("Parameter 'exp' must be a string or integer") + + if isinstance(mod, str): + mod = int(mod) + elif not isinstance(mod, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": str(pow(base, exp, mod))} + + def calc_modexp_int(self, inputs): + # 参数检查 + if "base" not in inputs: + raise ValueError("Missing required parameter: base") + if "exp" not in inputs: + raise ValueError("Missing required parameter: exp") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["base"], int): + raise ValueError("Parameter 'base' must be an integer") + if not isinstance(inputs["exp"], int): + raise ValueError("Parameter 'exp' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + base = inputs["base"] + exp = inputs["exp"] + mod = inputs["mod"] + + if mod == 0: + raise ValueError("Modulus cannot be zero") + + return {"value": pow(base, exp, mod)} + + def calc_gcd(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + b = inputs["b"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(b, str): + b = int(b) + elif not isinstance(b, int): + raise ValueError("Parameter 'b' must be a string or integer") + + # 计算 GCD 并返回字符串格式(符合 Big_Int 输出类型) + result = math.gcd(a, b) + return {"gcd": str(result)} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def calc_gcd_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "b" not in inputs: + raise ValueError("Missing required parameter: b") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["b"], int): + raise ValueError("Parameter 'b' must be an integer") + + # 获取参数 + a = inputs["a"] + b = inputs["b"] + + return {"gcd": math.gcd(a, b)} + + def calc_inv_mod(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 转换参数(支持 str 和 int) + try: + a = inputs["a"] + m = inputs["mod"] + + # 转换为整数 + if isinstance(a, str): + a = int(a) + elif not isinstance(a, int): + raise ValueError("Parameter 'a' must be a string or integer") + + if isinstance(m, str): + m = int(m) + elif not isinstance(m, int): + raise ValueError("Parameter 'mod' must be a string or integer") + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": str(pow(a, -1, m))} + except ValueError as e: + # 模逆不存在时,返回一个特殊值(用于数据传递) + # 在 DAG 生成阶段,这允许数据流继续 + return {"inv": str(a)} + + def calc_inv_mod_int(self, inputs): + # 参数检查 + if "a" not in inputs: + raise ValueError("Missing required parameter: a") + if "mod" not in inputs: + raise ValueError("Missing required parameter: mod") + + # 类型检查 + if not isinstance(inputs["a"], int): + raise ValueError("Parameter 'a' must be an integer") + if not isinstance(inputs["mod"], int): + raise ValueError("Parameter 'mod' must be an integer") + + # 获取参数 + a = inputs["a"] + m = inputs["mod"] + + # 模数不能为零 + if m == 0: + raise ValueError("Modulus cannot be zero") + + try: + return {"inv": pow(a, -1, m)} + except ValueError as e: + raise ValueError(f"Modular inverse does not exist: {str(e)}") + + def hash_sha256(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.sha256(text.encode()).hexdigest()} + + def hash_md5(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + return {"hex": hashlib.md5(text.encode()).hexdigest()} + + def hmac_sha256(self, inputs): + # 参数检查 + if "hex_key" not in inputs: + raise ValueError("Missing required parameter: hex_key") + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["hex_key"], str): + raise ValueError("Parameter 'hex_key' must be a string") + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + try: + key = bytes.fromhex(inputs["hex_key"]) + text = inputs["text"].encode() + return {"hex": hmac.new(key, text, hashlib.sha256).hexdigest()} + except ValueError as e: + raise ValueError(f"Parameter conversion error: {str(e)}") + + def base64_decode(self, inputs): + # 参数检查 + if "data" not in inputs: + raise ValueError("Missing required parameter: data") + + # 类型检查 + if not isinstance(inputs["data"], str): + raise ValueError("Parameter 'data' must be a string") + + data = inputs["data"] + try: + return {"bytes_hex": binascii.hexlify(base64.b64decode(data)).decode()} + except Exception as e: + raise ValueError(f"Base64 decode error: {str(e)}") + + def base64_encode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"b64": base64.b64encode(bytes.fromhex(hex_data)).decode()} + except Exception as e: + raise ValueError(f"Base64 encode error: {str(e)}") + + def hex_decode(self, inputs): + # 参数检查 + if "hex" not in inputs: + raise ValueError("Missing required parameter: hex") + + # 类型检查 + if not isinstance(inputs["hex"], str): + raise ValueError("Parameter 'hex' must be a string") + + hex_data = inputs["hex"] + try: + return {"text": bytes.fromhex(hex_data).decode('utf-8', errors='ignore')} + except Exception as e: + raise ValueError(f"Hex decode error: {str(e)}") + + def hex_encode(self, inputs): + # 参数检查 + if "text" not in inputs: + raise ValueError("Missing required parameter: text") + + # 类型检查 + if not isinstance(inputs["text"], str): + raise ValueError("Parameter 'text' must be a string") + + text = inputs["text"] + try: + return {"hex": text.encode().hex()} + except Exception as e: + raise ValueError(f"Hex encode error: {str(e)}") + + + # 到此处实现已经更新 + + def zlib_inflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("Parameter 'hex' must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("Missing required parameter: hex") + + try: + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空字符串 + if not hex_data: + raise ValueError("Empty hex string provided") + + # 检查十六进制字符串的有效性 + if len(hex_data) % 2 != 0: + raise ValueError("Hex string must have even length") + + # 检查是否只包含有效的十六进制字符 + if not all(c in '0123456789abcdefABCDEF' for c in hex_data): + raise ValueError("Invalid hex string provided") + + # 尝试解压缩 + return {"text": zlib.decompress(bytes.fromhex(hex_data)).decode('utf-8')} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hex string provided") from e + raise ValueError(f"Invalid zlib data: {e}") from e + except Exception as e: + raise RuntimeError(f"Failed to inflate data: {e}") from e + + def zlib_deflate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("Parameter 'text' must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("Missing required parameter: text") + + try: + # 压缩文本 + return {"hex": zlib.compress(text.encode('utf-8')).hex()} + except Exception as e: + raise RuntimeError(f"Failed to deflate data: {e}") from e + + # --- File Operations --- + + def zip_unzip(self, inputs): + """ZIP 解压工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"files": golden_outputs.get("files", "")} + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return {"files": golden_outputs.get("files", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "files" in golden_outputs: + # 验证必需参数 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 检查类型 + if has_zip_id and not isinstance(zip_id, str): + return {"error": "Parameter 'zip_id' must be a string type"} + if has_password and not isinstance(password, str): + return {"error": "Parameter 'password' must be a string type"} + + # 验证输入是否与预期匹配 + if golden_inputs: + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return {"files": golden_outputs["files"]} + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + # 没有golden_inputs但有golden_outputs,直接返回输出 + return {"files": golden_outputs["files"]} + + # 如果没有预期输出,返回空结果 + return {"files": ""} + + def regex_search(self, inputs): + """正则搜索工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"matches": golden_outputs.get("matches", "[]")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "matches" in golden_outputs: + # 提取实际参数 + pattern = inputs.get("pattern") + file_id = inputs.get("file_id") + text = inputs.get("text") + + # 1. 检查必需参数 + if pattern is None: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["pattern"], + "message": "Missing required parameter 'pattern'" + } + } + + # 类型检查 + if not isinstance(pattern, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "pattern", + "message": "Parameter 'pattern' must be a string type" + } + } + if file_id is not None and not isinstance(file_id, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if text is not None and not isinstance(text, str): + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "text", + "message": "Parameter 'text' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合 + provided_params = {} + if pattern is not None: + provided_params["pattern"] = pattern + if file_id is not None: + provided_params["file_id"] = file_id + if text is not None: + provided_params["text"] = text + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数(关键改进) + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "matches": "[]", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_pattern = golden_inputs.get("pattern") + expected_file_id = golden_inputs.get("file_id") + expected_text = golden_inputs.get("text") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_pattern is not None: + if str(pattern) != str(expected_pattern): + incorrect_params.append("pattern") + else: + correct_params.append("pattern") + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_text is not None: + if str(text) != str(expected_text): + incorrect_params.append("text") + else: + correct_params.append("text") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "matches": "[]", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "matches": golden_outputs["matches"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空列表 + return {"matches": "[]"} + + def json_get(self, inputs): + """JSON 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"values": golden_outputs.get("values", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "values" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + jsonpath = inputs.get("jsonpath", "") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if jsonpath is not None and not isinstance(jsonpath, str): + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "jsonpath", + "message": "Parameter 'jsonpath' must be a string type" + } + } + + # 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:jsonpath有默认值"") + provided_params = {} + if file_id is not None: + provided_params["file_id"] = file_id + if jsonpath != "": + provided_params["jsonpath"] = jsonpath + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "values": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_jsonpath = golden_inputs.get("jsonpath") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_jsonpath is not None: + if str(jsonpath) != str(expected_jsonpath): + incorrect_params.append("jsonpath") + else: + correct_params.append("jsonpath") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "values": "", + "_validation": validation_info + } + + # 所有验证通过,返回正确输出 + return { + "values": golden_outputs["values"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"values": ""} + + def csv_query(self, inputs): + """CSV 查询工具(模拟) + + 验证输入参数是否与 DAG 中的预期输入匹配,然后返回预先计算的输出。 + 不需要真实文件系统操作。 + + 返回包含 _validation 字段用于精细化错误反馈。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取初始化的输入和输出(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return {"rows": golden_outputs.get("rows", "")} + + # 如果有预设输出,进行验证后返回 + if golden_outputs and "rows" in golden_outputs: + # 提取实际参数 + file_id = inputs.get("file_id") + select_columns = inputs.get("select", "") + where_clause = inputs.get("where", "") + + # 1. 检查必需参数 + if file_id is None: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "missing_required", + "missing_params": ["file_id"], + "message": "Missing required parameter 'file_id'" + } + } + + # 类型检查 + if not isinstance(file_id, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "file_id", + "message": "Parameter 'file_id' must be a string type" + } + } + if not isinstance(select_columns, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "select", + "message": "Parameter 'select' must be a string type" + } + } + if not isinstance(where_clause, str): + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "type_error", + "param_name": "where", + "message": "Parameter 'where' must be a string type" + } + } + + # 2. 验证输入是否与预期匹配 + if golden_inputs: + # 构建已提供的参数集合(注意:select和where有默认值"") + provided_params = {"file_id": file_id} + if select_columns != "": + provided_params["select"] = select_columns + if where_clause != "": + provided_params["where"] = where_clause + + expected_param_names = set(golden_inputs.keys()) + provided_param_names = set(provided_params.keys()) + + # 2a. 检查是否缺少 golden inputs 中的参数 + missing_in_golden = expected_param_names - provided_param_names + if missing_in_golden: + return { + "rows": "", + "_validation": { + "valid": False, + "error_type": "incomplete_optional", + "provided_params": list(provided_param_names), + "missing_params": list(missing_in_golden), + "hint": f"The parameters you provided are partially correct, but may also need: {', '.join(missing_in_golden)}" + } + } + + # 2b. 检查参数值是否匹配 + expected_file_id = golden_inputs.get("file_id") + expected_select = golden_inputs.get("select") + expected_where = golden_inputs.get("where") + + # 收集正确和错误的参数 + incorrect_params = [] + correct_params = [] + + if expected_file_id is not None: + if str(file_id) != str(expected_file_id): + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_select is not None: + if str(select_columns) != str(expected_select): + incorrect_params.append("select") + else: + correct_params.append("select") + + if expected_where is not None: + if str(where_clause) != str(expected_where): + incorrect_params.append("where") + else: + correct_params.append("where") + + # 如果有参数不正确,返回详细反馈 + if incorrect_params: + hint = f"The value of parameter(s) {', '.join(incorrect_params)} may be incorrect" + if correct_params: + hint += f". Correct parameters: {', '.join(correct_params)}" + + validation_info = { + "valid": False, + "error_type": "value_mismatch", + "incorrect_params": incorrect_params, + "hint": hint + } + if correct_params: + validation_info["correct_params"] = correct_params + + return { + "rows": "", + "_validation": validation_info + } + + # 3. 所有验证通过,返回正确输出 + return { + "rows": golden_outputs["rows"], + "_validation": { + "valid": True + } + } + + # 如果没有预期输出,返回空结果 + return {"rows": ""} + + def graph_shortest_path(self, inputs): + """图最短路径工具 + + 如果有 _golden_outputs 或 _init_outputs,验证输入并返回预设输出。 + 否则执行真实的 Dijkstra 算法。 + """ + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 检查是否在预设模式中(DAG 生成阶段用 _init_*,评测阶段用 _golden_*) + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation and golden_outputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + if golden_outputs and "path" in golden_outputs: + # 评测阶段但没有 golden_inputs,直接返回 outputs + if not golden_inputs: + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 评测模式:验证输入参数是否匹配 golden 值 + src = inputs.get("src") + dst = inputs.get("dst") + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + + has_src = src is not None and src != "" + has_dst = dst is not None and dst != "" + + # 验证必需参数 + if not has_src or not has_dst: + missing = [] + if not has_src: + missing.append("src") + if not has_dst: + missing.append("dst") + return {"error": "Missing required parameters: " + ", ".join(missing)} + + # 类型检查 + if not isinstance(src, str): + return {"error": "Parameter 'src' must be a string"} + if not isinstance(dst, str): + return {"error": "Parameter 'dst' must be a string"} + + # 验证输入是否匹配期望值 + if golden_inputs: + expected_src = golden_inputs.get("src") + expected_dst = golden_inputs.get("dst") + expected_file_id = golden_inputs.get("file_id") + expected_graph_data = golden_inputs.get("graph_data") + + # 收集验证结果 + incorrect_params = [] + correct_params = [] + + # 检查必需参数是否匹配 + if expected_src is not None: + if str(src) != str(expected_src): + incorrect_params.append("src") + else: + correct_params.append("src") + + if expected_dst is not None: + if str(dst) != str(expected_dst): + incorrect_params.append("dst") + else: + correct_params.append("dst") + + # 检查可选参数(如果在 expected_inputs 中定义了) + if expected_file_id is not None: + if file_id != expected_file_id: + incorrect_params.append("file_id") + else: + correct_params.append("file_id") + + if expected_graph_data is not None: + if graph_data != expected_graph_data: + incorrect_params.append("graph_data") + else: + correct_params.append("graph_data") + + # 如果有参数不正确,返回详细的反馈 + if incorrect_params: + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 验证通过,返回预设的输出 + return { + "path": golden_outputs.get("path", "[]"), + "cost": golden_outputs.get("cost", 0) + } + + # 获取参数(真实执行路径) + file_id = inputs.get("file_id") + graph_data = inputs.get("graph_data") + # Support both src/dst (interface definition) and start/end (original implementation) + start = inputs.get("src") + end = inputs.get("dst") + + # 类型检查 + if file_id is not None and not isinstance(file_id, str): + raise TypeError("file_id must be a string") + + if graph_data is not None and not isinstance(graph_data, str): + raise TypeError("graph_data must be a string") + + if start is not None and not isinstance(start, str): + raise TypeError("src/start must be a string") + + if end is not None and not isinstance(end, str): + raise TypeError("dst/end must be a string") + + # 检查必需参数 + if file_id is None and graph_data is None: + raise ValueError("Either file_id or graph_data must be provided") + + if start is None: + raise ValueError("src/start parameter is required") + + if end is None: + raise ValueError("dst/end parameter is required") + + # Get graph content + content = None + if file_id is not None: + # 尝试从 VFS 获取(如果存在) + if hasattr(self, 'vfs') and file_id in self.vfs: + content = self.vfs[file_id] + else: + # VFS 不存在或文件不在 VFS 中 + # 返回一个默认的空图结果,或者抛出错误提示需要 init_outputs + raise ValueError( + f"File '{file_id}' not found. For tools that require files, " + f"please provide init_outputs in the initial_values." + ) + elif graph_data is not None: + content = graph_data + + if content is None: + content = "{}" + + try: + # Parse graph data + graph = json.loads(content) + + # 类型检查 + if not isinstance(graph, dict): + raise TypeError("Graph data must be a dictionary") + + # If graph is not in the expected format, try to extract adjacency list + if "nodes" in graph and "edges" in graph: + # 验证nodes和edges的类型 + if not isinstance(graph["nodes"], list): + raise TypeError("Nodes must be a list") + + if not isinstance(graph["edges"], list): + raise TypeError("Edges must be a list") + + # Convert from nodes/edges format to adjacency list + adjacency_list = {} + for node in graph["nodes"]: + # 验证node类型 + if not isinstance(node, dict): + raise TypeError("Each node must be a dictionary") + + # Use node ID as key, not the entire node dictionary + node_id = node.get("id", "") + if node_id: + adjacency_list[node_id] = {} + + for edge in graph["edges"]: + # 验证edge类型 + if not isinstance(edge, dict): + raise TypeError("Each edge must be a dictionary") + + u = edge["from"] + v = edge["to"] + weight = edge.get("weight", 1) # Default to unweighted + + # 类型检查 + if not isinstance(u, str): + raise TypeError("Edge 'from' must be a string") + + if not isinstance(v, str): + raise TypeError("Edge 'to' must be a string") + + if not isinstance(weight, (int, float)): + raise TypeError("Edge weight must be a number") + + if u not in adjacency_list: + adjacency_list[u] = {} + if v not in adjacency_list: + adjacency_list[v] = {} + + adjacency_list[u][v] = weight + # If undirected, add reverse edge + if not edge.get("directed", False): + adjacency_list[v][u] = weight + elif isinstance(graph, dict): + # Already in adjacency list format + adjacency_list = graph + + # 验证邻接表结构 + for node, neighbors in adjacency_list.items(): + if not isinstance(neighbors, dict): + raise TypeError("Adjacency list must be a dictionary of dictionaries") + + for neighbor, weight in neighbors.items(): + if not isinstance(weight, (int, float)): + raise TypeError("Edge weights must be numbers") + else: + raise TypeError("Graph data must be a dictionary") + + # 检查起点和终点是否为空 + if not start: + raise ValueError("Start node cannot be empty") + + if not end: + raise ValueError("End node cannot be empty") + + # 检查起点和终点是否在图中 + if start not in adjacency_list: + raise ValueError(f"Start node '{start}' not found in graph") + + if end not in adjacency_list: + raise ValueError(f"End node '{end}' not found in graph") + + # Dijkstra's algorithm implementation + import heapq + + # Initialize distances and previous nodes + distances = {node: float('infinity') for node in adjacency_list} + previous = {node: None for node in adjacency_list} + distances[start] = 0 + + # Priority queue + pq = [(0, start)] + heapq.heapify(pq) + + while pq: + current_dist, current_node = heapq.heappop(pq) + + # If we've reached the end node, we can break early + if current_node == end: + break + + # Nodes can be added multiple times to the priority queue, but we only process them once + if current_dist > distances[current_node]: + continue + + # Explore neighbors + for neighbor, weight in adjacency_list[current_node].items(): + distance = current_dist + weight + + # If a shorter path is found + if distance < distances[neighbor]: + distances[neighbor] = distance + previous[neighbor] = current_node + heapq.heappush(pq, (distance, neighbor)) + + # Reconstruct the shortest path + path = [] + current = end + while current is not None: + path.append(current) + current = previous[current] + path.reverse() # Reverse to get from start to end + + # Check if path exists + if not path or path[0] != start: + return {"path": "[]", "cost": 0} + + return { + "path": json.dumps(path), + "cost": distances[end] + } + except json.JSONDecodeError as e: + raise ValueError(f"Invalid JSON in graph data: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in graph_shortest_path: {str(e)}") + + # --- Crypto (Simplified) --- + def crypto_aes_cbc_decrypt(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 (使用模板中定义的参数名) + hex_cipher = inputs.get("hex_cipher") + hex_key = inputs.get("hex_key") + hex_iv = inputs.get("hex_iv") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + + if hex_key is not None and not isinstance(hex_key, str): + raise TypeError("hex_key must be a string") + + if hex_iv is not None and not isinstance(hex_iv, str): + raise TypeError("hex_iv must be a string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + + if hex_key is None: + raise ValueError("hex_key parameter is required") + + if hex_iv is None: + raise ValueError("hex_iv parameter is required") + + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import padding + + try: + # Convert hex strings to bytes + ciphertext = bytes.fromhex(hex_cipher) + key = bytes.fromhex(hex_key) + iv = bytes.fromhex(hex_iv) + + # Validate key length (AES-128, AES-192, AES-256) + if len(key) not in [16, 24, 32]: + raise ValueError("Invalid key length. Must be 16, 24, or 32 bytes.") + + if len(iv) != 16: + raise ValueError("Invalid IV length. Must be 16 bytes.") + + # Create cipher object + cipher = Cipher( + algorithms.AES(key), + modes.CBC(iv), + backend=default_backend() + ) + + decryptor = cipher.decryptor() + + # Decrypt the ciphertext + padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() + + # Remove PKCS7 padding + unpadder = padding.PKCS7(128).unpadder() + plaintext = unpadder.update(padded_plaintext) + unpadder.finalize() + + # Return decrypted text + return {"text": plaintext.decode('utf-8', errors='ignore')} + except ValueError as e: + if "non-hexadecimal number found in fromhex()" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher, hex_key, or hex_iv") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in crypto_aes_cbc_decrypt: {str(e)}") + + def crypto_rsa_decrypt_hex(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_cipher = inputs.get("hex_cipher") + n = inputs.get("n") + d = inputs.get("d") + + # 类型检查 + if hex_cipher is not None and not isinstance(hex_cipher, str): + raise TypeError("hex_cipher must be a string") + if n is not None and not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + if d is not None and not isinstance(d, (int, str)): + raise TypeError("d must be an integer or string") + + # 检查必需参数 + if hex_cipher is None: + raise ValueError("hex_cipher parameter is required") + if n is None: + raise ValueError("n parameter is required") + if d is None: + raise ValueError("d parameter is required") + + try: + # Convert parameters to appropriate types + cipher_int = int(hex_cipher, 16) + n_int = int(n) if isinstance(n, str) else n + d_int = int(d) if isinstance(d, str) else d + + # RSA decryption: plaintext = ciphertext^d mod n + plaintext_int = pow(cipher_int, d_int, n_int) + + # Convert result to hex and then to text + plaintext_hex = hex(plaintext_int)[2:] + + # Pad with leading zero if odd length + if len(plaintext_hex) % 2 != 0: + plaintext_hex = '0' + plaintext_hex + + # Convert hex to bytes and then to text + try: + plaintext_bytes = bytes.fromhex(plaintext_hex) + plaintext_text = plaintext_bytes.decode('utf-8', errors='ignore') + except: + # If decoding fails, return hex representation + plaintext_text = plaintext_hex + + return {"text": plaintext_text} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string in hex_cipher") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in crypto_rsa_decrypt_hex: {str(e)}") + + # --- Others --- + def num_base_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + s = inputs.get("s") + from_base = inputs.get("from_base") + to_base = inputs.get("to_base") + + # 类型检查 - 接受 str 或 int + if s is not None and not isinstance(s, (str, int)): + raise TypeError("s must be a string or integer") + + if from_base is not None and not isinstance(from_base, (int, str)): + raise TypeError("from_base must be an integer") + + if to_base is not None and not isinstance(to_base, (int, str)): + raise TypeError("to_base must be an integer") + + # 检查必需参数 + if s is None: + raise ValueError("s parameter is required") + + if from_base is None: + raise ValueError("from_base parameter is required") + + if to_base is None: + raise ValueError("to_base parameter is required") + + try: + # Convert to int if needed + from_base = int(from_base) if isinstance(from_base, str) else from_base + to_base = int(to_base) if isinstance(to_base, str) else to_base + s_str = str(s) + + # 验证基数范围 + if from_base < 2 or from_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + if to_base < 2 or to_base > 36: + # 在 DAG 生成阶段,如果基数无效,返回输入值本身以保持数据流 + return {"str": s_str} + + # Convert from source base to decimal + val = int(s_str, from_base) + + # Convert from decimal to target base + if to_base == 10: + result = str(val) + elif to_base == 16: + result = hex(val)[2:] + elif to_base == 8: + result = oct(val)[2:] + elif to_base == 2: + result = bin(val)[2:] + else: + # Generic base conversion for other bases + if val == 0: + result = "0" + else: + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + n = abs(val) + while n: + result = digits[n % to_base] + result + n //= to_base + if val < 0: + result = "-" + result + + return {"str": result} + except ValueError as e: + raise ValueError(f"Invalid number format: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in num_base_convert: {str(e)}") + + def time_convert(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iso = inputs.get("iso") + timestamp = inputs.get("timestamp") + datetime_str = inputs.get("datetime") + from_tz = inputs.get("from_tz") + to_tz = inputs.get("to_tz") + format_str = inputs.get("format") + + # 类型检查 + if iso is not None and not isinstance(iso, str): + raise TypeError("iso must be a string") + + if timestamp is not None and not isinstance(timestamp, (str, int, float)): + raise TypeError("timestamp must be a string, integer, or float") + + if datetime_str is not None and not isinstance(datetime_str, str): + raise TypeError("datetime must be a string") + + if from_tz is not None and not isinstance(from_tz, str): + raise TypeError("from_tz must be a string") + + if to_tz is not None and not isinstance(to_tz, str): + raise TypeError("to_tz must be a string") + + if format_str is not None and not isinstance(format_str, str): + raise TypeError("format must be a string") + + # 设置默认值 + if from_tz is None: + from_tz = "UTC" + + if to_tz is None: + to_tz = "UTC" + + import datetime + import pytz + + # 验证时区参数 + try: + if from_tz: + pytz.timezone(from_tz) + if to_tz: + pytz.timezone(to_tz) + except Exception: + raise ValueError("Invalid timezone provided") + + try: + # Parse input time + dt = None + + if iso is not None: + # Parse ISO 8601 format + dt = datetime.datetime.fromisoformat(iso.replace('Z', '+00:00')) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=pytz.UTC) + elif timestamp is not None: + # Parse Unix timestamp + timestamp = float(timestamp) + dt = datetime.datetime.fromtimestamp(timestamp, pytz.UTC) + elif datetime_str is not None: + # Parse datetime string + # Try common formats + formats_to_try = [ + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%d %H:%M:%S.%f", + "%Y-%m-%d", + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y" + ] + + parse_success = False + for fmt in formats_to_try: + try: + dt = datetime.datetime.strptime(datetime_str, fmt) + dt = pytz.timezone(from_tz).localize(dt) + parse_success = True + break + except ValueError: + continue + + if not parse_success: + raise ValueError("Unable to parse datetime string with common formats") + else: + # 如果没有提供任何时间参数,则使用当前时间 + dt = datetime.datetime.now(pytz.UTC) + except ValueError as e: + raise ValueError(f"Error parsing time input: {str(e)}") + except Exception as e: + raise RuntimeError(f"Unexpected error parsing time input: {str(e)}") + + try: + # Convert timezone + if from_tz != to_tz: + dt = dt.astimezone(pytz.timezone(to_tz)) + + # Format outputs + result = { + "iso": dt.isoformat(), + "timestamp": str(dt.timestamp()), + "datetime": dt.strftime("%Y-%m-%d %H:%M:%S"), + "date": dt.strftime("%Y-%m-%d"), + "time": dt.strftime("%H:%M:%S"), + "timezone": to_tz + } + + # Add custom format if requested + if format_str: + try: + result["formatted"] = dt.strftime(format_str) + except ValueError as e: + raise ValueError(f"Invalid format string: {str(e)}") + + return result + except Exception as e: + raise RuntimeError(f"Error in time_convert: {str(e)}") + + def checksum_crc32(self, inputs): + import zlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_data = inputs.get("hex") + + # 类型检查 + if hex_data is not None and not isinstance(hex_data, str): + raise TypeError("hex must be a string") + + # 检查必需参数 + if hex_data is None: + raise ValueError("hex parameter is required") + + try: + # 验证十六进制字符串 + # 移除可能的空格 + hex_data = hex_data.replace(" ", "") + + # 检查是否为空 + if not hex_data: + raise ValueError("hex data cannot be empty") + + # 检查是否为有效的十六进制字符串 + if not all(c in "0123456789abcdefABCDEF" for c in hex_data): + raise ValueError("hex must be a valid hexadecimal string") + + # 检查长度是否为偶数 + if len(hex_data) % 2 != 0: + raise ValueError("hex must have even number of characters") + + val = zlib.crc32(bytes.fromhex(hex_data)) + # 确保 hex 输出是 8 位,前导补 0 + return {"hex": f"{val:08x}", "int": val} + except ValueError as e: + if "non-hexadecimal number found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise e + except Exception as e: + raise RuntimeError(f"Error in checksum_crc32: {str(e)}") + + def geo_haversine(self, inputs): + import math + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + lat1 = inputs.get("lat1") + lon1 = inputs.get("lon1") + lat2 = inputs.get("lat2") + lon2 = inputs.get("lon2") + + # 类型检查 + if lat1 is not None and not isinstance(lat1, (int, float, str)): + raise TypeError("lat1 must be a number or string") + if lon1 is not None and not isinstance(lon1, (int, float, str)): + raise TypeError("lon1 must be a number or string") + if lat2 is not None and not isinstance(lat2, (int, float, str)): + raise TypeError("lat2 must be a number or string") + if lon2 is not None and not isinstance(lon2, (int, float, str)): + raise TypeError("lon2 must be a number or string") + + # 检查必需参数 + if lat1 is None: + raise ValueError("lat1 parameter is required") + if lon1 is None: + raise ValueError("lon1 parameter is required") + if lat2 is None: + raise ValueError("lat2 parameter is required") + if lon2 is None: + raise ValueError("lon2 parameter is required") + + try: + # 转换为浮点数:如果本身就是数字就不用操作,如果是字符串就转成数字类型 + if isinstance(lat1, str): + lat1 = float(lat1) + elif not isinstance(lat1, (int, float)): + raise TypeError("lat1 must be a number or string") + else: + lat1 = float(lat1) + + if isinstance(lon1, str): + lon1 = float(lon1) + elif not isinstance(lon1, (int, float)): + raise TypeError("lon1 must be a number or string") + else: + lon1 = float(lon1) + + if isinstance(lat2, str): + lat2 = float(lat2) + elif not isinstance(lat2, (int, float)): + raise TypeError("lat2 must be a number or string") + else: + lat2 = float(lat2) + + if isinstance(lon2, str): + lon2 = float(lon2) + elif not isinstance(lon2, (int, float)): + raise TypeError("lon2 must be a number or string") + else: + lon2 = float(lon2) + + # Validate coordinates (approximate range check) + if not (-90 <= lat1 <= 90): + raise ValueError("lat1 must be between -90 and 90") + if not (-90 <= lat2 <= 90): + raise ValueError("lat2 must be between -90 and 90") + if not (-180 <= lon1 <= 180): + raise ValueError("lon1 must be between -180 and 180") + if not (-180 <= lon2 <= 180): + raise ValueError("lon2 must be between -180 and 180") + + # Earth radius in meters + R = 6371000 # Approximate radius of Earth + + # Convert degrees to radians + lat1_rad = math.radians(lat1) + lon1_rad = math.radians(lon1) + lat2_rad = math.radians(lat2) + lon2_rad = math.radians(lon2) + + # Calculate differences + delta_lat = lat2_rad - lat1_rad + delta_lon = lon2_rad - lon1_rad + + # Haversine formula + a = math.sin(delta_lat / 2) ** 2 + \ + math.cos(lat1_rad) * math.cos(lat2_rad) * \ + math.sin(delta_lon / 2) ** 2 + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + distance_m = R * c + + # Return distance in meters + return {"meters": round(distance_m, 2)} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in geo_haversine: {str(e)}") + + def otp_totp_generate(self, inputs): + import hmac + import hashlib + import base64 + import time + import struct + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + base32_secret = inputs.get("base32_secret") + step = inputs.get("step", 30) # Default to 30 seconds + digits = inputs.get("digits", 6) # Default to 6 digits + timestamp_iso = inputs.get("timestamp_iso", "") + algo = inputs.get("algo", "sha1") # Default to sha1 as current implementation only supports this + + # 类型检查 + if base32_secret is not None and not isinstance(base32_secret, str): + raise TypeError("base32_secret must be a string") + if not isinstance(step, (int, str)): + raise TypeError("step must be an integer or string") + if not isinstance(digits, (int, str)): + raise TypeError("digits must be an integer or string") + if not isinstance(timestamp_iso, str): + raise TypeError("timestamp_iso must be a string") + if not isinstance(algo, str): + raise TypeError("algo must be a string") + + # 检查必需参数 + if base32_secret is None: + raise ValueError("base32_secret parameter is required") + + try: + # Convert step and digits to appropriate types + step = int(step) + digits = int(digits) + if digits < 6 or digits > 8: + raise ValueError("Digits must be between 6 and 8") + + # Convert timestamp_iso to integer timestamp + if timestamp_iso: + import datetime + dt = datetime.datetime.fromisoformat(timestamp_iso.replace('Z', '+00:00')) + timestamp = int(dt.timestamp()) + else: + timestamp = int(time.time()) + + # Calculate counter value (T = floor(timestamp / step)) + counter = timestamp // step + + # Decode the base32 secret + # Add padding if necessary (base64 requires padding to be multiple of 8) + base32_secret = base32_secret.upper().replace(' ', '') + if len(base32_secret) % 8 != 0: + base32_secret += '=' * (8 - (len(base32_secret) % 8)) + key = base64.b32decode(base32_secret, casefold=True) + + # Calculate HMAC-SHA1 + counter_bytes = struct.pack('>Q', counter) # Big-endian 8-byte integer + hmac_hash = hmac.new(key, counter_bytes, hashlib.sha1).digest() + + # Dynamic truncation + offset = hmac_hash[-1] & 0xF + code = struct.unpack('>I', hmac_hash[offset:offset+4])[0] & 0x7FFFFFFF + + # Generate the OTP + otp = str(code % (10 ** digits)).zfill(digits) + + # Calculate remaining time until next OTP change + remaining_time = step - (timestamp % step) + + return {"totp": otp, "remaining_time": remaining_time, "time_step": step} + except ValueError as e: + if "invalid literal for int()" in str(e): + raise ValueError("step and digits must be valid integers") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in otp_totp_generate: {str(e)}") + + def unicode_norm(self, inputs): + import unicodedata + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + form = inputs.get("form", "NFC") # Default to NFC + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if form is not None and not isinstance(form, str): + raise TypeError("form must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Normalize form (NFC, NFD, NFKC, NFKD) + form = form.upper().strip() + + if form not in ['NFC', 'NFD', 'NFKC', 'NFKD']: + raise ValueError(f"Invalid normalization form: {form}. Must be one of: NFC, NFD, NFKC, NFKD") + + # Apply Unicode normalization + normalized_text = unicodedata.normalize(form, text) + + return {"text": normalized_text} + except ValueError as e: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in unicode_norm: {str(e)}") + + def text_bidi_sanitize(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + # Bidi control characters to remove + bidi_controls = [ + '\u200E', # LEFT-TO-RIGHT MARK + '\u200F', # RIGHT-TO-LEFT MARK + '\u202A', # LEFT-TO-RIGHT EMBEDDING + '\u202B', # RIGHT-TO-LEFT EMBEDDING + '\u202C', # POP DIRECTIONAL FORMATTING + '\u202D', # LEFT-TO-RIGHT OVERRIDE + '\u202E', # RIGHT-TO-LEFT OVERRIDE + '\u2066', # LEFT-TO-RIGHT ISOLATE + '\u2067', # RIGHT-TO-LEFT ISOLATE + '\u2068', # FIRST STRONG ISOLATE + '\u2069', # POP DIRECTIONAL ISOLATE + ] + + # Remove all Bidi control characters + sanitized_text = text + for control_char in bidi_controls: + sanitized_text = sanitized_text.replace(control_char, '') + + return {"text": sanitized_text} + except Exception as e: + raise RuntimeError(f"Error in text_bidi_sanitize: {str(e)}") + + def text_xor_hex(self, inputs): + import binascii + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + hex_a = inputs.get("hex_a") + hex_b = inputs.get("hex_b") + + # 类型检查 + if hex_a is not None and not isinstance(hex_a, str): + raise TypeError("hex_a must be a string") + if hex_b is not None and not isinstance(hex_b, str): + raise TypeError("hex_b must be a string") + + # 检查必需参数 + if hex_a is None: + raise ValueError("hex_a parameter is required") + if hex_b is None: + raise ValueError("hex_b parameter is required") + + try: + # Remove any whitespace + hex_a = hex_a.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + hex_b = hex_b.replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "") + + # Validate hex strings + if not (all(c in "0123456789abcdefABCDEF" for c in hex_a) and len(hex_a) % 2 == 0): + raise ValueError("hex_a must be a valid hexadecimal string with even length") + if not (all(c in "0123456789abcdefABCDEF" for c in hex_b) and len(hex_b) % 2 == 0): + raise ValueError("hex_b must be a valid hexadecimal string with even length") + + # Convert hex strings to bytes + bytes_a = binascii.unhexlify(hex_a) + bytes_b = binascii.unhexlify(hex_b) + + # Make the byte arrays the same length by padding the shorter one with zeros + max_len = max(len(bytes_a), len(bytes_b)) + bytes_a = bytes_a.ljust(max_len, b'\x00') + bytes_b = bytes_b.ljust(max_len, b'\x00') + + # Perform XOR operation + result_bytes = bytes(a ^ b for a, b in zip(bytes_a, bytes_b)) + + # Convert result back to hex + result_hex = binascii.hexlify(result_bytes).decode('utf-8') + + return {"hex": result_hex} + except ValueError as e: + if "Non-hexadecimal digit found" in str(e): + raise ValueError("Invalid hexadecimal string") + else: + raise ValueError(f"Invalid input values: {str(e)}") + except Exception as e: + raise RuntimeError(f"Error in text_xor_hex: {str(e)}") + + def text_rotN(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + text = inputs.get("text") + n = inputs.get("n", 0) + + # 类型检查 + if text is not None and not isinstance(text, str): + raise TypeError("text must be a string") + if not isinstance(n, (int, str)): + raise TypeError("n must be an integer or string") + + # 检查必需参数 + if text is None: + raise ValueError("text parameter is required") + + try: + n = int(n) + except ValueError: + raise ValueError("n must be a valid integer") + + result = [] + for char in text: + if char.isupper(): + # Rotate uppercase letters + result_char = chr((ord(char) - ord('A') + n) % 26 + ord('A')) + result.append(result_char) + elif char.islower(): + # Rotate lowercase letters + result_char = chr((ord(char) - ord('a') + n) % 26 + ord('a')) + result.append(result_char) + else: + # Keep non-alphabetic characters unchanged + result.append(char) + + return {"text": ''.join(result)} + + def luhn_check(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数(支持 card_number 和 number 两个参数名) + card_number = inputs.get("number") or inputs.get("card_number") + + # 类型检查 + if card_number is not None and not isinstance(card_number, str): + raise TypeError("number must be a string") + + # 检查必需参数 + if card_number is None: + raise ValueError("number parameter is required") + + try: + # 如果输入是JSON数组或其他非数字字符串,返回该字符串本身(用于数据传递) + # 这种情况发生在DAG设计中类型不匹配时 + if card_number.startswith('[') or card_number.startswith('{'): + # 输入是JSON,直接返回原值(用于传递) + return {"valid": card_number} + + # Remove whitespace from card number + card_number = card_number.replace(" ", "").replace("-", "") + + # Check if card number is all digits + if not card_number.isdigit() or len(card_number) < 13: + return {"valid": "false"} + + # Implement Luhn algorithm + total = 0 + reverse_digits = card_number[::-1] # Reverse the number for easier processing + + for i, digit in enumerate(reverse_digits): + num = int(digit) + if i % 2 == 1: # Every second digit starting from the right (which is first in reversed string) + num *= 2 + if num > 9: + num -= 9 # Equivalent to sum of digits for 2-digit numbers + total += num + + # Check if total is divisible by 10 + is_valid = total % 10 == 0 + return {"valid": "true" if is_valid else "false"} + except Exception as e: + raise RuntimeError(f"Error in luhn_check: {str(e)}") + + def iban_validate(self, inputs): + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + iban = inputs.get("iban") + + # 类型检查 + if iban is not None and not isinstance(iban, str): + raise TypeError("iban must be a string") + + # 检查必需参数 + if iban is None: + raise ValueError("iban parameter is required") + + try: + # Remove whitespace from IBAN + iban = iban.replace(" ", "") + + # Basic length and format check + if not (len(iban) >= 15 and len(iban) <= 34): + return {"valid": "False"} + + if not (iban[:2].isalpha() and iban[2:].isdigit()): + return {"valid": "False"} + + # Move first four characters to the end + rearranged = iban[4:] + iban[:4] + + # Replace letters with numbers (A=10, B=11, ..., Z=35) + numeric_iban = '' + for char in rearranged: + if char.isdigit(): + numeric_iban += char + else: + numeric_iban += str(ord(char.upper()) - ord('A') + 10) + + # Perform modulo 97 check + # Use step-by-step approach for very large numbers + remainder = 0 + for char in numeric_iban: + remainder = (remainder * 10 + int(char)) % 97 + + is_valid = remainder == 1 + return {"valid": "True" if is_valid else "False"} + except Exception as e: + raise RuntimeError(f"Error in iban_validate: {str(e)}") + + def matter_synthesizer(self, inputs): + import hashlib + + # 参数检查 + if not isinstance(inputs, dict): + raise TypeError("inputs must be a dictionary") + + # 获取参数 + blueprint = inputs.get("blueprint") + + # 类型检查 + if blueprint is not None and not isinstance(blueprint, str): + raise TypeError("blueprint must be a string") + + try: + # Get blueprint parameter as defined in interface + if blueprint is None: + blueprint = "" + + # Generate a unique item ID based on the blueprint + # This ensures the same blueprint always produces the same item + blueprint_hash = hashlib.sha256(blueprint.encode()).hexdigest()[:16] + + # Create a synthesized item with a deterministic ID based on blueprint + synthesized_item = f"synthesized_item_{blueprint_hash}" + + return {"output_slot": synthesized_item} + except Exception as e: + raise RuntimeError(f"Error in matter_synthesizer: {str(e)}") + + # --- Terminal Implementations --- + def terminal_1(self, inputs): + """ + terminal_1: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 只返回 text_output + - 只输入正确的 slot_b → 只返回 hex_output + - 同时输入正确的 slot_a 和 slot_b → 返回 item_dispenser(物品掉落) + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + # 检查哪些输入被提供了 + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值是否正确(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + expected_a = golden_inputs["slot_a"] + a_valid = str(slot_a) == str(expected_a) + + if has_b and "slot_b" in golden_inputs: + expected_b = golden_inputs["slot_b"] + b_valid = str(slot_b) == str(expected_b) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 item_dispenser + if has_a and has_b: + if a_valid and b_valid: + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 text_output + if has_a and not has_b: + if a_valid: + if "text_output" in golden_outputs: + result["text_output"] = golden_outputs["text_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 hex_output + if has_b and not has_a: + if b_valid: + if "hex_output" in golden_outputs: + result["hex_output"] = golden_outputs["hex_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def terminal_2(self, inputs): + """ + terminal_2: Terminal 节点,根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 text_result + - 同时输入正确的 num1 和 num2 → 返回 hex_result 和 math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + # 检查哪些输入被提供了 + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值是否正确(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + expected_num1 = golden_inputs["num1"] + num1_valid = str(num1) == str(expected_num1) + + if has_num2 and "num2" in golden_inputs: + expected_num2 = golden_inputs["num2"] + num2_valid = str(num2) == str(expected_num2) + + # 根据验证结果返回对应的输出 + result = {} + + # 如果同时提供了两个输入且都正确 → 返回 hex_result 和 math_token + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + # 至少有一个输入错误 + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 text_result + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "text_result" in golden_outputs: + result["text_result"] = golden_outputs["text_result"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def logic_terminal(self, inputs): + """ + Logic Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 slot_a → 返回 screen(部分输出) + - 只输入正确的 slot_b → 返回 screen 和 secondary_output + - 同时输入正确的 slot_a 和 slot_b → 返回 screen, secondary_output, item_dispenser + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + slot_a = inputs.get("slot_a") + slot_b = inputs.get("slot_b") + + has_a = slot_a is not None and slot_a != "" + has_b = slot_b is not None and slot_b != "" + + # 验证输入值(与 golden values 比较) + a_valid = False + b_valid = False + + if has_a and "slot_a" in golden_inputs: + a_valid = str(slot_a) == str(golden_inputs["slot_a"]) + + if has_b and "slot_b" in golden_inputs: + b_valid = str(slot_b) == str(golden_inputs["slot_b"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出(包括 item_dispenser) + if has_a and has_b: + if a_valid and b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + if "item_dispenser" in golden_outputs: + result["item_dispenser"] = golden_outputs["item_dispenser"] + return result + else: + incorrect_params = [] + correct_params = [] + if not a_valid: + incorrect_params.append("slot_a") + else: + correct_params.append("slot_a") + if not b_valid: + incorrect_params.append("slot_b") + else: + correct_params.append("slot_b") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 slot_a 且正确 → 返回 screen(部分输出) + if has_a and not has_b: + if a_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_a"} + + # 只提供 slot_b 且正确 → 返回 screen 和 secondary_output + if has_b and not has_a: + if b_valid: + if "screen" in golden_outputs: + result["screen"] = golden_outputs["screen"] + if "secondary_output" in golden_outputs: + result["secondary_output"] = golden_outputs["secondary_output"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: slot_b"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def math_terminal(self, inputs): + """ + Math Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 num1 或 num2(任一)→ 返回 result_display + - 同时输入正确的 num1 和 num2 → 返回 result_display, hex_result, math_token + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + num1 = inputs.get("num1") + num2 = inputs.get("num2") + + has_num1 = num1 is not None and num1 != "" + has_num2 = num2 is not None and num2 != "" + + # 验证输入值(与 golden values 比较) + num1_valid = False + num2_valid = False + + if has_num1 and "num1" in golden_inputs: + num1_valid = str(num1) == str(golden_inputs["num1"]) + + if has_num2 and "num2" in golden_inputs: + num2_valid = str(num2) == str(golden_inputs["num2"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_num1 and has_num2: + if num1_valid and num2_valid: + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + if "hex_result" in golden_outputs: + result["hex_result"] = golden_outputs["hex_result"] + if "math_token" in golden_outputs: + result["math_token"] = golden_outputs["math_token"] + return result + else: + incorrect_params = [] + correct_params = [] + if not num1_valid: + incorrect_params.append("num1") + else: + correct_params.append("num1") + if not num2_valid: + incorrect_params.append("num2") + else: + correct_params.append("num2") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供一个输入且正确 → 返回 result_display + if (has_num1 or has_num2): + if (has_num1 and num1_valid) or (has_num2 and num2_valid): + if "result_display" in golden_outputs: + result["result_display"] = golden_outputs["result_display"] + return result + else: + if has_num1 and not num1_valid: + return {"error": "Input validation failed. Incorrect parameters: num1"} + if has_num2 and not num2_valid: + return {"error": "Input validation failed. Incorrect parameters: num2"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + def crypt_terminal(self, inputs): + """ + Encryption Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 plaintext → 返回 status(部分输出) + - 同时输入正确的 plaintext 和 key → 返回 status, encrypted_hex, encryption_chip + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + plaintext = inputs.get("plaintext") + key = inputs.get("key") + + has_plaintext = plaintext is not None and plaintext != "" + has_key = key is not None and key != "" + + # 验证输入值(与 golden values 比较) + plaintext_valid = False + key_valid = False + + if has_plaintext and "plaintext" in golden_inputs: + plaintext_valid = str(plaintext) == str(golden_inputs["plaintext"]) + + if has_key and "key" in golden_inputs: + key_valid = str(key) == str(golden_inputs["key"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_plaintext and has_key: + if plaintext_valid and key_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + if "encrypted_hex" in golden_outputs: + result["encrypted_hex"] = golden_outputs["encrypted_hex"] + if "encryption_chip" in golden_outputs: + result["encryption_chip"] = golden_outputs["encryption_chip"] + return result + else: + incorrect_params = [] + correct_params = [] + if not plaintext_valid: + incorrect_params.append("plaintext") + else: + correct_params.append("plaintext") + if not key_valid: + incorrect_params.append("key") + else: + correct_params.append("key") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 plaintext 且正确 → 返回 status(部分输出) + if has_plaintext and not has_key: + if plaintext_valid: + if "status" in golden_outputs: + result["status"] = golden_outputs["status"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: plaintext"} + + # 只提供 key 但没有 plaintext + if has_key and not has_plaintext: + return {"error": "plaintext required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + def sequence_terminal(self, inputs): + """ + Sequence Terminal: 根据输入参数的正确性返回对应的输出 + + 逻辑: + - 只输入正确的 sequence → 返回 verification(部分输出) + - 同时输入正确的 sequence 和 checksum → 返回 verification, auth_code, access_card + - 输入错误 → 返回错误信息 + + 在离线 DAG 生成阶段,golden_outputs 存在但 golden_inputs 为空,直接返回所有 outputs。 + 在运行时评测阶段,golden_inputs 和 golden_outputs 都存在,根据输入验证返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段(使用 _init_* 参数) + # DAG 生成阶段:直接返回所有 init_outputs,不进行参数验证 + # 因为 init_inputs 可能只包含部分参数,其他参数从上游节点传递 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:根据输入验证返回对应输出 + sequence = inputs.get("sequence") + checksum = inputs.get("checksum") + + has_sequence = sequence is not None and sequence != "" + has_checksum = checksum is not None and checksum != "" + + # 验证输入值(与 golden values 比较) + sequence_valid = False + checksum_valid = False + + if has_sequence and "sequence" in golden_inputs: + sequence_valid = str(sequence) == str(golden_inputs["sequence"]) + + if has_checksum and "checksum" in golden_inputs: + checksum_valid = str(checksum) == str(golden_inputs["checksum"]) + + result = {} + + # 同时提供两个输入且都正确 → 返回所有输出 + if has_sequence and has_checksum: + if sequence_valid and checksum_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + if "auth_code" in golden_outputs: + result["auth_code"] = golden_outputs["auth_code"] + if "access_card" in golden_outputs: + result["access_card"] = golden_outputs["access_card"] + return result + else: + incorrect_params = [] + correct_params = [] + if not sequence_valid: + incorrect_params.append("sequence") + else: + correct_params.append("sequence") + if not checksum_valid: + incorrect_params.append("checksum") + else: + correct_params.append("checksum") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 只提供 sequence 且正确 → 返回 verification(部分输出) + if has_sequence and not has_checksum: + if sequence_valid: + if "verification" in golden_outputs: + result["verification"] = golden_outputs["verification"] + return result + else: + return {"error": "Input validation failed. Incorrect parameters: sequence"} + + # 只提供 checksum 但没有 sequence + if has_checksum and not has_sequence: + return {"error": "sequence required"} + + # 没有提供任何输入 + return {"error": "No valid inputs provided"} + + # --- Additional File Tools --- + + def zip_unzip_file(self, inputs): + """ZIP 解压文件工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def zip_unzip_item(self, inputs): + """ZIP 解压道具工具(模拟) + + 在 DAG 生成阶段,直接返回 init_outputs,不验证输入。 + 在运行时评测阶段,验证输入并返回对应输出。 + """ + # 优先使用 _golden_*,如果不存在则回退到 _init_* + golden_outputs = inputs.get("_golden_outputs") or inputs.get("_init_outputs", {}) + golden_inputs = inputs.get("_golden_inputs") or inputs.get("_init_inputs", {}) + + # 判断是否在 DAG 生成阶段 + is_dag_generation = "_init_outputs" in inputs and "_golden_outputs" not in inputs + + if is_dag_generation: + return dict(golden_outputs) + + # 评测阶段但没有 golden_inputs,也直接返回 outputs + if not golden_inputs: + return dict(golden_outputs) + + # 运行时评测阶段:验证输入 + zip_id = inputs.get("zip_id") + password = inputs.get("password") + + has_zip_id = zip_id is not None and zip_id != "" + has_password = password is not None and password != "" + + # 验证输入值(与 golden values 比较) + zip_id_valid = False + password_valid = False + + if has_zip_id and "zip_id" in golden_inputs: + zip_id_valid = str(zip_id) == str(golden_inputs["zip_id"]) + + if has_password and "password" in golden_inputs: + password_valid = str(password) == str(golden_inputs["password"]) + + # 两个输入都提供且都正确 → 返回所有输出 + if has_zip_id and has_password: + if zip_id_valid and password_valid: + return dict(golden_outputs) + else: + incorrect_params = [] + correct_params = [] + if not zip_id_valid: + incorrect_params.append("zip_id") + else: + correct_params.append("zip_id") + if not password_valid: + incorrect_params.append("password") + else: + correct_params.append("password") + + error_msg = f"Input validation failed. Incorrect parameters: {', '.join(incorrect_params)}" + if correct_params: + error_msg += f". Correct parameters: {', '.join(correct_params)}" + return {"error": error_msg} + + # 没有提供完整输入 + missing = [] + if not has_zip_id: + missing.append("zip_id") + if not has_password: + missing.append("password") + return {"error": "Missing required inputs: " + ", ".join(missing)} + + def code_py_exec(self, inputs): + """Python 代码执行工具 + + 这是一个真实执行的工具,在 DAG 生成阶段和运行时评测阶段都会执行代码。 + 输入: code (Python 代码字符串) + 输出: stdout (标准输出,包含执行结果和错误信息) + + 特殊行为: + - 如果代码定义了 main() 函数,会自动调用它 + - 如果执行出错,错误信息会包含在 stdout 中 + """ + code = inputs.get("code", "") + + if not code: + return {"stdout": "Error: No code provided"} + + try: + # 创建一个受限的执行环境 + import io + import sys + + # 捕获标准输出和标准错误 + old_stdout = sys.stdout + old_stderr = sys.stderr + sys.stdout = io.StringIO() + sys.stderr = io.StringIO() + + # 执行代码 + exec_globals = {"__builtins__": __builtins__} + exec_locals = {} + exec(code, exec_globals, exec_locals) + + # 如果定义了 main() 函数,自动调用它 + if 'main' in exec_locals and callable(exec_locals['main']): + exec_locals['main']() + + # 获取输出 + stdout_value = sys.stdout.getvalue() + stderr_value = sys.stderr.getvalue() + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 合并 stdout 和 stderr + output = stdout_value + if stderr_value: + output += ("\n" if output else "") + f"[stderr] {stderr_value}" + + # 如果没有任何输出,尝试返回 result 变量的值 + if not output: + result = exec_locals.get("_result") or exec_locals.get("result") + if result is not None: + output = str(result) + + return {"stdout": output if output else "(no output)"} + + except Exception as e: + # 恢复标准输出和错误输出 + sys.stdout = old_stdout + sys.stderr = old_stderr + + # 返回错误信息 + return {"stdout": f"Error: {type(e).__name__}: {str(e)}"} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.Dockerfile b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1b77e0d8f92199505b6d138c374a5ec34037bfc --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +RUN apt-get update && apt-get install -y --no-install-recommends libseccomp2 && rm -rf /var/lib/apt/lists/* +COPY requirements.txt /app/requirements.txt +RUN pip install --no-cache-dir -r /app/requirements.txt +WORKDIR /app +COPY worker.py child.py /app/ +COPY upstream/simulator.py /app/simulator.py +CMD ["uvicorn", "worker:app", "--host", "0.0.0.0", "--port", "8001", "--workers", "1", "--no-access-log"] diff --git a/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.py b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..c25c766fb317c67678ccccf489e9125cdac06471 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/environment/puzzle/worker.py @@ -0,0 +1,73 @@ +"""Stateless Python tool worker. Never receives a scenario or reference values.""" + +import json +import os +import signal +import subprocess +import sys +import tempfile +import threading + +from fastapi import FastAPI +from pydantic import BaseModel, ConfigDict + +app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) +lock = threading.Lock() + + +class Execution(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + code: str + + +@app.get("/health") +def health(): + return {"ok": True} + + +@app.post("/execute") +def execute(request: Execution): + if len(request.code.encode()) > 65536: + return {"stdout": "Error: code exceeds 64 KiB limit"} + with lock, tempfile.TemporaryDirectory(prefix="escape-code-") as directory: + os.chown(directory, 65534, 65534) + with tempfile.TemporaryFile() as output: + process = subprocess.Popen( + [sys.executable, "-I", "/app/child.py"], + stdin=subprocess.PIPE, + stdout=output, + stderr=subprocess.DEVNULL, + cwd=directory, + user=65534, + group=65534, + extra_groups=[], + start_new_session=True, + env={"PATH": "/usr/local/bin:/usr/bin:/bin"}, + ) + try: + process.communicate( + json.dumps({"code": request.code}).encode(), timeout=5 + ) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + return {"stdout": "Error: Python execution timed out"} + finally: + # Also remove children still in the process group after normal exit. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + output.seek(0) + value = output.read(65537) + if len(value) > 65536 or process.returncode != 0: + return { + "stdout": "Error: Python execution exceeded a resource limit or failed" + } + try: + result = json.loads(value) + if not isinstance(result.get("stdout"), str): + raise ValueError("Invalid worker response") + return result + except (ValueError, AttributeError): + return {"stdout": "Error: Python execution returned invalid output"} diff --git a/tasks/agentescape-10-skeleton-5198ed25/instruction.md b/tasks/agentescape-10-skeleton-5198ed25/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5669b47f2084a4e557094f231bb09768f3f6e015 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/instruction.md @@ -0,0 +1,18 @@ +# Escape the room + +Discover the victory string and submit it with `escape submit-answer`. +Start with `escape observe`. This returns the room, available information, visible entities, and victory node ID. + +Use these commands (JSON responses): + +```sh +escape investigate NODE_ID +escape tool-call NODE_ID --arguments-json '{"parameter": "value"}' +escape use-item NODE_ID --arguments-json '{"parameter": "value"}' +escape submit-answer 'exact victory string' +escape state +``` + +Investigate tools to learn their interfaces and clues. Investigate items for their contents; items requiring parameters use `use-item`. Tool calls can reveal new entities. A hidden-item hint means investigate that tool again. Use node IDs and parameter names exactly as returned. Carry outputs into subsequent calls; do not guess intermediate values. The victory string can be code, a number encoded as text, or other arbitrary text. + +Only successful answer submission completes the task. Wrong submissions allow another attempt. You have **500 puzzle actions**; invalid actions count. `observe` and `state` do not count. This action limit differs from the original evaluator's model-turn limit. Do not reset or replace the environment. diff --git a/tasks/agentescape-10-skeleton-5198ed25/solution/oracle.py b/tasks/agentescape-10-skeleton-5198ed25/solution/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..b67459607cafc1735ec590373b4e4f851e9ffb11 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/solution/oracle.py @@ -0,0 +1,133 @@ +"""Reference solver: use trusted inputs, but obtain the answer through public actions.""" + +import json +import urllib.request +from pathlib import Path + + +def http_action(base_url, payload): + request = urllib.request.Request( + base_url + "/action", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def solve(scenario, act, observe): + nodes = {node["id"]: node for node in scenario["nodes"]} + visible = {entity["id"] for entity in observe["available_entities"]} + solved = set() + seen_outputs = {} + action_count = 0 + + def call(payload): + nonlocal action_count + action_count += 1 + response = act(payload) + visible.update(entity["id"] for entity in response.get("newly_revealed", [])) + if ( + response.get("episode", {}).get("termination_reason") + == "infrastructure_error" + ): + raise RuntimeError("Infrastructure failure") + return response + + for _round in range(len(nodes) + 2): + progress = False + for node_id, node in nodes.items(): + if node_id not in visible or node_id in solved: + continue + # Preserve graph order for data inputs; trigger/drop edges express visibility. + predecessors = [ + edge["source_id"] + for edge in scenario["edges"] + if edge["target_id"] == node_id + and edge["connection_type"] not in ("Item", "Hidden_Item") + ] + if any(pred not in solved for pred in predecessors): + continue + info = call({"action": "investigate", "node_id": node_id}) + if not info.get("ok"): + raise RuntimeError(f"Investigation failed: {node_id}: {info}") + inputs = { + port["name"]: port["value"] + for port in node.get("inputs", []) + if "value" in port + } + if node["type"] == "Tool": + result = call( + {"action": "tool_call", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok") or result.get("output_values", {}).get("error"): + raise RuntimeError(f"Tool failed: {node_id}: {result}") + output = result.get("output_values", {}) + if node.get("template_id") in ("terminal_1", "terminal_2"): + slots = { + port["name"]: inputs[port["name"]] + for port in node["inputs"] + if port["type"] not in ("Item", "Hidden_Item") + and port["name"] in inputs + } + triggers = { + key: value for key, value in inputs.items() if key not in slots + } + for key, value in slots.items(): + partial = call( + { + "action": "tool_call", + "node_id": node_id, + "arguments": {**triggers, key: value}, + } + ) + if partial.get("ok"): + output.update(partial.get("output_values", {})) + # HIDDEN_ITEM tool drops only occur on subsequent investigation. + call({"action": "investigate", "node_id": node_id}) + elif info.get("required_inputs"): + result = call( + {"action": "use_item", "node_id": node_id, "arguments": inputs} + ) + if not result.get("ok"): + raise RuntimeError(f"Item failed: {node_id}: {result}") + output = result.get("content") + else: + output = info.get("content") + seen_outputs[node_id] = output + solved.add(node_id) + progress = True + win_id = scenario["metadata"]["win_node_id"] + if win_id in solved and (len(solved) == len(nodes) or not progress): + outputs = seen_outputs[win_id] + if not outputs: + raise RuntimeError(f"Victory node returned no output: {win_id}") + # Upstream grades its first stored output port, independent of response order. + victory_port = next( + port["name"] for port in nodes[win_id]["outputs"] if "value" in port + ) + answer = outputs[victory_port] if isinstance(outputs, dict) else outputs + result = call({"action": "submit_answer", "answer": answer}) + if not result.get("is_win"): + raise RuntimeError(f"Victory submission failed: {result}") + return {"won": True, "actions": action_count, "visited_nodes": len(solved)} + if not progress: + raise RuntimeError(f"No progress: visible={visible}, solved={solved}") + raise RuntimeError("Reference solver exceeded graph traversal limit") + + +if __name__ == "__main__": + import os + + base = os.environ.get("ESCAPE_URL", "http://puzzle:8000") + with urllib.request.urlopen(base + "/observation", timeout=20) as response: + observation = json.load(response) + print( + json.dumps( + solve( + json.loads(Path("/solution/scenario.json").read_text()), + lambda payload: http_action(base, payload), + observation, + ) + ) + ) diff --git a/tasks/agentescape-10-skeleton-5198ed25/solution/scenario.json b/tasks/agentescape-10-skeleton-5198ed25/solution/scenario.json new file mode 100644 index 0000000000000000000000000000000000000000..bc1428cbde59b8a30aeded36ce92d88a77944677 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/solution/scenario.json @@ -0,0 +1,735 @@ +{ + "metadata": { + "total_nodes": 10, + "total_edges": 13, + "win_node_id": "json_get", + "win_condition": { + "type": "tool_output", + "node_id": "json_get", + "output_port": "values", + "output_type": "Text_Generic", + "description": "Execute JSON Getter and get the output from port 'values'" + }, + "source_init": { + "source_nodes": [ + "json_get", + "zip_unzip_file", + "zip_unzip_file_1456", + "zip_unzip_file_51c7", + "terminal_1", + "code_py_exec_075b", + "graph_shortest_path", + "item_7", + "csv_query" + ], + "by_node": { + "json_get": { + "node_name": "JSON Getter", + "node_type": "Tool", + "template_id": "json_get", + "init_inputs": {}, + "init_outputs": { + "values": { + "type": "Text_Generic", + "description": "Extracted values" + } + } + }, + "zip_unzip_file": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": {}, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "zip_unzip_file_1456": { + "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_51c7": { + "node_name": "Zip Unzipper", + "node_type": "Tool", + "template_id": "zip_unzip_file", + "init_inputs": { + "zip_id": { + "type": "File_Id", + "description": "Zip file ID" + } + }, + "init_outputs": { + "files": { + "type": "File_Id", + "description": "Extracted file ID" + } + } + }, + "terminal_1": { + "node_name": "", + "node_type": "Tool", + "template_id": "terminal_1", + "init_inputs": {}, + "init_outputs": { + "text_output": { + "type": "Text_Generic", + "description": "Text output when only slot_a is provided" + }, + "hex_output": { + "type": "Hex_String", + "description": "Hex output when only slot_b is provided" + } + } + }, + "code_py_exec_075b": { + "node_name": "Python Executor", + "node_type": "Tool", + "template_id": "code_py_exec", + "init_inputs": { + "code": { + "type": "Code_Python", + "description": "Python code" + } + }, + "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" + } + } + }, + "item_7": { + "node_name": "", + "node_type": "Item", + "template_id": "item_7", + "init_inputs": {}, + "init_outputs": { + "content": { + "type": "Code_Python", + "description": "The integer" + } + } + }, + "csv_query": { + "node_name": "CSV Query", + "node_type": "Tool", + "template_id": "csv_query", + "init_inputs": { + "file_id": { + "type": "File_Id", + "description": "CSV file ID" + }, + "select": { + "type": "Text_Generic", + "description": "Columns to select" + }, + "where": { + "type": "Text_Generic", + "description": "Where clause" + } + }, + "init_outputs": { + "rows": { + "type": "Text_Generic", + "description": "Result rows" + } + } + } + } + }, + "initial_values": { + "json_get": { + "init_inputs": {}, + "init_outputs": { + "values": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + }, + "zip_unzip_file": { + "init_inputs": {}, + "init_outputs": { + "files": "extracted_config_v2.json" + } + }, + "zip_unzip_file_1456": { + "init_inputs": {}, + "init_outputs": { + "files": "legacy_data_dump.xml" + } + }, + "zip_unzip_file_51c7": { + "init_inputs": { + "zip_id": "project_blue_archive.zip" + }, + "init_outputs": { + "files": "blueprint_schematic.cad" + } + }, + "terminal_1": { + "init_inputs": {}, + "init_outputs": { + "text_output": "$.store.inventory[*].id", + "hex_output": "1a2b3c4d5e6f7890" + } + }, + "code_py_exec_075b": { + "init_inputs": { + "code": "import time\nprint(1772962913.642455)" + }, + "init_outputs": {} + }, + "graph_shortest_path": { + "init_inputs": { + "file_id": "regional_traffic_map.json" + }, + "init_outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "83746592018374659201" + } + }, + "item_7": { + "init_inputs": {}, + "init_outputs": { + "content": "target_value = 1024" + } + }, + "csv_query": { + "init_inputs": { + "file_id": "customer_transactions.csv", + "select": "transaction_id, date, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "init_outputs": { + "rows": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + } + }, + "intro_narrative": "You stand before the ruined gates of the Aetherial Spire, a legendary tower where the Grand Archmage hid the realm's greatest secret. The air shimmers with residual arcane energy, thick, ancient, and deeply intertwined with complex, puzzle-like enchantments. Your ultimate objective is to awaken the Oracle's Pedestal at the very peak of the spire, which holds the truth to saving your kingdom. However, the path is sealed by layers of magical security. You must navigate a labyrinth of mystical artifacts, locked coffers, and magical weavers that demand specific arcane inputs to operate. Gather the scattered tools, consult the ancient texts, and figure out how each artifact connects to the next. The spire is unstable, and time is running out. You must unravel the Grand Archmage's final enchantment before the entire structure collapses into the void forever.", + "narrative_style": "fantasy" + }, + "nodes": [ + { + "id": "json_get", + "name": "JSON Getter", + "description": "Extract values by simple JSONPath.", + "type": "Tool", + "template_id": "json_get", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "JSON file ID", + "value": "extracted_config_v2.json" + }, + { + "name": "jsonpath", + "type": "Text_Generic", + "description": "JSONPath expression", + "value": "$.store.inventory[*].id" + } + ], + "outputs": [ + { + "name": "values", + "type": "Text_Generic", + "description": "Extracted values", + "value": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + ], + "init": { + "inputs": {}, + "outputs": { + "values": "[\"entry_alpha\", \"entry_beta\", \"entry_gamma\"]" + } + }, + "narrative": "This is the Oracle's Pedestal. It requires inputs from both the Inner Sanctum Chest and the Celestial Astrolabe to reveal the final truth." + }, + { + "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": "legacy_data_dump.xml" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "extracted_config_v2.json" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "extracted_config_v2.json" + } + }, + "narrative": "This is the Inner Sanctum Chest. It requires inputs from both the Sunlit Strongbox and the Rune Weaver to open." + }, + { + "id": "zip_unzip_file_1456", + "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_schematic.cad" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "legacy_data_dump.xml" + } + ], + "init": { + "inputs": {}, + "outputs": { + "files": "legacy_data_dump.xml" + } + }, + "narrative": "This is the Sunlit Strongbox. It requires inputs from both the Moonlit Coffer and the Rune Weaver to break its seals." + }, + { + "id": "code_py_exec", + "name": "Python Executor", + "description": "Run limited Python: only safe builtins.", + "type": "Tool", + "template_id": "code_py_exec", + "initial_visible": false, + "is_revealed": false, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "code", + "type": "Code_Python", + "description": "Python code", + "value": "target_value = 1024" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "(no output)" + } + ], + "narrative": "This is the Rune Weaver, a magical loom. It requires input from the Ancient Scroll to begin its weaving." + }, + { + "id": "zip_unzip_file_51c7", + "name": "Zip Unzipper", + "description": "Unzip a password-protected zip file by id.", + "type": "Tool", + "template_id": "zip_unzip_file", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "trigger_item", + "type": "Item", + "description": "Required item to unlock this tool" + }, + { + "name": "zip_id", + "type": "File_Id", + "description": "Zip file ID", + "value": "project_blue_archive.zip" + }, + { + "name": "password", + "type": "Text_Generic", + "description": "Password", + "value": "(no output)" + } + ], + "outputs": [ + { + "name": "files", + "type": "File_Id", + "description": "Extracted file ID", + "value": "blueprint_schematic.cad" + } + ], + "init": { + "inputs": { + "zip_id": "project_blue_archive.zip" + }, + "outputs": { + "files": "blueprint_schematic.cad" + } + }, + "narrative": "This is the Moonlit Coffer. It requires input from the Rune Weaver to shatter its magical 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": "1772962913.642455\n" + }, + { + "name": "slot_b", + "type": "Big_Int", + "description": "Input Slot B", + "value": "83746592018374659201" + } + ], + "outputs": [ + { + "name": "text_output", + "type": "Text_Generic", + "description": "Text output when only slot_a is provided", + "value": "$.store.inventory[*].id" + }, + { + "name": "hex_output", + "type": "Hex_String", + "description": "Hex output when only slot_b is provided", + "value": "1a2b3c4d5e6f7890" + }, + { + "name": "item_dispenser", + "type": "Item", + "description": "Item output when both slots are provided" + } + ], + "init": { + "inputs": {}, + "outputs": { + "text_output": "$.store.inventory[*].id", + "hex_output": "1a2b3c4d5e6f7890" + } + }, + "narrative": "This is the Celestial Astrolabe. It requires inputs from both the Prophecy Obelisk and the Leyline Map to align the stars." + }, + { + "id": "code_py_exec_075b", + "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": "import time\nprint(1772962913.642455)" + } + ], + "outputs": [ + { + "name": "stdout", + "type": "Text_Generic", + "description": "Standard Output (includes errors if any)", + "value": "1772962913.642455\n" + } + ], + "init": { + "inputs": { + "code": "import time\nprint(1772962913.642455)" + }, + "outputs": {} + }, + "narrative": "A towering Prophecy Obelisk inscribed with glowing celestial runes, waiting to be deciphered." + }, + { + "id": "graph_shortest_path", + "name": "Shortest Path Finder", + "description": "Shortest path on graph json file with edges list.", + "type": "Tool", + "template_id": "graph_shortest_path", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "Graph JSON file ID", + "value": "regional_traffic_map.json" + }, + { + "name": "src", + "type": "Text_Generic", + "description": "Source node", + "value": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + }, + { + "name": "dst", + "type": "Text_Generic", + "description": "Destination node", + "value": "1772962913.642455\n" + } + ], + "outputs": [ + { + "name": "path", + "type": "Text_Generic", + "description": "Path list", + "value": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]" + }, + { + "name": "cost", + "type": "Big_Int", + "description": "Path cost", + "value": "83746592018374659201" + } + ], + "init": { + "inputs": { + "file_id": "regional_traffic_map.json" + }, + "outputs": { + "path": "[\"Node_Alpha\", \"Node_Beta\", \"Node_Gamma\", \"Node_Delta\", \"Node_Epsilon\"]", + "cost": "83746592018374659201" + } + }, + "narrative": "This is the Leyline Map. It requires inputs from both the Prophecy Obelisk and the Archivist's Ledger to chart the correct path." + }, + { + "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": "target_value = 1024" + } + ], + "init": { + "inputs": {}, + "outputs": { + "content": "target_value = 1024" + } + }, + "narrative": "A fragile Ancient Scroll radiating a faint, ancient magical aura." + }, + { + "id": "csv_query", + "name": "CSV Query", + "description": "Query CSV: select columns and simple WHERE.", + "type": "Tool", + "template_id": "csv_query", + "initial_visible": true, + "is_revealed": true, + "inputs": [ + { + "name": "file_id", + "type": "File_Id", + "description": "CSV file ID", + "value": "customer_transactions.csv" + }, + { + "name": "select", + "type": "Text_Generic", + "description": "Columns to select", + "value": "transaction_id, date, amount" + }, + { + "name": "where", + "type": "Text_Generic", + "description": "Where clause", + "value": "amount > 1000 AND status = 'completed'" + } + ], + "outputs": [ + { + "name": "rows", + "type": "Text_Generic", + "description": "Result rows", + "value": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + ], + "init": { + "inputs": { + "file_id": "customer_transactions.csv", + "select": "transaction_id, date, amount", + "where": "amount > 1000 AND status = 'completed'" + }, + "outputs": { + "rows": "[{\"transaction_id\": \"TX99\", \"date\": \"2023-10-27\", \"amount\": 1500}, {\"transaction_id\": \"TX100\", \"date\": \"2023-10-28\", \"amount\": 2000}]" + } + }, + "narrative": "A thick, leather-bound Archivist's Ledger containing the long-forgotten records of the realm." + } + ], + "edges": [ + { + "source_id": "zip_unzip_file", + "target_id": "json_get", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "file_id" + }, + { + "source_id": "zip_unzip_file_1456", + "target_id": "zip_unzip_file", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "zip_unzip_file_51c7", + "target_id": "zip_unzip_file_1456", + "connection_type": "File_Id", + "source_port": "files", + "target_port": "zip_id" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_51c7", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "terminal_1", + "target_id": "code_py_exec", + "connection_type": "Item", + "source_port": "item_dispenser", + "target_port": "trigger_item" + }, + { + "source_id": "terminal_1", + "target_id": "json_get", + "connection_type": "Text_Generic", + "source_port": "text_output", + "target_port": "jsonpath" + }, + { + "source_id": "code_py_exec_075b", + "target_id": "terminal_1", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "slot_a" + }, + { + "source_id": "code_py_exec", + "target_id": "zip_unzip_file_1456", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "password" + }, + { + "source_id": "graph_shortest_path", + "target_id": "terminal_1", + "connection_type": "Big_Int", + "source_port": "cost", + "target_port": "slot_b" + }, + { + "source_id": "item_7", + "target_id": "code_py_exec", + "connection_type": "Code_Python", + "source_port": "content", + "target_port": "code" + }, + { + "source_id": "code_py_exec_075b", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "stdout", + "target_port": "dst" + }, + { + "source_id": "csv_query", + "target_id": "graph_shortest_path", + "connection_type": "Text_Generic", + "source_port": "rows", + "target_port": "src" + } + ] +} \ No newline at end of file diff --git a/tasks/agentescape-10-skeleton-5198ed25/solution/solve.sh b/tasks/agentescape-10-skeleton-5198ed25/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45ad2242e787d15326592822268083bbba1fd0e1 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python -I /solution/oracle.py diff --git a/tasks/agentescape-10-skeleton-5198ed25/task.toml b/tasks/agentescape-10-skeleton-5198ed25/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b935231c17520e932b91b3009250c868ffef67fb --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/task.toml @@ -0,0 +1,38 @@ +schema_version = "1.4" +source = "https://github.com/AGI-Eval-Official/Repo-of-AgentEscapeBench" + +[[artifacts]] +source = "/evidence/final.json" +service = "puzzle" + +[[artifacts]] +source = "/evidence/trace.jsonl" +service = "puzzle" + +[task] +name = "edbeeching/agentescape-10-skeleton-5198ed25" +version = "0.1.0" + +[metadata] +difficulty = 10 +source_revision = "03742c79f48646e0130886e18e3e79798cf8edd7" +scenario_sha256 = "62110038d2eb8289faea9213dd72b601ba569da6687fa63b0cd7d6544af3e7c7" +protocol = "harbor-cli-action-budget-v1" +max_actions = 500 + +[agent] +timeout_sec = 1200 + +[environment] +build_timeout_sec = 900 +cpus = 1 +memory_mb = 1024 + +[verifier] +environment_mode = "separate" +timeout_sec = 60 + +[[verifier.collect]] +service = "puzzle" +command = "python -I /app/export.py" +timeout_sec = 15 diff --git a/tasks/agentescape-10-skeleton-5198ed25/tests/Dockerfile b/tasks/agentescape-10-skeleton-5198ed25/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1c9a09f6b84c450acbf2127e521987476905b8b --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/tests/Dockerfile @@ -0,0 +1,2 @@ +FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f +COPY . /tests/ diff --git a/tasks/agentescape-10-skeleton-5198ed25/tests/expected.json b/tasks/agentescape-10-skeleton-5198ed25/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..a1b3c7eabcd95abb461a20d303a1d8a05aa51ab4 --- /dev/null +++ b/tasks/agentescape-10-skeleton-5198ed25/tests/expected.json @@ -0,0 +1 @@ +{"scenario_sha256": "62110038d2eb8289faea9213dd72b601ba569da6687fa63b0cd7d6544af3e7c7", "max_actions": 500} \ No newline at end of file