Agent Zero AI framework
Install Context Doctor dependency after self-update
Alessandro519f2c2a6241
diff --git a/plugins/_context_doctor/AGENTS.md b/plugins/_context_doctor/AGENTS.mdindex 365965bf1..0cf6a6e97 100644--- a/plugins/_context_doctor/AGENTS.md+++ b/plugins/_context_doctor/AGENTS.md@@ -7,6 +7,8 @@## Ownership- `helpers/context_doctor.py` transforms output and refreshes log fields.+- `hooks.py` installs the exact root-pinned repair dependency in the framework runtime.+- `extensions/python/startup_migration/` prepares that dependency after startup and self-update.- `extensions/python/message_loop_result/` normalizes completed model output before default processing.- `webui/config.html` exposes XML suppression and log-detail settings.@@ -16,6 +18,7 @@- Nonempty non-tool output becomes `{"thoughts":[raw]}`; XML-like output becomes `{}` only when suppression is enabled.- Log kvps and heading always reflect transformed output; `update_log` controls only View Details content.- A repaired `response` tool call refreshes the response log item when streaming did not create it.+- Runtime setup reads the `json_repair` pin from root `requirements.txt`; do not duplicate its version in plugin code.## Work Guidancediff --git a/plugins/_context_doctor/extensions/python/startup_migration/_20_context_doctor_runtime.py b/plugins/_context_doctor/extensions/python/startup_migration/_20_context_doctor_runtime.pynew file mode 100644index 000000000..f2133d300--- /dev/null+++ b/plugins/_context_doctor/extensions/python/startup_migration/_20_context_doctor_runtime.py@@ -0,0 +1,11 @@+from helpers.extension import Extension+from helpers.plugins import call_plugin_hook+++class ContextDoctorRuntime(Extension):+ def execute(self, **kwargs):+ call_plugin_hook(+ "_context_doctor",+ "ensure_dependencies",+ raise_on_error=False,+ )diff --git a/plugins/_context_doctor/hooks.py b/plugins/_context_doctor/hooks.pynew file mode 100644index 000000000..d30a3519e--- /dev/null+++ b/plugins/_context_doctor/hooks.py@@ -0,0 +1,81 @@+from __future__ import annotations++import importlib+import importlib.metadata+import importlib.util+import shutil+import subprocess+import sys+import threading+from pathlib import Path++from helpers.errors import format_error+from helpers.print_style import PrintStyle+++_LOCK = threading.Lock()+_PLUGIN_DIR = Path(__file__).resolve().parent+_ROOT_REQUIREMENTS_FILE = _PLUGIN_DIR.parents[1] / "requirements.txt"+++def ensure_dependencies(raise_on_error: bool = True) -> bool:+ """Install the pinned framework-runtime dependency when needed."""+ with _LOCK:+ try:+ requirement = _json_repair_requirement()+ if _json_repair_is_current(requirement):+ return True++ uv = shutil.which("uv")+ if not uv:+ raise RuntimeError(+ "Context Doctor plugin requires 'uv' to install json_repair automatically"+ )++ PrintStyle.info(+ "Context Doctor: installing pinned json_repair dependency"+ )+ subprocess.check_call(+ [uv, "pip", "install", "--python", sys.executable, requirement],+ cwd=str(_PLUGIN_DIR),+ )+ importlib.invalidate_caches()+ if not _json_repair_is_current(requirement):+ raise RuntimeError(+ f"Context Doctor dependency {requirement!r} is unavailable after installation"+ )+ return True+ except Exception as exc:+ message = (+ "Context Doctor: failed to install json_repair dependency: "+ f"{format_error(exc)}"+ )+ if raise_on_error:+ raise RuntimeError(message) from exc+ PrintStyle.error(message)+ return False+++def install() -> bool:+ return ensure_dependencies(raise_on_error=True)+++def _json_repair_requirement() -> str:+ if _ROOT_REQUIREMENTS_FILE.is_file():+ for line in _ROOT_REQUIREMENTS_FILE.read_text(encoding="utf-8").splitlines():+ requirement = line.strip()+ if requirement.startswith("json_repair=="):+ return requirement+ raise RuntimeError(+ f"Context Doctor pinned json_repair requirement not found in {_ROOT_REQUIREMENTS_FILE}"+ )+++def _json_repair_is_current(requirement: str) -> bool:+ expected_version = requirement.partition("==")[2]+ if not expected_version or importlib.util.find_spec("json_repair") is None:+ return False+ try:+ return importlib.metadata.version("json-repair") == expected_version+ except importlib.metadata.PackageNotFoundError:+ return Falsediff --git a/plugins/_context_doctor/tests/test_hooks.py b/plugins/_context_doctor/tests/test_hooks.pynew file mode 100644index 000000000..093256b41--- /dev/null+++ b/plugins/_context_doctor/tests/test_hooks.py@@ -0,0 +1,69 @@+import sys++from plugins._context_doctor import hooks+from plugins._context_doctor.extensions.python.startup_migration import (+ _20_context_doctor_runtime as startup_runtime,+)+++def test_dependency_check_requires_root_pinned_version(monkeypatch):+ requirement = hooks._json_repair_requirement()+ expected_version = requirement.partition("==")[2]++ monkeypatch.setattr(hooks.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(+ hooks.importlib.metadata, "version", lambda _name: expected_version+ )+ assert hooks._json_repair_is_current(requirement)++ monkeypatch.setattr(+ hooks.importlib.metadata, "version", lambda _name: f"{expected_version}.stale"+ )+ assert not hooks._json_repair_is_current(requirement)+++def test_dependency_hook_installs_root_pinned_requirement(monkeypatch):+ requirement = hooks._json_repair_requirement()+ checks = iter((False, True))+ calls = []++ monkeypatch.setattr(+ hooks, "_json_repair_is_current", lambda _candidate: next(checks)+ )+ monkeypatch.setattr(hooks.shutil, "which", lambda _command: "/usr/local/bin/uv")+ monkeypatch.setattr(+ hooks.subprocess,+ "check_call",+ lambda command, cwd: calls.append((command, cwd)),+ )++ assert requirement.startswith("json_repair==")+ assert hooks.ensure_dependencies()+ assert calls == [+ (+ [+ "/usr/local/bin/uv",+ "pip",+ "install",+ "--python",+ sys.executable,+ requirement,+ ],+ str(hooks._PLUGIN_DIR),+ )+ ]+++def test_startup_migration_calls_dependency_hook(monkeypatch):+ calls = []+ monkeypatch.setattr(+ startup_runtime,+ "call_plugin_hook",+ lambda *args, **kwargs: calls.append((args, kwargs)),+ )++ startup_runtime.ContextDoctorRuntime(None).execute()++ assert calls == [+ (("_context_doctor", "ensure_dependencies"), {"raise_on_error": False})+ ]