An agent reads web pages and emails and can call tools that write records and send messages. Text it reads can contain instructions aimed at the agent. Write the runtime gate that sits between the model and the tools: for each proposed call, decide allow, require_confirmation or deny from the agent's role, each tool's risk level and whether the arguments came from untrusted content, and keep an audit log.
Implement gate_tool_calls(messages, calls, tools, role, policy).
messages: the conversation, a list of {"id": str, "source": str, "content": str}. source is "system", "user", "tool" (output of an internal API) or "retrieved" (web pages, emails, documents). The first three are trusted; "retrieved" is untrusted.calls: proposed tool calls, {"id": str, "tool": str, "args": dict}, in order.tools: name -> {"risk": "read" | "write" | "send"}; a "send" tool also has "dest_arg", the name of the argument holding the destination address.role: the agent's role. policy = {"roles": {role: [tool names]}, "allowed_domains": [str]}. A role not in policy["roles"] may use no tools.Taint. An argument is tainted when its value is a string v such that, with s = v.strip().lower(): s has at least 4 characters, s is a substring of the lowercased content of at least one untrusted message, and s is not a substring of the lowercased content of any trusted message. Non-string values are never tainted. A call's tainted_from is the sorted list of ids of the untrusted messages that contain the value of any of its tainted arguments.
Destination. For a "send" tool, the destination is args.get(dest_arg). It is internal when it is a string containing @ and the text after its last @, stripped and lowercased, equals one of allowed_domains lowercased. Anything else, including a missing destination, is external.
Decision, first rule that applies:
tools: deny, reasons ["unknown_tool"].deny, ["not_allowed_for_role"]."send" tool with an external destination whose dest_arg is tainted: deny, ["injected_destination"]."external_destination" for a "send" tool with an external destination, then, for "write" and "send" tools only, "tainted:<arg>" for each tainted argument in the order of args. Any reasons give require_confirmation; none give allow.Return {"decisions": {call id: decision}, "audit": [...], "summary": {"allow": n, "require_confirmation": n, "deny": n}}, with one audit entry per call, in call order: {"call": id, "tool": name, "decision": decision, "reasons": [...], "tainted_from": [...]}. Taint is computed for every call, including denied and read-only ones.