#!/usr/bin/env python3 import ai_brain_env # auto-inserted by update_ai_brain_env_paths.sh """ event_handler.py (patched) Routes events to the AI orchestrator for chrome errors so the AI loop drives fixes. Reads event JSON from stdin (or from argv[1]) and calls ai_orchestrator.py. Prints the orchestrator's JSON result to stdout (so manager/event_endpoint can return it). """ import sys, json, subprocess from pathlib import Path BASE = Path.home() / "Desktop" / "AI_Brain" DEVTOOLS = BASE / "sub_brains" / "hypothalamus" / "devtools" AI_ORCHESTRATOR = DEVTOOLS / "ai_orchestrator.py" DEFAULT_HANDLER = DEVTOOLS / "devtools_healer" / "handle_event.py" def read_event(): if not sys.stdin.isatty(): raw = sys.stdin.read() try: return json.loads(raw) except Exception: return {"raw": raw} elif len(sys.argv) > 1: try: return json.loads(sys.argv[1]) except Exception: return {"raw_arg": sys.argv[1]} else: return {} def run_orchestrator(event): if AI_ORCHESTRATOR.exists(): try: proc = subprocess.run([sys.executable, str(AI_ORCHESTRATOR)], input=json.dumps(event), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=600) out = proc.stdout.strip() if out: try: return json.loads(out) except Exception: return {"status":"ok","raw_output": out, "stderr": proc.stderr} else: return {"status":"no_output","stderr": proc.stderr} except Exception as e: return {"status":"error","error": str(e)} else: # fallback: call module handler directly handler = DEFAULT_HANDLER if handler.exists(): try: proc = subprocess.run([sys.executable, str(handler), "--dry-run", "--event", json.dumps(event)], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180) # try parse try: return json.loads(proc.stdout.strip()) except Exception: return {"status":"fallback_ok","output": proc.stdout, "stderr": proc.stderr} except Exception as e: return {"status":"error","error": str(e)} return {"status":"error","message":"no orchestrator or handler present"} def main(): evt = read_event() # If chrome event, route to AI orchestrator for iterative fix-first flow source = evt.get("source","").lower() if isinstance(evt.get("source",""), str) else "" err_type = (evt.get("error_type") or "").lower() if source == "chrome" or "chrome" in err_type or "extension" in err_type: res = run_orchestrator(evt) # echo result JSON to stdout for manager to pick up print(json.dumps(res)) return # non-chrome default behavior: fallback to simple module mapping (existing logic can be restored) res = run_orchestrator(evt) print(json.dumps(res)) if __name__ == "__main__": main()