ManipulationArena / release /engine /modules /environment_hooks-00268fd55e31.py
krystal7's picture
Add files using upload-large-folder tool
04d5e92 verified
Raw History Blame Contribute Delete
1.89 kB
"""Generic JSON protocol changes, with no attack-action or content taxonomy."""
from __future__ import annotations
import copy
def apply_patch(document, operations):
result = copy.deepcopy(document)
for operation in operations:
path = operation["path"]
if path == "":
if operation["op"] in {"add", "replace"}:
result = copy.deepcopy(operation["value"])
continue
raise ValueError("root patch requires add or replace")
if not isinstance(path, str) or not path.startswith("/"):
raise ValueError("patch path must be a JSON pointer")
parts = [part.replace("~1", "/").replace("~0", "~") for part in path[1:].split("/")]
parent = result
for part in parts[:-1]:
parent = parent[int(part)] if isinstance(parent, list) else parent[part]
key = parts[-1]
if isinstance(parent, list):
index = len(parent) if key == "-" else int(key)
if operation["op"] == "remove": del parent[index]
elif operation["op"] == "add": parent.insert(index, copy.deepcopy(operation["value"]))
elif operation["op"] == "replace": parent[index] = copy.deepcopy(operation["value"])
else: raise ValueError("unsupported JSON patch operation")
elif operation["op"] == "remove": del parent[key]
elif operation["op"] in {"add", "replace"}: parent[key] = copy.deepcopy(operation["value"])
else: raise ValueError("unsupported JSON patch operation")
return result
def transform_response(response, *, method, target, state):
transformed = response
for rule in state.get("protocol_patches", []):
if rule.get("method", method) == method and rule.get("target", "*") in {"*", target}:
transformed = apply_patch(transformed, rule.get("patches", []))
return transformed