"""Policy gate between the model and the tools. Runs in our code, never in the prompt. Fail closed: unknown tool, schema violation, or policy violation => denied and logged, tool not run.""" import json, os, sys, time from jsonschema import Draft202012Validator import tools from registry import REGISTRY, ALLOWED_RECIPIENT_DOMAINS LOG = sys.stderr def _log(tool, args, decision, rule): LOG.write(json.dumps({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "tool": tool, "arguments": args, "decision": decision, "rule": rule}) + "\n") def check(tool, args): """Return (None) if allowed, else a rule id.""" if tool not in REGISTRY: return "R1-unknown-tool" errs = sorted(Draft202012Validator(REGISTRY[tool]["schema"]).iter_errors(args), key=lambda e: list(e.path)) if errs: return "R2-schema:" + errs[0].validator # e.g. R2-schema:maxLength, additionalProperties if tool == "read_note": real = os.path.realpath(os.path.join(tools.ROOT, args["path"])) if os.path.commonpath([real, tools.ROOT]) != tools.ROOT: return "R3-path-outside-root" if tool == "send_email": domain = args["to"].rsplit("@", 1)[-1].lower() if args["to"].count("@") == 1 else "" if domain not in ALLOWED_RECIPIENT_DOMAINS: return "R4-recipient-domain" return None def call_tool(tool, args, enforce=None): if enforce is None: enforce = os.environ.get("ENFORCE", "1") == "1" rule = check(tool, args) if enforce else None if rule: _log(tool, args if len(json.dumps(args)) < 300 else {"_truncated": len(json.dumps(args))}, "deny", rule) return {"ok": False, "error": f"denied by policy ({rule})"} _log(tool, args if len(json.dumps(args)) < 300 else {"_truncated": len(json.dumps(args))}, "allow", "-" if enforce else "enforcement-off") try: return {"ok": True, "result": tools.IMPLS[tool](**args)} except Exception as e: return {"ok": False, "error": f"{type(e).__name__}: {e}"}