Agent Zero AI framework
fix(prompts): strip JSON fences at render time
Alessandro9f1e24a2dbc6
diff --git a/AGENTS.md b/AGENTS.mdindex 3da3cebb6..c0fd03f43 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -29,6 +29,7 @@- Use Linux paths and commands in examples.- When a live Dockerized Agent Zero target is explicitly named, verify that exact runtime instead of assuming a fixed localhost port.- Message-loop completion flows through a response tool with `break_loop`; plain or malformed Chat Completions text enters repair, and native Responses output text is normalized through the same response-tool path.+- Prompt Markdown may retain fenced JSON examples for readability; final system-prompt rendering removes only their JSON fence markers before model calls and preserves non-JSON fences.- Copy live core-plugin changes back into tracked source under `plugins/`.- Develop new custom plugins under ignored `usr/plugins/`; tracked bundled plugins live under `plugins/`.- Use the framework runtime for backend and plugin-hook verification, not the separate agent execution runtime.diff --git a/agent.py b/agent.pyindex c20a7b38b..62beb8bc1 100644--- a/agent.py+++ b/agent.py@@ -568,8 +568,10 @@ class Agent:"message_loop_prompts_after", self, loop_data=loop_data)- # concatenate system prompt- system_text = "\n\n".join(loop_data.system)+ # concatenate system prompt and remove JSON fence markers from examples+ system_text = files.remove_code_fences(+ "\n\n".join(loop_data.system), language="json"+ )# join protocol and extrasprotocol = self._build_context_message(diff --git a/helpers/files.py b/helpers/files.pyindex c77ab54cf..6fb7643b9 100644--- a/helpers/files.py+++ b/helpers/files.py@@ -433,7 +433,14 @@ def find_existing_paths_by_pattern(pattern: str):return matches-def remove_code_fences(text):+def remove_code_fences(text, language: str | None = None):+ if language:+ pattern = (+ rf"(?ims)^[ \t]*(```|~~~)[ \t]*{re.escape(language)}[ \t]*\r?\n"+ r"(.*?)^[ \t]*\1[ \t]*\r?$"+ )+ return re.sub(pattern, lambda match: match.group(2), text)+# Pattern to match code fences with optional language specifierpattern = r"(```|~~~)(.*?\n)(.*?)(\1)"diff --git a/helpers/files.py.dox.md b/helpers/files.py.dox.mdindex b4f153240..086886e24 100644--- a/helpers/files.py.dox.md+++ b/helpers/files.py.dox.md@@ -33,7 +33,7 @@- `find_file_in_dirs(_filename: str, _directories: list[str])`: This function searches for a filename in a list of directories in order.- `get_unique_filenames_in_dirs(dir_paths: list[str], pattern: str=..., type: Literal['file', 'dir', 'any']=...)`- `find_existing_paths_by_pattern(pattern: str)`-- `remove_code_fences(text)`+- `remove_code_fences(text, language: str | None=...)`: Remove every code fence, or only fences for one language while preserving their contents.- `is_full_json_template(text)`- `write_file(relative_path: str, content: str, encoding: str=...)`- `delete_file(relative_path: str)`@@ -55,7 +55,7 @@## Key Concepts-- Important called helpers/classes observed in the source: `os.path.dirname`, `os.path.abspath`, `find_file_in_dirs`, `is_full_json_template`, `remove_code_fences`, `evaluate_text_conditions`, `replace_placeholders_text`, `process_includes`, `re.compile`, `_process`, `get_abs_path`, `is_probably_binary_bytes`, `replace_value`, `re.sub`, `os.path.normpath`, `FileNotFoundError`, `result.sort`, `glob.glob`, `matches.sort`, `re.fullmatch`.+- Important called helpers/classes observed in the source: `os.path.dirname`, `os.path.abspath`, `find_file_in_dirs`, `is_full_json_template`, `remove_code_fences`, `evaluate_text_conditions`, `replace_placeholders_text`, `process_includes`, `re.compile`, `re.escape`, `_process`, `get_abs_path`, `is_probably_binary_bytes`, `replace_value`, `re.sub`, `os.path.normpath`, `FileNotFoundError`, `result.sort`, `glob.glob`, `matches.sort`, `re.fullmatch`.- Keep request/response, tool, or helper semantics documented here at the same time as source changes.## Work Guidancediff --git a/prompts/agent.system.main.communication.md b/prompts/agent.system.main.communication.mdindex 4eb01ff9b..0d365fcf4 100644--- a/prompts/agent.system.main.communication.md+++ b/prompts/agent.system.main.communication.md@@ -18,6 +18,7 @@Fences in the examples below are documentation formatting only. Your actual output starts with `{` and ends with `}` — no fences, no language tag, no prose.### Response example+~~~json{"thoughts": ["instructions?",@@ -32,5 +33,6 @@ Fences in the examples below are documentation formatting only. Your actual outp"arg2": "val2"}}+~~~{{ include "agent.system.main.communication_additions.md" }}diff --git a/tests/test_default_prompt_budget.py b/tests/test_default_prompt_budget.pyindex 92886a4f2..3825844d1 100644--- a/tests/test_default_prompt_budget.py+++ b/tests/test_default_prompt_budget.py@@ -19,7 +19,7 @@ def _iter_prompt_files():yield from prompts_dir.rglob("*.md")-async def _build_system_text(profile: str = "agent0") -> str:+async def _build_system_text(profile: str = "agent0", rendered: bool = False) -> str:old_args = dict(runtime.args)runtime.args.clear()runtime.args["dockerized"] = "true"@@ -34,6 +34,9 @@ async def _build_system_text(profile: str = "agent0") -> str:set_current=False,)try:+ if rendered:+ prompt = await ctx.agent0.prepare_prompt(ctx.agent0.loop_data)+ return str(prompt[0].content)system = await ctx.agent0.get_system_prompt(ctx.agent0.loop_data)return "\n\n".join(system)finally:@@ -45,6 +48,7 @@ async def _build_system_text(profile: str = "agent0") -> str:@pytest.mark.asyncioasync def test_default_agent0_prompt_budget_and_guardrails():system_text = await _build_system_text()+ rendered_system_text = await _build_system_text(rendered=True)communication_prompt = (PROJECT_ROOT / "prompts" / "agent.system.main.communication.md").read_text(encoding="utf-8")@@ -66,7 +70,9 @@ async def test_default_agent0_prompt_budget_and_guardrails():assert '"tool_name": "memory_load"' in system_textassert "informative but tight" in system_textassert "Your actual output starts with `{` and ends with `}`" in system_text- assert "~~~json" not in communication_prompt+ assert "~~~json" in communication_prompt+ assert "~~~json" not in rendered_system_text+ assert "```json" not in rendered_system_textassert "# code_execution_remote tool" not in system_textassert "# text_editor_remote tool" not in system_textassert "### computer_use_remote" not in system_text@@ -76,6 +82,40 @@ async def test_default_agent0_prompt_budget_and_guardrails():assert "Computer Use enablement is scoped to the current CLI session" not in system_text+ "profile", ["agent0", "default", "developer", "researcher", "tiny-local"]+)+async def test_rendered_profiles_strip_json_fences(profile: str):+ system_text = await _build_system_text(profile, rendered=True)++ assert "~~~json" not in system_text+ assert "```json" not in system_text++ if profile == "researcher":+ assert "~~~python" in system_text+++def test_remove_code_fences_can_target_json_only():+ from helpers import files++ prompt = """Before+~~~json+{"tool_name":"response","tool_args":{"text":"done"}}+~~~+~~~python+print("keep me fenced")+~~~+After+"""++ rendered = files.remove_code_fences(prompt, language="json")++ assert "~~~json" not in rendered+ assert '{"tool_name":"response"' in rendered+ assert '~~~python\nprint("keep me fenced")\n~~~' in rendered++@pytest.mark.asyncioasync def test_tiny_local_profile_prompt_is_action_first_json_contract():system_text = await _build_system_text("tiny-local")