Metadata-Version: 2.4
Name: recusal-openai-agents
Version: 0.2.7
Summary: Recusal gate for the OpenAI Agents SDK: judge every function tool call in a tool input guardrail, refuse before it runs, and optionally put each decision on a hash-chained audit log.
Project-URL: Homepage, https://recusal.io
Project-URL: Documentation, https://github.com/philpaz/recusal/tree/main/adapters/openai-agents
Project-URL: Repository, https://github.com/philpaz/recusal
Project-URL: Issues, https://github.com/philpaz/recusal/issues
Project-URL: Changelog, https://github.com/philpaz/recusal/blob/main/CHANGELOG.md
Author-email: Philip Paz <philip.paz@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agent-governance,ai-agents,guardrails,openai-agents,recusal,tool-use
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: openai-agents<1,>=0.24.0
Requires-Dist: recusal<1,>=0.18.2
Description-Content-Type: text/markdown

<p align="center">
  <a href="https://recusal.io">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip.png">
      <img alt="recusal, deterministic governance for AI agents" src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/banner-gate-strip-light.png" width="880">
    </picture>
  </a>
</p>

# recusal-openai-agents

[![Website](https://img.shields.io/badge/website-recusal.io-2453c4)](https://recusal.io)
[![PyPI](https://img.shields.io/pypi/v/recusal-openai-agents)](https://pypi.org/project/recusal-openai-agents/)
[![CI](https://github.com/philpaz/recusal/actions/workflows/ci.yml/badge.svg)](https://github.com/philpaz/recusal/actions/workflows/ci.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/philpaz/recusal/badge)](https://scorecard.dev/viewer/?uri=github.com/philpaz/recusal)
![python](https://img.shields.io/badge/python-3.10%2B-blue)
![license](https://img.shields.io/badge/license-Apache--2.0-green)

The [Recusal](https://github.com/philpaz/recusal) gate for the
[OpenAI Agents SDK](https://openai.github.io/openai-agents-python/): every function tool
call an agent proposes is judged by your policy before the tool runs, and a refused call
never runs.

**New to Recusal?** It checks each tool call an AI agent proposes against your policy and
refuses the unsafe or unapproved ones before the tool runs. No model makes that decision.
A policy is a plain Python function: it is given the tool's name and its arguments and
returns a list of findings. An empty list lets the call run; a failing finding refuses it
and gives the reason.
[Writing a policy](https://github.com/philpaz/recusal#write-the-policy-two-postures-one-principle)
covers the two postures, allowlist and deny-list.

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position.svg">
    <img alt="Before the tool runs. An agent proposes a tool call. Recusal, your policy with no model in it, decides. With no objection the tool runs. On a failing finding, or when the policy itself raises, the call is refused: the tool never runs and the reason goes back to the model. Every decision can be written to a hash-chained audit log, if you pass one." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/gate-position-light.svg" width="880">
  </picture>
</p>

This is a separate distribution from `recusal`. The kernel has zero runtime dependencies
and a frozen compatibility perimeter; this package carries the SDK dependency and its own
version, so an SDK release never forces a release of the kernel.

Install it from PyPI:

```bash
pip install recusal-openai-agents
```

Requires Python 3.10+ (the SDK's minimum), `recusal>=0.18.2` and `openai-agents>=0.24.0`.
It is tested on every pull request against exactly `openai-agents==0.24.0` with
`openai==3.49.0`, and weekly against the newest releases.

Beside `openai-agents` 0.26.1 or newer, use 0.2.5 or newer of this package. From
0.26.1 the SDK puts a decoder of its own in front of every tool's parameter model,
and 0.2.4 and earlier refuse every function tool there when the agent is built
(`its parameter model cannot be read`): nothing runs unjudged, and no gated agent
with a function tool can be built
([issue #358](https://github.com/philpaz/recusal/issues/358)). What 0.2.5 was run
against is under [Status](#status).

The package ships inline types (`py.typed`) for your editor and type checker.

## Use

```python
from agents import Agent, function_tool
from recusal import Finding
from recusal_openai_agents import gated_agent


@function_tool
def run_sql(sql: str) -> str: ...


def policy(tool_name, tool_input):
    sql = tool_input.get("sql", "")
    if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
        return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
    return []


agent = gated_agent(Agent(name="assistant", tools=[run_sql]), policy)
```

`gated_agent` returns a copy of the agent with a Recusal tool input guardrail on every
function tool. A refused call's output is Recusal's reason, which the model reads on its
next turn. The tool does not run. A policy that raises refuses the call (fail closed).
`Runner.run`, `Runner.run_streamed` and a human approval (`needs_approval`) all pass
through the guardrail, which runs when the tool is about to execute, after any approval.
Under `RunConfig(tool_execution=ToolExecutionConfig(pre_approval_tool_input_guardrails=True))`
the SDK runs the guardrail before it asks a person as well, so such a call is judged
twice: once before the approval and once when it is about to run.

The gate judges the arguments as the SDK prepares them from the tool's schema: validated,
types converted (`{"amount": "50"}` reaches an `int` parameter as `50`) and defaults
filled, each under the name of the parameter that receives it. Which parameter is the
context the SDK fills itself is read from the SDK's own schema for the tool. An allowed
call's prepared arguments are pinned on the tool context, so the SDK runs what was judged.

A sub-agent behind `agent.as_tool(...)` is called like a function tool, and the parent's
policy judges the input the sub-agent is given. With the default `as_tool` that is the
arguments as the model wrote them, `{"input": "..."}`. With `as_tool(parameters=Model)`
it is what the SDK's own adapter for that model makes of them: validated, types
converted (`{"rows": "9"}` reaches the sub-agent as `9`), defaults filled, and a key the
model does not name dropped. Arguments the model does not accept are refused before the
policy runs. The sub-agent's own tool calls are judged by the sub-agent's gate, which
`gate_tools` requires.

Build the agent completely, then gate it. A tool appended to the gated agent's list
afterwards is not gated. The gated copy has its own `tools`, `handoffs` and `mcp_servers`
lists, so a handoff or a server added to the original agent after gating is not the
copy's. `gate_tools(tools, policy)` gates a list of tools directly.

### Parameter types

Declare data-only parameters. These are gated and judged by value:

- `str`, `int`, `float`, `bool`, `None`, `Optional[...]` and unions of these;
- `Literal[...]` of strings, integers and booleans;
- `list[...]` and `dict[str, ...]` of the above, a `dict` keyed by a `Literal` of strings
  (`dict[Literal["a", "b"], int]`), and `Any` (judged as the JSON it was sent as);
- any of them with `Field` limits such as `ge=`, `le=` or `max_length=`;
- any of them with a default that is JSON data, or with `Field(default_factory=list)` or
  `Field(default_factory=dict)`.

A `dict` parameter needs `function_tool(..., strict_mode=False)`: under the SDK's default
strict schema the SDK itself refuses to build such a tool (`UserError`,
"additionalProperties should not be set").

`gate_tools` and `gated_agent` raise `TypeError`, naming the tool and the parameter, for a
parameter no call to which could be judged:

- a type or a validation the SDK prepares only by running code of the tool's own: an
  `Enum`, a Pydantic model, a dataclass, a `TypedDict`, `datetime` and `date`, `tuple`,
  `set`, `Sequence[...]` and `Iterable[...]`, `bytes`, `Field(pattern=...)` and a custom
  validator. Take a `str`, an `int`, a `list` or a `dict` in its place and build the
  application type inside the tool body;
- a default factory other than `list` or `dict` (`Field(default_factory=lambda: [...])`).
  Use a plain default and build the value inside the tool body;
- a default that is not JSON data (`tags: list[str] = ()`, `timeout: float = math.inf`).
  Give it a JSON default: `None`, a string, a finite number, a boolean, a list or a dict;
- a mapping whose key type is neither `str` nor a `Literal` of strings (`dict[int, str]`,
  `dict[Literal[1, 2], str]`). The SDK converts the keys of the JSON object the model
  sends, and the gate judges arguments as JSON data, whose keys are strings. Declare
  `dict[str, ...]` and convert the keys inside the tool body.

## Put every decision on the record

```python
from recusal.audit import AuditLog
from recusal_openai_agents import audited_agent

log = AuditLog(path="decisions.jsonl")
agent = audited_agent(Agent(name="assistant", tools=[run_sql]), policy, log)
```

`audited_tools(tools, policy, log)` is the list form. Each call a guardrail sees, allowed
or refused, is one hash-chained entry labeled `openai_agents.tool_input_guardrail` with
the SDK's tool call id and a SHA-256 fingerprint of the arguments (never the arguments).
If the log cannot be written the call is refused. Check the log with
`recusal audit verify decisions.jsonl`.

The audited forms are the plain ones with a recording passed in, so there is one decision
path: a call the audited gate refuses, the plain gate refuses, for the same cause.

A call that waits for a person's approval is judged, and recorded, when it is about to
run, so a call a person rejected is not on the log. The exception is the SDK option
`pre_approval_tool_input_guardrails=True` (above): the gate then runs before the approval
as well, so a call has an entry before a person decides, a rejected call keeps that one
entry, and an approved call has two entries under the same call id.

## What the gate refuses, and what it does not see

`gated_agent` raises `ValueError` at construction for an agent that can run something the
guardrail never sees. The rule is default-deny:

- **MCP servers attached with `mcp_servers=`, and handoffs to other agents.** For MCP
  servers use
  [`recusal-openai-agents-mcp`](https://github.com/philpaz/recusal/tree/main/adapters/openai-agents-mcp).
- **An agent with a `prompt`.** A prompt stored on OpenAI's servers can configure tools
  that are not in the agent's `tools` list. Put the instructions and the tools on the
  agent itself.
- **An agent whose `model_settings` can put tools into the request.** `extra_body` or
  `extra_args` with a `tools`, `prompt`, `plugins`, `web_search_options` or `mcp_servers`
  key is refused. The SDK merges `extra_body` into the body of every model request: a
  `tools` key there replaces the agent's own tool list in the request, and each of the
  other four is sent beside it. `extra_args` are passed as arguments of the request call:
  a `prompt` there is sent with a Responses request, and a `tools` key makes the SDK's
  OpenAI models raise `TypeError` before anything is sent. Put the tools on the agent
  itself.
- **`Agent` subclasses** such as `SandboxAgent` and `RealtimeAgent`: a subclass can add
  tools of its own at run time.
- **Function tools that share a name.** Two tools under one name are resolved by the SDK
  last-wins. Two tools under one name in different `tool_namespace` groups both run, but
  the policy and the audit record are given the tool's own name without the namespace
  and could not tell them apart. Give every function tool a unique name.

`gate_tools` and `gated_agent` raise `TypeError`, naming the tool, for a tool the
guardrail cannot judge:

- **Any tool that is not a `FunctionTool`:** hosted tools that run on OpenAI's servers
  (web search, file search, code interpreter, image generation, hosted MCP, tool search)
  and local ones the SDK executes itself (shell, apply patch, computer, custom). A tool
  type added in a later SDK release is refused too. The experimental Codex tool is
  refused as well: it runs its own commands.
- **A `FunctionTool` built by hand** (`FunctionTool(..., on_invoke_tool=...)`). The gate
  could judge only the model's raw JSON, not what your invoker makes of it. Build the
  tool with `function_tool`.
- **A parameter outside the data-only set** listed under Parameter types above: its
  type, its default, or the key type of a mapping.
- **A variadic parameter** (`*args`, `**kwargs`). Its values have no names to judge by.
  Declare each parameter by name.
- **A wrapped function whose wrapper takes other parameters than the function.** The SDK
  reads a `functools.wraps` decorator as the function it wraps. A wrapper that adds a
  parameter of its own (`dry_run=False`) would run it at a default that is in no schema,
  and one that takes some of the function's parameters, or takes them in another order,
  would hand the function other values than the policy judged. Two kinds of wrapper are
  gated: one that forwards `*args, **kwargs` and names no parameter, and one that takes
  exactly the function's parameters, by the same names, in the same order and of the
  same kinds, and, since 0.2.6, gives none a default the function does not give it; on
  a method such a wrapper is gated only where the method gives no parameter a default
  (the restating family under Status), and, since 0.2.7, over a function that takes the
  SDK's run context first only where the function gives no parameter a default (the
  context-restating family). So is a stack of them, each level read in turn.
  A stack of more than 31 wrappers, or more than eight `functools.lru_cache` layers one
  on another, is refused as more than the walk reads. Since 0.2.6 the rule is the
  kernel's (`recusal.invocation.judge_tool`) and so are the words of the refusal; up to
  0.2.5 it was this gate's own.
- **A function that carries a declared signature.** A `__signature__` attribute,
  whatever its value, or a `__text_signature__` that is not the interpreter's own, on
  the function or on a callable on the way to it. `inspect.signature`, which the SDK
  reads a tool with, can read such a declaration in place of the parameters Python
  binds, and which ones it reads differs between Python versions. The kernel's walk
  relies on none. It refuses each one, also where this Python would not read it (a
  `__signature__` of `None`) and where it matches the real parameters, so a tool refused
  for this may run correctly. Remove the declaration, so that the parameters Python
  binds are what is read.
- **A decorator whose signature cannot be read.** A class-based decorator that is also a
  descriptor (`cachetools.cached`, `cachetools.func.ttl_cache`, `cachetools.func.lru_cache`)
  hides the functions under it from inspection. Register the function without that
  decorator, or use one the gate reads (a `functools.wraps` function decorator, or a
  class-based decorator with no `__get__` that calls `functools.update_wrapper(self,
  fn)`). A `staticmethod` object that something other than a class
  holds (`functools.partial(staticmethod(f))` under a decorator) is such an object too:
  Python shows no signature for it, so the tool is refused with the same reason,
  although it runs correctly. 0.2.1 beside `recusal` 0.15.1 refused it as well under an
  ordinary `functools.wraps` decorator, and gated it under a decorator written with
  `functools.update_wrapper` over a `functools.partial`. `functools.lru_cache` and `functools.cache` are read
  through and gated. With `functools.wraps(f)` written above the cache, the cache names
  `f` and calls the wrapper it was built over. The kernel's walk reads that wrapper: one
  that only forwards is gated, and one with a parameter of its own is refused. Since
  0.2.3 the gate's own walk follows both, what the cache names and what it calls
  (`recusal.invocation.cache_target`), so its own questions (a single-dispatch function,
  a `functools.partialmethod`, a weak proxy) are asked behind such a cache too. Refused
  although it runs correctly: such a cache over a `functools.partial` of a second
  `functools.lru_cache` wrapper or of a `staticmethod` object, for which Python shows no
  signature. Since 0.2.6 the reason for both is the kernel's for a callable that cannot
  be read: it names the class of what `inspect.signature` raised (`ValueError`), passes
  on none of the words raised, and says what to register (up to 0.2.5 the gate gave its
  own reason over a `staticmethod` object, and over a second cache the name of the
  exception class alone); 0.2.1 beside `recusal` 0.15.1 gated both. A cache whose
  function cannot be told from what the cache refers to is refused; no interpreter this
  package is tested on gives one.
- **A decorator that holds a second wrapper of the function.** A decorator can apply
  another `functools.wraps` wrapper inside itself and call the result, while its own
  `functools.wraps` names the undecorated function. The wrapper in between is then not
  on the `__wrapped__` chain. The kernel's walk reads what a wrapper on the chain holds
  in its closure, in the module globals its code names, or, for a callable object, in
  its instance attributes. From a wrapper held there it goes on to the function: through
  plain functions and `functools.lru_cache` wrappers (to what each names as
  `__wrapped__`, and a cache named again to the function it calls), bound methods,
  `functools.partial` objects (to their function, and to a `__wrapped__` a partial
  carries), `staticmethod` and `classmethod` objects, class-based decorators and other
  callable objects (through what their instance dictionary holds), a `weakref.proxy` of
  a callable the walk stood on, and a second wrapper that is itself only held. This is
  the walk of `recusal` 0.17.0 and later; that of 0.16.0 followed fewer of these, and
  0.2.4 requires 0.17.1. It judges the way only if that ends at a function the walk
  read. The tool is then refused when a function on that way:
  - takes a parameter the tool does not declare;
  - passes the call on (`*args` or `**kwargs`) and takes a parameter the tool declares,
    which the function then does not receive;
  - takes, in a place an argument passed by position can fill, another name than the
    tool declares in that place (`def flipped(force, sql)` held over
    `def fetch(sql, force=False)`): the reason names the two parameters;
  - takes its leading parameter in the place of an argument bound on the way (the
    object of a method), where the tool declares that parameter and the wrapper passes
    the call on, or the tool does not declare it and it has a default;
  - takes an argument bound on the way under another name than the function it hands
    the call to has for that place (`def forward(receiver, *args, **kwargs)`, held, over
    `def run(self, sql="x", force=False)`), since `recusal` 0.17.1, where the last place
    the bound arguments would fill on that function is not declared by the tool and has
    a default, or has none while the tool declares a parameter an argument passed by
    position can fill: a held wrapper that keeps the object runs every judged value one
    place off, and one that hands it on has the same signature;

  and when the way cannot be judged by parameters: it passes a single-dispatch function
  (whatever is registered on it), or a cache named again that calls anything but a
  plain function, or it does not end within 32 steps, or it comes back on itself (a
  chain of `__wrapped__` that returns to a value already on it, since 0.17.1), or the
  held values lead to more than 16,384 callables. A `weakref.proxy` a wrapper holds of a
  callable the walk did not stand on (a helper) is refused too. The reason names a
  parameter in each of the five cases above (two in the third and the fifth) and none
  in the others. A tool refused for the fifth, or for one of the others, may run
  correctly: see "Refused although it runs correctly" under Status. A held wrapper the
  walk does not find is not refused: see "What the gate does not see" below.
- **A wrapper that is handed a bound argument and may not pass it on.** A facade method
  written as `@functools.wraps(search)` over `def search(self, *args, **kwargs)`, which
  calls `search(self.tenant, *args, **kwargs)`, takes its object as `self`, where the
  function it wraps has another first parameter. Whether such a wrapper hands the bound
  argument on, keeps it or passes a value of its own in its place cannot be read from
  its signature, so the kernel's walk cannot tell which parameter of the function each
  judged value fills. A facade that takes its object in `*args` is refused the same way.
  Which signatures the kernel refuses is its rule (`BoundArgumentKept` in
  `recusal.invocation`): a parameter the bound arguments could leave open that nothing
  is known to fill with a judged value, where that parameter has a default, or where
  the tool declares it and a wrapper on the way takes that name itself. Where it has no
  default and the tool does not declare it, the walk of `recusal` 0.17.0 read the
  facade, because a call by keyword would then fail. This SDK calls by position, and
  the walk of 0.17.1, which 0.2.4 requires, refuses it too where the tool declares a
  parameter an argument passed by position can fill (any that is not keyword-only): a
  call by position runs with each value one place from where it was judged. Where the facade takes its object in `*args` or under the
  very name the function has for that place, the kernel's walk reads it (the shape of
  every method decorator that hands its object on), and the gate refuses that shape
  itself where the function's first parameter is not named `self` or `cls` (the next
  bullet). A wrapper of a refused signature that runs correctly is refused with it,
  because the two cannot be told apart. The reason carries the kernel's text, which
  names the parameter that could be left open and, where a wrapper took the bound
  argument under a name, that name too. That text is the kernel's and is quoted whole.
  In `recusal` 0.16.0 it could say a parameter "runs at a default no policy judged"
  where the parameter has no default; the text of 0.17.0 and later says only what holds
  for the parameter. Register the function itself; or write the method without
  `functools.wraps`, naming the parameters the tool takes in its own signature, and
  pass them on to the function by keyword. The kernel's text ends with advice of its
  own, which can be to take the argument under the name the function has for that
  place and hand it on by position: that removes the cause only where no other wrapper
  on the way keeps the object, and where one does (a method decorator that does not
  pass `self` on), the tool so written can be gated and run every judged value one
  place off. Since 0.2.6 the reason is the kernel's alone, and it says so itself, for a
  call by position (up to 0.2.5 the gate said it in a note before the kernel's text).
- **A method, or a `functools.partial` with positional arguments, over a wrapper of a
  function not written to take what is bound (since 0.2.3).** A decorator written with
  `functools.wraps` that exposes a module function as a method,
  `def method(self, *args, **kwargs): return fn(*args, **kwargs)` over
  `def execute(database, sql="SELECT 1", note="")`, as `Warehouse().run_sql`:
  `inspect.signature` reads the method as `execute` and leaves `database` out as the
  object's place, and the SDK passes every declared parameter by position
  (`FuncSchema.to_call_args`), so the method's call drops the object and `execute` runs
  with each value one place off. 0.2.2 and 0.2.3 as first written gated it: the policy
  judged `sql="SELECT 1"` and `note="DELETE FROM audit_log"`, and the function ran
  `database="SELECT 1"` and `sql="DELETE FROM audit_log"`. Refused, by a rule of this
  gate's own from 0.2.3 to 0.2.5 and by the kernel's since 0.2.6, with the same verdict: a method
  whose function is a wrapper (it names `__wrapped__`) of a function whose first
  parameter is not named `self` or `cls`, however the wrapper takes the object (as
  `self`, in `*args`, under the function's own first name, under a
  `functools.lru_cache`), and a `functools.partial` that binds a positional argument to
  such a wrapper in the place of a parameter so named. Beside `recusal` 0.17.1 the
  kernel's walk, which is asked first, refuses the forms whose wrapper takes the object
  under another name than the function has for that place (as `self` over `database`,
  under a cache too, and a partial's argument taken as `first`), with the reason of the
  bullet above; the rule for a bound place under a name that is not an object's refuses
  the forms the walk reads, where the wrapper takes it in `*args` or as `database`. The
  rule is by name: where the dropped place is
  named `self` or `cls`, it is the ordinary decorated method, and a decorator that
  forgets to pass the object on, under that name or in `*args`, is not found (stated
  under Open below). One that takes it under another name than the method has for it
  (`self` over a class method's `cls`, or `self` over a module function whose first
  parameter is `cls`) is refused by the kernel's walk of 0.17.1. Refused although it
  runs correctly: one that does hand the object on, since the signature does not show
  it; a correct decorated method whose object's place has another name (`this`): under
  a decorator that hands everything on in `*args` the reason says to name it `self`,
  and under one that takes the object as `self` the kernel's walk refuses it first,
  whose reason says to write the method out; and two such facades, one over the other,
  behind a cache named again for a function that shows the whole signature, where the
  SDK reads that signature and each drop is what makes the call correct. A decorated
  method of an ordinary class (`def run_sql(self, sql)`) is read as before. Register the
  function itself, not the method or the partial that wraps it.
- **A `functools.singledispatch` function or a `singledispatchmethod`, with or without
  an implementation registered.** The implementation that runs is chosen at call time by
  the type of an argument, each one has its own parameters and defaults, and one can be
  registered at any moment. The SDK checks every call of a model turn before any tool
  body runs, so an implementation that one call of a turn registers (or that the tool
  registers on its own first use) would run, unjudged, for a later call of that turn. So
  a single-dispatch function is refused when the agent is built, whether or not
  anything is registered, wherever the gate's own walk reaches it. Register one plain function as the tool, with the code of each implementation in its own
  body under a branch on the type (`if isinstance(...)`). Do not call a single-dispatch function from
  that body in its place: a single-dispatch function called from the body is not read,
  and the implementation it picks runs with its own defaults. The dispatcher is refused
  wherever it stands among the callables the gate reads: as the tool itself, as a
  method, a class method or a static method (`function_tool(service.handle)`), as a
  callable object's `__call__`, under `functools.wraps` wrappers or
  `functools.lru_cache`, behind a cache named again for another function (since 0.2.3),
  and as the callable a `functools.partialmethod` holds. It is
  recognised in three ways, any one of which is enough: by the code of the function
  `functools.singledispatch` returns (as read when this package was imported, and as
  `functools` stands when the tool is checked, so after `importlib.reload(functools)`
  too); by how that function is built (its closure holds a `dispatch` function whose
  closure holds a `registry` dict, a `dispatch_cache` and a `cache_token`, as
  `functools` builds it on Python 3.10 to 3.15); and by its attributes (a `registry`
  that is a `types.MappingProxyType` beside a callable `dispatch` and a callable
  `register`, on any object, so a service object of your own that has all three is
  refused too). A `functools.wraps` wrapper over a dispatcher carries a copy of those
  attributes and is refused with it. Not taken for one: a callable object that happens
  to have a `dispatch` method and a `registry` attribute that is not a mapping proxy,
  and an event bus of your own whose function closes over a `dispatch` function and a
  `registry` dict. A dispatcher that a wrapper calls from a closure, a global or an
  attribute, and not through `__wrapped__`, is refused by the kernel's walk where it is
  a wrapper of the function the walk reads (`functools.singledispatch(f)` held by a
  decorator of `f`), whatever is registered on it. One built over another function, and
  one reached through a helper that names nothing as `__wrapped__`, are not found: see
  "What the gate does not see" below. A dispatcher a decorator holds is refused with
  the reason for a held wrapper, whose advice is to hold no single-dispatch function
  there or to register the function itself. The kernel's walk also refuses a
  single-dispatch function with nothing registered that it stands on
  (`OpenDispatch` in `recusal.invocation`), with the kernel's own reason since 0.2.6: an
  implementation can be registered on it at any moment, between the check and the call
  too, and the base function itself is what to register where nothing is to be
  registered. Since 0.2.3 the gate's own walk stands wherever the kernel's does and
  finds such a dispatcher first, so no tool is known that gets that reason.
- **A `functools.partialmethod`.** What the tool calls is the callable the partialmethod
  holds, and Python reads the tool's parameters from that callable without anything
  reading what is under it: a single-dispatch function or a wrapper with a parameter of
  its own there would run with a value no policy judged. So a function that is or
  carries a partialmethod is refused wherever the gate's own walk or the kernel's reaches
  it, whatever it holds, a plain function too. That is
  what you get when you read a partialmethod from the class (`Db.export`), and from an
  object (`db.export`) when the callable it holds does not bind as a method: a
  class-based decorator's instance, or a `functools.partial`. A partialmethod over
  a plain function or method read from an object is a `functools.partial`, which the
  SDK refuses itself (`function_tool` raises). Write the method out in its place: the
  work of the callable it holds in the method's own body, and the values the
  partialmethod binds as defaults of the method's own parameters (`def export(self, sql,
  force=False)` for `export = functools.partialmethod(run, force=False)`), with no call
  to that callable; and register that. A plain function that calls the partialmethod is gated with the cause
  still inside it: the gate reads its parameters and never its body.
  Behind a cache named again for another function the gate's own walk follows what the
  cache calls (since 0.2.3), and a partialmethod there is refused; where a
  `weakref.proxy` stands on the way it is refused as a proxy. 0.2.2 gated a
  partialmethod behind a proxy of a second cache named again where a
  `functools.partial` or a wrapper stood between that cache and it. A partialmethod
  that a plain function's body calls is not read, as nothing a body calls is.
- **A `weakref.proxy`**, as the tool's function or anywhere among the callables the
  gate's own walk reaches, behind a cache named again for another function too (since
  0.2.3). A proxy shows the attributes of the object it stands for and is not that
  object, so the gate cannot tell which callables a call to it runs. Put the
  object the proxy stands for in its place. A proxy of a plain function is
  refused although it runs correctly. A proxy a decorator holds, and does not reach
  through `__wrapped__`, is refused by the kernel's walk unless it stands for a callable
  that walk read (see the bullet on a decorator that holds a second wrapper).
- **A callable that answers for another object.** A class-based decorator that keeps the
  function in an attribute (`self.fn = fn`) and hands every other attribute on to it
  (`def __getattr__(self, name): return getattr(self.fn, name)`), over a function that
  names a `__wrapped__` of its own (any `functools.wraps` decorator, any
  `functools.lru_cache`), answers `__wrapped__` with what THAT function wraps, so a walk
  would step past the function it calls. The kernel's walk of `recusal` 0.17.0 refuses
  such an object (`ProxiedCallable`), and any other that answers `__wrapped__` without
  holding one or shows another class than its own (its `__class__` is not its type).
  The reason is the kernel's, which says which was found. Such a decorator
  ordinarily runs correctly, and is refused all the same: call
  `functools.update_wrapper(self, fn)` in its `__init__`, and it is read like any other
  wrapper, so one that only forwards is gated. For another such object, register the
  function it calls itself.
- **A sub-agent behind `agent.as_tool(...)` whose own tools are not gated.** Gate the
  sub-agent first, `gated_agent(sub, policy).as_tool(...)`, and the parent accepts it.
- **An agent tool whose `parameters` type is not a data-only Pydantic model.** The gate
  works out what the sub-agent is given with the SDK's adapter for that type, and the
  SDK then validates the arguments again itself, so the two agree only for a model the
  SDK's own rule for data-only validation admits (`can_prepare_without_user_code`) and
  that is written out with no code of its own. For a cause that lies in one field the
  refusal names the field and what puts it outside: its pydantic core type, a string
  pattern, what a list, a mapping or a union holds, a validator, or its default. For a
  cause on the type as a whole (a `model_validator`, a dataclass, a private attribute)
  it names that and no field. Refused, with what to declare in its place:
  - a `date`, `datetime`, `time` or `timedelta` field, a `UUID`, a `Path`, an `AnyUrl`,
    a `Decimal`, `bytes`: a `str` (or a `float` for the `Decimal`), read inside the
    sub-agent's own tools;
  - a `tuple`, a `set`, a `frozenset`, a `Sequence[str]`: a `list`;
  - an `Enum`: a `Literal` of its values;
  - a nested model, a model that refers to itself, a dataclass: flat fields;
  - a field with a pattern, a validator, a serializer, a computed field, or
    `Field(exclude_if=...)` (the SDK runs that callable again when it writes the input
    out): plain fields, checked inside the sub-agent's own tools;
  - a default that is not JSON data (`tags: list[str] = ()`) and a default factory other
    than `list` or `dict`: a JSON default, or `Field(default_factory=list)`;
  - a model with a `PrivateAttr`, and one built with `defer_build=True`: neither.

Refused call by call, before the policy runs, with a reason the model reads:

- arguments that did not arrive as JSON text (a `dict`, a list, a number). The SDK
  hands a function tool's arguments as text; a seam another package builds on this one
  (the hosted approval callback of `recusal-openai-agents-mcp`) may be handed something
  else. It is not read as arguments decoded already: it is refused, and the reason
  names the type it arrived as and nothing it holds. The type is asked exactly: an
  instance of a subclass of `str` or `bytes` is refused too;
- arguments that are not a JSON object, or that do not validate against the tool's
  parameters (for an agent tool, against its `parameters` model);
- a non-finite number (`NaN`, `Infinity`, a literal too large for a float, or a string a
  `float` parameter reads as one). It is not JSON data: a policy cannot compare it and a
  record cannot fingerprint it;
- arguments given to a tool that takes none;
- a call to a tool whose function was changed after the tool was gated into one the
  list above refuses. The guardrail asks the same questions again on every call, and
  the SDK runs every guardrail of a model turn before any tool body of that turn. So a
  change made before a run, or between runs, is seen by the next call; a change a tool
  body makes during a run is seen from the next model turn, and not by the other calls
  of the turn it was made in (see "What the gate does not see");
- arguments that hold a value more than 64 levels below the arguments object. The limit
  is the gate's own and fixed: it is the same with and without an audit log, and does not
  move with the interpreter's recursion limit.

What the gate does not see:

- **What a wrapper or the tool body does with the arguments.** The gate judges the
  values the function is called with. A decorator that changes them in its body, and
  anything the tool reads from elsewhere, is not seen.
- **A function a wrapper holds some other way than `__wrapped__`, beyond the shapes that
  are refused.** The gate walks the function, what its `__wrapped__` chain leads to, a
  bound method's function, a callable object's `__call__` and the function a
  `functools.lru_cache` wrapper calls. A wrapper that a decorator holds in a closure, a
  global or an instance attribute is not walked by the gate itself. The kernel's walk
  refuses the shapes of it that the bullet "A decorator that holds a second wrapper of
  the function" above lists. Not found, and gated (a plain inner function, a wrapper
  built on first use, and one in a slot, a `types.SimpleNamespace`, a list, a function's
  own attribute and behind a `weakref.ref` were each run through this gate beside
  `recusal` 0.17.0, 0.17.1 and 0.18.1, with a held wrapper whose own `skip_review=True`
  ran at that default):
  - a second wrapper that names nothing as `__wrapped__` (a plain inner function, a
    lambda, a helper). One that takes the object of a method under another name than
    the method has for it and drops it (`def forward(receiver, *args, **kwargs): return
    run(*args, **kwargs)`, with no `functools.wraps`, called by a
    `functools.wraps(run)` pass-through) runs every judged value one place off: the
    policy judged `sql="S"` and `force=True`, and `run` ran with `self="S"`,
    `sql=True` and `force=False`. The kernel's entry for 0.17.1 states it as read by
    design, as refusing it would refuse every correct held wrapper written without
    `functools.wraps`; with `functools.wraps(run)` on the held wrapper it is refused;
  - a wrapper built on first use (`if "held" not in state: state["held"] = guarded(f)`
    in the body of the wrapper that calls it): it does not exist when the tool is
    checked;
  - one held where no instance dictionary shows it: in a slot, in a C structure (a
    wrapper a C extension builds), or in a dictionary behind a `__dict__` property;
  - one held by an object that is not callable (a settings object, a
    `types.SimpleNamespace`), in a container, in a class attribute or in a function's
    own attribute;
  - one behind a `weakref.ref` the wrapper calls to get it.

  A wrapper handed in as an argument that a `functools.partial` named for the function
  binds (`functools.update_wrapper(functools.partial(helper, wrapper), f)`, where
  `helper` calls `wrapper`) was gated up to 0.2.5, and its own parameter ran at its
  default. Since 0.2.6 it is refused: the kernel refuses a named partial that binds a
  value by position, whatever the value is (the named-partial family under Status).

  A parameter such a wrapper takes or adds is not judged. The same holds for a
  single-dispatch function: a wrapper that names a plain function as `__wrapped__` and
  calls a dispatcher of another function that it holds in a closure or a global, or one
  it reaches through a helper that names nothing as `__wrapped__`, is gated, and an
  implementation registered on that dispatcher runs with its own defaults. So is a
  plain function whose body calls a dispatcher. The kernel's changelog entry for 0.17.0
  lists the rest of what its walk does not find, under "Still not found, by design",
  and its entry for 0.17.1 what it reads, under "Still read, by design".
- **A held wrapper whose leading parameter the kernel takes for an argument bound on
  the way, where it is not.** Under a method, the kernel counts the places of a wrapper
  a decorator holds by their names and does not read the decorator's body. A held
  wrapper with a parameter of its own in the leading place (`def second(mode, sql="x",
  force=False)`), under a method decorator that keeps the object and calls
  `second(*args, **kwargs)`, was read beside `recusal` 0.17.0 as if `mode` were the
  object's place, gated by 0.2.3, and run one place off; the walk of 0.17.1 refuses
  it, as `mode` is another name than the method has for that place. Its reason quotes
  the kernel's advice to give that parameter the method's name and hand the argument
  on by position. Followed literally here, that gives a held wrapper whose leading
  place has the method's name (`def second(self, sql="x", force=False): return
  run(self, sql, force)`). Up to 0.2.5 that was read as if it were handed the object
  and gated, and the SDK's call handed the judged values on one place off: the policy
  judged `sql="S"` and `force=True`, and `run` ran with `self="S"`, `sql=True` and
  `force=False`. Since 0.2.6 it is refused: the kernel refuses a held wrapper that takes
  the object by name, under the method's own name for it too. Refused as well since
  0.2.6, although it runs correctly: the held wrapper that names the method's
  parameters without the object (`def second(sql="x", force=False)`), which 0.2.5's own
  reason advised (the kept-object family under Status). What is gated and runs as
  judged under such a decorator is a held wrapper that takes `*args, **kwargs` alone. A
  decorator that hands the object on to a held wrapper whose leading place is named as
  the tool names a parameter was gated up to 0.2.5, and every call of it raised
  `TypeError`; since 0.2.6 it is refused.
- **A change a tool body makes to another tool's function, for the calls of the same
  model turn.** The SDK runs the guardrail of every call of a turn before any tool body
  of that turn. A tool body that re-wraps the function of another tool (sets its
  `__wrapped__` to a wrapper with a parameter of its own, say) is not seen by a call to
  that tool in the same turn, which runs the new wrapper unjudged. A call in the next
  model turn is refused.
- **Code of your callables that runs while a tool is checked.** To find the callables a
  call reaches, the gate reads `__wrapped__` the ordinary way, as Python and
  `inspect.signature` do, so a `__wrapped__` property or a `__getattr__` of a callable
  object runs when the tool is gated and again on every call. The tests that recognise a
  single-dispatch function, a partialmethod and a weak proxy read the object's type, its
  closure cells and its attributes with `inspect.getattr_static`, which runs no property
  and no `__getattr__` of the object; the `isinstance` tests among them read an object's
  `__class__`. What a `functools.lru_cache` wrapper calls is read with the kernel's
  `cache_target`, which asks only the wrapper's own type: it lists what the cache refers
  to with `gc.get_referents` the first time it reads that cache, and calls nothing the
  cache holds.
- **What runs after the guardrail: the SDK's `on_tool_start` hooks.** The gate is a
  tool input guardrail. For each call the SDK runs the tool's input guardrails, then
  the run's and the agent's `on_tool_start` hooks, then the tool
  (`agents/run_internal/tool_execution.py`, lines 2041 to 2054 in `openai-agents`
  0.24.0 and 2066 to 2079 in 0.26.1). Nothing after the guardrail is seen by the gate.
  A hook that rewrites the arguments of the call it is shown (`context.tool_call`)
  fails closed, by the SDK's own check of the invocation the gate pinned: the tool
  does not run, and the SDK raises a `UserError`
  (`test_a_hook_that_rewrites_the_call_after_the_guardrail_runs_nothing`). A hook that
  reaches into the SDK's private state on the tool context and edits or removes the
  pinned invocation (`context._function_tool_arguments`) runs a value no policy
  judged: that is the application's own code changing the SDK's private state after
  the decision, and outside what this gate holds. It was so in 0.2.5 and earlier too.
  Do not write to the tool context in a hook.
- **Model settings given to a run.** Only the agent's own `model_settings` are read when
  it is gated. `RunConfig(model_settings=...)` is merged in when a run starts, and an
  `extra_body` there is not seen.
- **Legacy `functions` definitions in `extra_body`.** A `functions` key there is sent in
  the body of the request and is not refused. It only describes functions to the model:
  the SDK runs a call by looking its name up among the agent's own tools, so a call to a
  name that is not one of them raises `ModelBehaviorError` and nothing runs, and a call
  to a name that is one passes through that tool's guardrail.
- **A call the SDK rejects before the guardrail runs.** For each of these the tool does
  not run and the call is not on the audit log. These raise inside the SDK and stop the
  run: a tool call id the model reuses for another call, within one response or in a
  later turn, and a blank tool call id (`ModelBehaviorError`); arguments that hold a lone
  surrogate character (`UnicodeEncodeError`); and arguments nested about a thousand
  levels deep or more (`RecursionError`, at a depth that depends on the interpreter's
  recursion limit). A tool the agent does not have raises `ModelBehaviorError` too,
  unless the run is given `RunConfig(tool_not_found_behavior="return_error_to_model")`,
  under which the model reads the SDK's "not found" error and the run goes on. A call
  the model repeats under the id and with the arguments of a call that already ran is
  not run a second time by the SDK, and is not judged a second time.
- **An error of the interpreter inside the guardrail.** Under a recursion limit too small
  for the guardrail's own walk over the arguments it raises `RecursionError`. The SDK
  then stops the run with an error, the tool does not run, and there is no entry.
- **A realtime session.** `gated_agent` refuses a `RealtimeAgent`. `gate_tools` accepts a
  list of function tools whatever they are attached to, but a realtime session runs the
  guardrail on a tool context of its own, so the arguments the gate pinned are not the
  ones that session executes, and this package has no test of a realtime session.

**Beyond the gate.** This gate judges the tool calls the framework routes through it;
the paths around it inside the framework are listed above. Like every Recusal gate, it
does not stop an agent that can reach a resource another way: a credential with wider
rights, a shell or network path outside the agent, or a file it can write that
configures the gate. Use it as one layer of several: least-privilege credentials for the
agent, a sandbox or container, limits on its network egress, and an audit anchor the
writer cannot reach ([the limits in
full](https://github.com/philpaz/recusal/blob/main/SECURITY.md#things-worth-knowing)).

## Status

**In-depth review under way.** Its fixes so far are released in 0.2.5, and the review continues. 0.2.6,
which moves the reading of a decorated tool to the kernel, and 0.2.7, which takes one more
rule of the kernel's with `recusal` 0.18.2, have not been through a review round. Recusal is a Beta (`0.x`) open-source project in active
development: it is not a finished or certified security product, and it is provided under
Apache-2.0 without warranty.
[What the reviews are, and where every adapter stands](https://github.com/philpaz/recusal#project-status).

**From the latest review rounds.** Rounds five and six found gaps that the 0.2.0 release
has and 0.2.1 closes: a `functools.singledispatch` tool with nothing registered was
accepted, so an implementation registered during a model turn ran unjudged for a later
call of that turn; a dispatcher behind a callable object's `__call__` was not found; a
dispatcher was recognised by one code object read at import; a `functools.partialmethod`
hid the callable it holds; a `weakref.proxy` of a single-dispatch function was accepted;
and an ordinary event bus was refused as a single-dispatch function. A single-dispatch
function, a partialmethod and a weak proxy are now refused as a tool wherever the gate's
own walk reaches one (see the bullets above). Up to 0.2.2 it did not reach one behind a
cache named again for another function; since 0.2.3 it does (below).

**From round seven, closed by the kernel.** Round seven found two stacks of decorators
that the kernel's walk in `recusal` 0.15.0 and 0.15.1 reads as a pass-through, so a
parameter of a wrapper under them ran with a value the policy was not shown. Both are in
0.2.0 and 0.2.1 installed beside either of those kernels. The walk of `recusal` 0.16.0
reads both, and 0.2.2 requires `recusal` 0.16.0:

- **A `functools.partial` that carries a `__wrapped__`.** A decorator written as
  `functools.update_wrapper(functools.partial(helper, f), f)` (or
  `functools.wraps(f)(functools.partial(helper, f))`) is followed to `f`, and a wrapper
  under it that adds a parameter of its own is refused. A wrapper the partial binds as
  an argument, other than the function it names, is not read (see "What the gate does
  not see").
- **`functools.wraps(f)` written above `functools.lru_cache`.** The cache names `f` and
  calls the wrapper it was built over. The kernel's walk reads that wrapper: one that
  only forwards is gated, and one with a parameter of its own is refused where the walk
  reaches it. Behind a `weakref.proxy` the walk of 0.16.0 did not reach it; 0.2.3
  refuses the proxy (below).

**What 0.2.2 changes.** Every refusal the kernel's walk makes by a class of its own
reaches you with a reason that says what was found and what to do. A bound argument the
walk cannot follow through a wrapper, a cache whose function cannot be told, and a
declared signature were each reported as "cannot be inspected" with the name of an
exception class. The reason for a decorator that holds a second wrapper said that the
wrapper takes a parameter of its own, which is not the cause of every such refusal.
Every reason that advises registering a plain function now says that the gate judges
that function's parameters and does not read what its body calls.

**What 0.2.3 changes.** It requires `recusal` 0.17.0, and closes the first three of the
four items 0.2.2 stated as open. Each was gated by 0.2.2 beside `recusal` 0.16.0 and ran
a value no policy judged:

- **Behind a cache named again for another function.** The gate's own walk followed
  what the cache names, so its own questions were not asked of what the cache calls,
  and the kernel's walk of 0.16.0 refused less there. A single-dispatch function with
  nothing registered was gated (an implementation registered after the check ran for
  the judged call, and the judged call itself could register it), and so was whatever
  stood behind a `weakref.proxy`: a wrapper with a parameter of its own, a dispatcher
  with an implementation registered before the tool was gated, and a second cache named
  again that calls a `functools.partialmethod` through a `functools.partial` or a
  wrapper. The gate's own walk now also follows what the cache calls, with the kernel's
  `cache_target`, and refuses the dispatcher and the proxy there with the reasons it
  gives the ones it finds elsewhere. The kernel's walk of 0.17.0 refuses them too.
- **A held wrapper that takes the tool's parameters in another order** is refused by the
  kernel's walk of 0.17.0, with a reason that names the two parameters. Beside 0.16.0 it
  was gated, and the function ran with the values swapped.
- **A held wrapper with a parameter of its own on a way 0.16.0 did not follow**, through
  a class-based decorator, a callable object, a `functools.partial` that carries a
  `__wrapped__`, a weak proxy, a cache named again or a second held wrapper, is refused
  by the kernel's walk of 0.17.0, with a reason that names the parameter.

The three refusals `recusal` 0.17.0 adds have reasons of their own: a single-dispatch
function with nothing registered (`OpenDispatch`), a callable that answers for another
object (`ProxiedCallable`), and a weak proxy (`WeakProxy`, which gets the reason the gate
gives a proxy its own walk finds). 0.2.2 beside 0.17.0 named the class alone ("the
function it runs cannot be inspected (WeakProxy)"). A cache whose function cannot be
told, met by the gate's own walk, is refused with the reason for one, not with the reason
for a callable the gate cannot question. The tests in `TestStatedLimits` hold each closed
item as refused, before any policy is asked and before anything runs.

The reviews of 0.2.3 before its release found more, answered here:

- **A method facade that drops its object**, over a function whose first parameter has
  no default, was gated and ran with every value one place off (the bullet on a method
  over a wrapper of a function not written to take what is bound, above). The kernel's
  walk of 0.17.0 read it; the gate refuses it itself where the dropped place is not
  named `self` or `cls`, and the same shape through a `functools.partial`. Where the
  place is named `self` or `cls` the shape is a decorator that forgets the object, and
  it is open (below). The walk of 0.17.1 refuses some of these forms first (0.2.4,
  below).
- **The advice of the reasons.** Followed literally, 11 of 15 reasons gave a gated tool
  that ran the cause: most advised calling the refused function from a plain function and
  registering that, and the gate reads a plain function's parameters and never its body.
  Every reason now advises removing the cause (drop a wrapper's own parameter or pass it
  explicitly, keep a held wrapper in the tool's order or keyword-only, register the
  function itself, call `functools.update_wrapper(self, fn)`, write the method out in
  place of a partialmethod with the held callable's work in its own body, branch on the
  type in one plain function's body), and ends by saying why the other way does not. A
  reason that quoted the kernel's text, whose own advice could then be to call the
  refused function from a plain function, said first not to follow that part, and gave
  the kernel's text last (0.2.4 changes that note, below). `TestReasonAdvice` follows
  each piece of advice and runs the result.
- **A false refusal**: a callable object whose class has a member named `partialmethod`,
  behind a cache named again, was refused as running a `functools.partialmethod`. That
  name is no name Python reads; it now counts only where the object itself holds it.

**What 0.2.4 changes.** It requires `recusal` 0.17.1 and changes no rule of its own.
Beside 0.17.0, 0.2.3 gated these, and each ran with the judged values one place off;
the walk of 0.17.1 refuses each before any policy is asked and before anything runs,
and each is held by a test named `test_closed_` in `TestStatedLimits`:

- **A held wrapper with a parameter of its own in the object's place**, under a method
  decorator that keeps the object (`def second(mode, sql="x", force=False)`), which
  this page stated as open: judged `sql="S"` and `force=True`, it ran `sql=True` and
  `force=False`.
- **A held `functools.wraps` wrapper that takes the object under another name and drops
  it** (`def forward(receiver, *args, **kwargs): return run(*args, **kwargs)` over
  `def run(self, sql="x", force=False)`): it ran `self="S"`, `sql=True`,
  `force=False`.
- **A method decorator that takes the object under another name than the method has for
  it and forgets to pass it on** (`self` over a class method's `cls`), which this page
  stated as open with the decorator that forgets the object.
- **A facade that drops its object over a module function whose first parameter is
  named `cls`**, as a method of an instance. The gate's own rule takes `cls` for an
  object's place and did not refuse it: judged `sql="SELECT 1"` and
  `note="DELETE FROM audit_log"`, it ran `cls="SELECT 1"` and
  `sql="DELETE FROM audit_log"`. Found by running the review probes of 0.2.3 beside
  0.17.1.

The reasons. A method facade over a function whose first parameter is not named `self`
or `cls`, where the facade takes the object as `self`, is now refused by the kernel's
walk before the gate's own rule is asked, so its reason is the one for a bound argument
a wrapper may keep, with the kernel's text, and not the gate's own; the verdict is the
same. The kernel's text in 0.17.1 advises no plain function that calls the refused
one, so the note that said not to follow that part is gone. In its place, the two
reasons that quote the kernel's text for a bound argument (a held wrapper, and a bound
argument a wrapper may keep) say first that its advice to take the argument under the
name the function has for that place, and hand it on by position, removes the cause
only where no other wrapper on the way keeps the object: where one does, the tool so
written can be gated and run every judged value one place off, and the gate's own
advice is to be followed. `TestReasonAdvice` follows both pieces of advice on a real
tool of each kind. The reason for a callable that answers for another object quotes
advice that removes the cause, and has no note.

**What 0.2.5 changes.** It gates function tools beside `openai-agents` 0.26.1 again
([issue #358](https://github.com/philpaz/recusal/issues/358)), and changes no rule, no
reason and no requirement: `recusal>=0.17.1` and `openai-agents>=0.24.0` as before.
From 0.26.1, `function_tool` adds a before-validator of the SDK's own
(`prepare_strict_json_values`) to every parameter model it generates, which puts the
model's fields one node deeper in its core schema. 0.2.4 read the fields at the old
place, found none, and refused every function tool as one whose parameter model
cannot be read. That was a refusal and not a bypass: no tool ran unjudged.

- The gate reads through that one validator and no other. It is known by the test the
  SDK's own rule applies, not by its shape: a method bound to the very parameter model
  whose function is the SDK's `prepare_strict_json_values`. Pydantic gives any
  before-validator on a model the same node, so a parameter model with a
  before-validator of another function, a second validator under the SDK's, an after
  or a wrap validator, or anything but its fields under the SDK's validator is
  refused as before.
- The reasons that name a parameter name it beside 0.26.1 too: for a type the SDK
  prepares only by running the tool's own code, a default that is not JSON data, a
  default factory other than `list` or `dict`, and a mapping keyed by another type
  than `str`.
- `TestTheSdksOwnDecoder` holds both halves on whichever SDK is installed, and
  `tests/test_compat_openai_agents.py` pins the two shapes the gate reads, so a third
  shape in a later SDK release fails there first.
- Run on `openai-agents` 0.24.0 with `openai` 3.49.0 (the versions every pull request
  is tested against) and on `openai-agents` 0.26.1 with `openai` 3.60.0, each on
  Python 3.10.22 and 3.12.5 on Windows, and on 0.25.0 and 0.26.0 on Python 3.12.5;
  the counts are in the
  [changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md). Every pull
  request still runs 0.24.0 only; 0.26.1 and whatever is newest are run by the weekly
  lane.

**What 0.2.6 changes.** It requires `recusal` 0.18.0 (0.2.5 allowed 0.17.1), and the
reading of a decorated tool is the kernel's: the gate asks
`recusal.invocation.judged_parameters` the way the SDK calls a tool, and passes on
`refusal_reason`, whole and alone. Gone from this package are the two rules it had of
its own for a wrapper (one that takes other parameters than the tool declares; a method
or a positional `functools.partial` over a wrapper of a function whose leading parameter
is not named `self` or `cls`) and its own reason for each class of refusal the kernel
makes, with the note that came before the kernel's text. The kernel asks both rules,
and more, for every framework. So the words of those refusals change (they are the
kernel's, which say what was found and what to write instead), and more tools are
refused: ten families of decorators, stated below, with the members of each that run
correctly, what to write instead, and what was measured against 0.2.5 (an eleventh
from 0.2.7, below). Two shapes this page stated as open are refused now (a method decorator that names the method's
parameters and passes them on without the object, and a held wrapper that takes the
object under the method's own name and names a parameter after it), and so is one it
stated as not found (a wrapper handed in as the argument of a named partial); each ran
a value no policy judged, or a judged value under another name, under 0.2.5. It is not
a new review round.

**What 0.2.7 changes.** It requires `recusal` 0.18.2 (0.2.6 required 0.18.0), whose
kernel asks of the run context the rules it asks of a method's object past a wrapper
that names a positional parameter (rule L of `recusal.invocation.judge_tool`). The gate
asks the kernel the same question, the same way, and holds no rule of its own for it.
One shape this page stated as open is refused now: a `functools.wraps` wrapper that
restates the parameters of a function that takes the run context first, the context's
place with them, and passes the judged values on without the context (`def
wrapper(ctx, table, limit=10): return fn(table, limit)`). 0.2.5 and 0.2.6 gated it,
and the SDK's call ran every judged value one place off. Its signature is the one the
wrapper that hands the context on has, so that one is refused too, although it runs
correctly: the context-restating family, below. It is not a new review round.

What the gate still asks itself, with reasons of its own, and discloses: that the tool
was built by `function_tool`; a variadic parameter; the SDK's own rule for a parameter
type it prepares without running the tool's code, and a mapping's key type; the three
questions it asks of the callables on the way (a single-dispatch function, a
`functools.partialmethod`, a weak proxy), a callable they cannot be asked of, and more
callables than they are asked of (512); that the SDK's invoker exposes the function;
and, new in 0.2.6, that the function shows the parameters the SDK built its schema
from. The last is refused where a function's `__wrapped__` is pointed at a function of
other parameters after the tool was made: the values are named by the SDK's schema, the
kernel's verdict is about the function as it stands, and the gate holds the two to each
other. The names are compared with the ones the kernel returns. The kernel returns no
kinds, so the kinds are held by the SDK's own reading: the SDK built the signature its
schema keeps with `inspect.signature` of the function (in `function_schema`), and on
every call the gate builds that signature of the function as it stands the same way
and compares the two, whole. This evaluates no annotation and builds no model, so no
code of a tool's annotations runs for it. A function whose
`__wrapped__` is pointed, after the tool was made, at one that takes a parameter
keyword-only is refused, as 0.2.5 refused it
(`test_a_function_that_changes_a_kind_after_the_tool_was_made_is_refused`). This is
asked of a function, a method or a built-in. Of a callable object the SDK builds its
schema from an adapter of its own, so the comparison is not made, and a kind changed on
one after the tool was made is not held.

**How the SDK calls a function tool, which is what the kernel is asked with.** The SDK
builds the call in `FuncSchema.to_call_args` (`agents/function_schema.py`, lines 46 to
89 in `openai-agents` 0.24.0 and in 0.26.1, where the method is the same text): a
parameter that is positional-only or positional-or-keyword goes by position, in the
order of the signature, and a keyword-only one by keyword; the first parameter is left
out where the SDK reads it as its run context (`takes_context`, set in
`function_schema` where the first parameter is annotated `RunContextWrapper` or
`ToolContext`). `function_tool` then calls `the_func(ctx, *args, **kwargs_dict)` for
such a tool and `the_func(*args, **kwargs_dict)` for any other (`_on_invoke_tool_impl`
in `agents/tool.py`, lines 2824 to 2832 in 0.24.0 and 2835 to 2843 in 0.26.1). So the
gate asks the kernel by position (`POSITION`), with one leading argument where the
SDK's own schema for the tool says it takes the run context and none otherwise, and
leaves no name out. `tests/test_reading_conformance_openai_agents.py` drives a wrapper
that records how it was called through `Runner.run` and `Runner.run_streamed` and holds
all of it: every positional parameter by position, a default the model left out among
them, the keyword-only one by keyword, and the run context first. The policy judges the
invocation the SDK prepared, as before, and an allowed call's prepared arguments are
pinned on the tool context, so what the kernel gives the gate is the verdict and the
reason, and the values are the SDK's.

**Why the kernel is not asked by name.** The kernel can ask four questions of each
parameter of the tool's own, together (`by_name`): a variadic parameter, a
positional-only one, an annotation outside its supported data types (`str`, `int`,
`float`, `bool`, `Optional` of one, `list[T]` and `dict[str, T]`), and a default
outside the JSON domain. This gate refuses a variadic parameter and none of the other
three, and asking them would refuse tools 0.2.5 gates and this page lists under
Parameter types: a `Literal`, `Any`, a parameter with no annotation, a union, an
`Annotated` description, `Field(default_factory=list)` and a positional-only parameter
of a plain function are each refused by the kernel where it is asked by name, and each
is read by this gate, which judges the value the SDK prepared and passes on
(`test_what_asking_by_name_would_refuse_is_read_and_judged_as_the_sdk_prepares_it`).
A positional-only parameter is not read everywhere: on a method under a decorator that
takes the object by name, or under `functools.lru_cache`, it is refused since 0.2.6 by
another rule of the kernel's, which is not asked by name (the positional-only family
below).
So the gate does not ask by name, and keeps its own refusal of a variadic parameter,
read from the signature the SDK's schema keeps of the tool, until the kernel asks that
question alone. The kernel's design named `by_name` for this route for the variadic
parameter; the registry of `tests/test_adapter_conformance.py` records the change and
why.

**The eleven families newly refused in part.** Each is stated once, and
`tools/differential/openai_agents.py` generates every member of each, through both
gates, and counts as a finding a member that is not as this page says. The first four
are generated by `tools/differential/openai.py`, member for member as
`recusal-openai`'s page states them; the SDK makes no `FunctionTool` of a
`functools.partial` or of a callable object that carries `__wrapped__`
(`function_tool` raises `UserError`), so a member whose outermost callable is one
reaches no gate, and a family is stated of the tools in it.

- **A restating wrapper**: a `functools.wraps` wrapper with a signature of its own and
  no `*args` or `**kwargs`. Over a plain function it is read only where it takes every
  parameter of the function, in the function's order, each of the function's kind, and
  gives none a default the function does not give it (the function's own default, or
  none). Over a method, taking the object first, it is read only where besides the
  method gives no parameter a default. Whatever its body does: each wrapper is
  generated with a body that hands every value on by keyword, with one that hands them
  on by position in the function's order and with one that hands them on by position
  in its own, and on a method with bodies that hand the object on and that drop it.
  0.2.5 refused another order, a parameter left out and another kind by its own rule.
  Newly refused are the wrappers 0.2.5 read: one with a default that is not the
  function's own, and, over a method that gives a parameter a default, one that takes
  the method's parameters in the method's order and kinds (`def wrapper(self, table,
  limit=10)` over `def purge(self, table: str, limit: int = 10)`): where its body
  passes the values on without the object (`return fn(table, limit)`), the SDK's call
  by position ran every judged value one place off, judged `{table: "t", limit: 5}`
  and ran `self="t"`, `table=5`, `limit=10`. Nothing in the wrapper's signature tells
  that body from one that hands the object on, so both are refused. Give the wrapper
  only `*args` and `**kwargs` after the object and hand them on with it, or the
  function's own order, kinds and defaults over a plain function.
- **A held wrapper**: a method decorator whose own wrapper calls a second wrapper of
  the method that the decorator holds. Where the held wrapper names the method as
  `__wrapped__` (`functools.wraps`, or the attribute set by hand), takes the object by
  name, under the method's own name for it (`self`) or another, and is held in the
  decorator's closure or in a module global its code names, the tool is refused:
  whatever the held wrapper takes after the object (`*args, **kwargs`, or the method's
  parameters, by position or keyword-only), whether it hands the object on or drops it,
  and whether the decorator's own wrapper is `outer(*args, **kwargs)` or `outer(self,
  *args, **kwargs)`. Where the held wrapper takes `*args, **kwargs` alone, the object
  in `*args` with the rest, it is read. 0.2.5 refused the ones that take the object
  under another name; newly refused are the ones that take it as `self`. Two kinds of
  held wrapper are read whatever they take (Open): one that names nothing as
  `__wrapped__`, and one the decorator keeps anywhere else than its closure or a module
  global its code names (an attribute of an object, as generated here with a
  `types.SimpleNamespace`), where the kernel does not look. Take the object in `*args`
  with the rest in the held wrapper (`def inner(*args, **kwargs): return fn(*args,
  **kwargs)`). Every member of this family calls the wrapper it holds, and each held
  wrapper is named for the method; a helper the decorator only names, or one named for
  another function, is the held-helper family below.
- **A held object**: a decorator that holds a class-based wrapper (an object with a
  `__call__`) and calls it. The tool is refused where the held object is named for the
  function with `functools.update_wrapper`, its `__call__` is not a plain method of its
  class (a `staticmethod`, another callable object), and an argument goes in by position
  ahead of the judged ones or is bound on the way: on a method, on a function that takes
  the SDK's run context, and on a plain function with a class-based decorator under it
  in the same stack. Its parameters cannot be read from a code object there, so whether
  it takes the place of that argument cannot be told. Otherwise it is read (Open says
  what that leaves). Write its `__call__` as a method (`def __call__(self, *args,
  **kwargs)`).
- **A held count**: a pass-through decorator whose code names many callables, the ones
  it never calls too. Where an argument is bound on the way or goes in ahead of the
  judged ones (the decorator is on a method, or on a function that takes the SDK's run
  context), the kernel looks at what the
  callables on the way hold, stops at about 512 callables in one walk, and refuses a
  tool it could not read to the end (generated here with 700 and 2,000 names, which are
  refused, and 300, which is read). Over a plain function with nothing bound on the way
  it does not look, and the tool is read whatever the count. Keep such a decorator's
  own code to the wrappers it calls.
- **A named partial**: a `functools.partial` that carries `__wrapped__`, as
  `functools.wraps` and `functools.update_wrapper` give it one, and that a wrapper on
  the way names as what it wraps, or that stands under a method decorator (the SDK
  makes no tool of a partial that is itself what `function_tool` is given). Where it
  binds nothing it is read as what it is of is read (generated here: a plain function
  and a bound method). One that binds a value, by position
  (`functools.wraps(f)(functools.partial(helper, f))`, the partial of a helper, which
  0.2.5 read to the end) or by keyword (`functools.wraps(f)(functools.partial(f,
  limit=7))`, refused by 0.2.5 too), is refused, and so is every one of a method's
  function under a method decorator. Write the decorator's wrapper as a function of
  its own (`@functools.wraps(f)` over `def wrapper(*args, **kwargs): return helper(f,
  *args, **kwargs)`). The rule asks about a partial that carries `__wrapped__`, and
  about no other. Read as under 0.2.5 (Open): a partial that a pass-through holds in
  its closure and does not name, whatever it binds; and a partial that carries no
  `__wrapped__`, which is judged by the signature it shows.
- **A held context helper**: a pass-through decorator, on a function or a method that
  takes the SDK's run context first, that holds a helper in a module global its code
  names or in its closure, whether its own wrapper calls the helper or only names it.
  Where the helper names nothing as `__wrapped__` the tool is read, whatever the helper
  takes. Where the helper is named with `functools.wraps`, for the function or for
  another, the tool is read only where the helper takes `*args, **kwargs` alone, and
  refused where it names a parameter. 0.2.5 refused the ones that take the context
  under another name, leave it out, or take it and hand the rest on in `*args`; newly
  refused are the ones that take it under the function's own name for it and name the
  function's parameters after it (`@functools.wraps(fn) def audit(ctx, table): ...`,
  held by a decorator of `def lookup(ctx: RunContextWrapper, table: str, limit: int =
  10)`), also where the decorator only names the helper and never calls it. Give the
  helper `*args, **kwargs` alone, or do not name it with `functools.wraps`.
- **A kept object**: a method decorator whose own wrapper takes the object, keeps it,
  and calls a second wrapper of the method that it holds, handing it the judged values
  alone (`def outer(self, *args, **kwargs): return inner(*args, **kwargs)`). Where the
  held wrapper names nothing as `__wrapped__` the tool is read. Where it is named with
  `functools.wraps`, the tool is read only where the held wrapper takes `*args,
  **kwargs` alone or takes every parameter keyword-only, and refused where it names a
  parameter a position can fill. 0.2.5 refused the ones that take the method's
  parameters in another order or a parameter of their own first; newly refused are the
  ones that take the method's parameters in the method's order (`def inner(table,
  limit=10)`), which run correctly: from the two signatures the kernel cannot tell that
  the first value handed on is not the object. (Keyword-only, the tool is read and
  every call raises a `TypeError`, since the decorator hands the values on by
  position.) Give the held wrapper `*args, **kwargs` alone.
- **A held helper**: a pass-through method decorator (`def outer(*args, **kwargs)`) that
  holds a helper in a module global its code names or in its closure, whether its own
  wrapper calls the helper or only names it in its body. Where the helper names nothing
  as `__wrapped__` the tool is read, whatever the helper takes. Where the helper is
  named with `functools.wraps`, for the method or for another function, the tool is
  read only where the helper takes `*args, **kwargs` alone, and refused where it names
  a parameter. 0.2.5 refused the ones that take the object under another name than the
  method has for it; newly refused are the ones that take it as `self`, or that name
  the method's parameters without it, also where the decorator never calls the helper
  (`@functools.wraps(other) def audit(self, table, limit=10): ...`, only named in the
  body of a decorator that hands everything on to the method). The kernel reads what a
  decorator holds and not what its body does with it. Give the helper `*args,
  **kwargs` alone, do not name it with `functools.wraps`, or keep it out of the
  decorator's closure and of the names its code uses.
- **A positional-only parameter**: a method or a class method with a positional-only
  parameter after the object (`def purge(self, table: str, /, limit: int = 10)`). It is
  read under no decorator and under pass-throughs alone (`def wrapper(*args,
  **kwargs)`), and refused where a decorator on the way takes the object by name (`def
  wrapper(self, *args, **kwargs): return fn(self, *args, **kwargs)`) or a
  `functools.lru_cache` stands on the way, although it runs correctly: 0.2.5 gated
  each on a method, and each ran as judged (a class method it gated under
  `functools.lru_cache` and refused under such a decorator). The kernel cannot tell
  from such a wrapper's signature whether the object reaches its place,
  and where it does not, a positional-only parameter after it takes a value by
  position that a keyword could not correct. A
  method with no positional-only parameter is read under each of these, alone and two
  deep. A plain function with a positional-only parameter, and a function that takes
  the SDK's run context ahead of one, are read under a pass-through, under
  `functools.lru_cache` and under the two together. Make the parameter one a keyword
  can fill (no `/`), or take the object in `*args` with the rest in the decorator.
- **A context place**: a function whose first parameter is annotated as the SDK's run
  context (`RunContextWrapper`, `ToolContext`). The SDK passes the context first, by
  position, so the gate asks the kernel with one argument ahead of the judged ones. It
  is read where a position can fill that place (an ordinary parameter, or a
  positional-only one), alone and under a pass-through, and refused where none can:
  `def lookup(*ctx: RunContextWrapper, table: str, limit: int = 10)`, which 0.2.5 gated
  and which ran as judged, and a keyword-only context, for which the SDK's own call
  raises a `TypeError`. Take the context as an ordinary first parameter.
- **A context restating wrapper** (new in 0.2.7, beside `recusal` 0.18.2): a
  `functools.wraps` wrapper that restates the parameters of a function that takes the
  SDK's run context first, the context's place with them, under the function's name for
  it (`def wrapper(ctx, table, limit=10)` over `def lookup(ctx: RunContextWrapper, table:
  str, limit: int = 10)`), alone, under a pass-through or over one. The SDK passes the
  context first, by position, and the judged values by position after it. Where the
  wrapper's body passes the values on without the context (`return fn(table, limit)`),
  each runs one place off and the last place left runs at its default: judged `{table:
  "t", limit: 5}`, it ran `ctx="t"`, `table=5`, `limit=10`. The tool is refused where the
  place so left without a value has a default to run at (a default of a positional
  parameter after the context, or of a keyword-only one), whatever the body does: the
  wrapper that hands the context on (`return fn(ctx, table, limit)`) is refused too,
  although it runs correctly. It is read over a function that gives no parameter a
  default: there the wrapper that hands the context on runs as judged, and the one that
  drops it fails the call with a `TypeError`. 0.2.5 and 0.2.6 read every member. Give
  the wrapper `*args` and `**kwargs` alone and hand them on (`def wrapper(*args,
  **kwargs): return fn(*args, **kwargs)`), which is read.

**Measured against 0.2.5.** `python tools/differential/openai_agents.py --summary` puts
the same calls to the gate as released (read out of git at the tag
`recusal-openai-agents-v0.2.5`) and to this one, both beside `recusal` 0.18.2, each on a
fresh tool, through the SDK's real entry (the tool made a `FunctionTool` by the SDK's
own `function_tool`, put on an `Agent`, the agent gated, one call proposed by the SDK's
scripted model) and under a policy that allows every call, so that each comparison has
what was judged and what the tool then ran: the 58 rows of the kernel's shared table of
decorator shapes, 210,600 calls of generated stacks of one to three decorators (36
decorators over 9 functions, each called with every parameter given and with a default
left out), 14,448 calls of stacks of one and two decorators (42 decorators) over 4
functions that take the SDK's run context first, 5,328 calls of stacks of one and two
decorators over 2 functions with a positional-only parameter, 4,298 calls of the eleven
families above (1,224 of the restating wrappers, 1,386 of the held wrappers, 264 of the
held objects, 24 of the held counts, 712 of the named partials, 264 of the held context
helpers, 120 of the kept objects, 132 of the held helpers, 108 of the positional-only
parameters, 16 of the context places and 48 of the context-restating wrappers), and
every tool the adapter's own test files put to the gate. Each set but the last is
compared twice, through `Runner.run` and through `Runner.run_streamed`, and every count
is the same through both. It was run twice, on Python 3.12.5 on Windows: beside
`openai-agents` 0.24.0 with `openai` 3.49.0, the versions every pull request is tested
against, and beside `openai-agents` 0.26.1 with `openai` 3.60.0. In no set, beside
either, is a call that 0.2.5 refused read by 0.2.7, are the arguments judged for a tool
both read any other, does a tool both read run otherwise than it did, or does a tool
this gate reads run otherwise than it does on an agent that is not gated. No tool both
read runs a value no policy judged outside the limits this page states as open, and no
call is newly refused for a cause this page does not list: a cause is told by the first
sentences of the kernel's reason, so the kernel's rules are told apart, and the match is
exact. Beside `openai-agents` 0.24.0, 0.2.7 newly refuses 19 rows of the table (10 ran
as judged, 1 raised and 8 ran a value no policy judged under 0.2.5), 17,656 of the
generated calls (3,230 ran as judged, 2,446 raised and 11,980 ran a value no policy
judged), 606 of the calls over a run context (218 ran as judged, 88 raised and 300 ran a
value no policy judged), 394 of the calls over a positional-only parameter (104 ran as
judged, 22 raised and 268 ran a value no policy judged) and 832 of the calls of the
families (432 ran as judged, 256 raised and 144 ran a value no policy judged). Read by
both: 16 rows, 3,286 generated calls, 304 calls over a run context, 160 calls over a
positional-only parameter and 1,534 calls of the families. The SDK makes no tool of 4
rows, 11,552 generated calls, 688 calls over a run context, 296 calls over a
positional-only parameter and 456 calls of the families, which reach neither gate.
Beside `openai-agents` 0.26.1, 0.2.7 newly refuses 19 rows of the table (10 ran as
judged, 1 raised and 8 ran a value no policy judged under 0.2.5), 17,656 of the
generated calls (3,230 ran as judged, 2,446 raised and 11,980 ran a value no policy
judged), 606 of the calls over a run context (218 ran as judged, 88 raised and 300 ran a
value no policy judged), 394 of the calls over a positional-only parameter (104 ran as
judged, 22 raised and 268 ran a value no policy judged) and 832 of the calls of the
families (432 ran as judged, 256 raised and 144 ran a value no policy judged). Read by
both: 16 rows, 3,286 generated calls, 304 calls over a run context, 160 calls over a
positional-only parameter and 1,534 calls of the families. The SDK makes no tool of 4
rows, 11,552 generated calls, 688 calls over a run context, 296 calls over a
positional-only parameter and 456 calls of the families, which reach neither gate. (The
ones that ran as judged are refused although they run correctly, by the causes above;
where the call raised, nothing ran as judged under 0.2.5 either; the ones that ran a
value no policy judged, or a judged value under another name, are what the move closes.)
The test files make, beside 0.24.0, 1,598 checks of a tool: 1,011 read by both, 461
refused by both, 126 newly refused, in 58 tests (18 of them, in 7 tests, while the test
had replaced a name of the gate's module, which forces the refusal), and none left out
of the comparison; beside 0.26.1, 1,598 checks of a tool: 1,011 read by both, 461
refused by both, 126 newly refused, in 58 tests (18 of them, in 7 tests, while the test
had replaced a name of the gate's module, which forces the refusal), and none left out
of the comparison. They are compared for the verdict alone. `--list` prints each newly
refused call. `tests/test_differential_openai_agents.py` runs the short form of it, the
table, the stacks of one and two decorators, the stacks over a run context and over a
positional-only parameter and every member of the eleven families, through both routes,
in the OpenAI Agents jobs of CI. The script says at its top what it does not show: it
compares the two gates on these tools and no others, and zero findings is not a proof
about a decorator that is not in the lists.

**Refused although it runs correctly.** The kernel's walk reads parameters and not
bodies, so it refuses some signatures a correct tool can have. Each is described in the
list of refused tools above.

- Since 0.2.2: a facade that is handed a bound argument and does pass it on; a declared
  signature that this Python would not read or that matches the real parameters; a
  decorator that holds a cache named again for the function over anything but a plain
  function; a cache named again over a `functools.partial` of a second cache or of a
  `staticmethod` object; and a `functools.partial` of a `staticmethod` object under a
  decorator. 0.2.1 beside `recusal` 0.15.1 gated the second and the third, and the
  fourth where the decorator is written with `functools.update_wrapper` over a
  `functools.partial` (under an ordinary `functools.wraps` decorator it refused that one
  too).
- New in 0.2.3, beside `recusal` 0.17.0. Each was gated by 0.2.2 beside `recusal`
  0.16.0, and each was run through this gate: it runs correctly and is refused.
  - A `weakref.proxy` of a plain function behind a cache named again for another
    function. Register the function itself.
  - A single-dispatch function that nothing is ever registered on, behind such a cache.
    Register the base function itself.
  - A class-based decorator that keeps the function in an attribute and hands every
    other attribute on with `__getattr__`, over a function that names a `__wrapped__`
    (any `functools.wraps` decorator, any `functools.lru_cache`). Call
    `functools.update_wrapper(self, fn)` in its `__init__`.
  - A decorator that holds a wrapper which takes the tool's parameters in another order
    and calls it by keyword or puts the values back. Give the held wrapper the tool's
    parameters in the tool's order, or by keyword only.
  - A decorator that holds a `weakref.proxy` of a helper. Hold the helper itself.
  - A decorator that holds a cache named again for another function over anything but
    a plain function (a `functools.partial`). Hold a cache of the function itself,
    or register the function itself.
  - A method, or a `functools.partial` with positional arguments, over a wrapper of a
    function whose first parameter is not named `self` or `cls`, where the wrapper does
    hand the bound argument on. Register the function itself. This one is refused by the
    gate's own rule, as are the next two, where the kernel's walk reads them; beside
    `recusal` 0.17.1 that walk refuses first the forms whose wrapper takes the bound
    argument under another name than the function has for it (`self` over `database`).
  - A correct decorated method whose object's place is named otherwise than `self`
    (`this`). Name it `self`. Under a decorator that takes the object as `self`, the
    kernel's walk of 0.17.1 refuses it first.
  - Two method facades that drop their object, one over the other, behind a cache named
    again for a function that shows the whole signature: the SDK reads that signature,
    and each drop is what makes the call correct. Register the function itself.

  The kernel's entry for 0.17.0 in the changelog has the whole list for its walk, each
  with what to write instead; the rest of it (an object whose `__class__` is not its
  type, a subclass of `wrapt.CallableObjectProxy` whose `__call__` names the
  parameters, a chain of held callables 32 links deep, held values that lead to more
  than 16,384 callables) was not run through this gate.
- New in 0.2.4, beside `recusal` 0.17.1, refused by its walk. Each was gated by 0.2.3
  beside `recusal` 0.17.0, and each was run through this gate: it runs correctly and is
  refused.
  - A method decorator that takes the object under another name than the method has for
    it and hands it on: `def wrapper(this, *args, **kwargs): return m(this, *args,
    **kwargs)` over `def run_sql(self, ...)` or over a class method's `cls`, and `self`
    over `cls`. Take the object under the name the method has for it (`self`, `cls`)
    and hand it on by position.
  - A held `functools.wraps` wrapper that does the same (`def forward(receiver, *args,
    **kwargs): return run(receiver, *args, **kwargs)` over `def run(self, ...)`, called
    by a pass-through). Take the object in `*args` with the rest (`def forward(*args,
    **kwargs): return run(*args, **kwargs)`). Up to 0.2.5 this page said to take it
    under the name the function has for it and hand it on by position, which the
    kernel's text for this refusal still advises; since 0.2.6 the held wrapper so
    written is refused as well (the held family above).
  - A held helper whose chain of `__wrapped__` comes back on itself
    (`helper.__wrapped__ = helper`). Name the function it wraps, once.

  Following each of these three remedies was run through this gate: it is gated and
  runs as judged. The kernel's entry for 0.17.1 in the changelog has its whole list,
  under "Refused although it runs correctly". The rest of it, a facade that hands its
  object on, or passes a value of its own in its place, over a function that names that
  place otherwise (`return search(self.tenant, *args, **kwargs)` over
  `def search(tenant, limit=10)`), 0.2.3 refused already beside 0.17.0, by the gate's
  own rule; where the facade takes the object as `self`, the walk of 0.17.1 now refuses
  it first, with its own reason.

- New in 0.2.6, beside `recusal` 0.18.0, each by a rule the kernel asks for every
  framework (0.2.5 beside the same kernel gated each, and it ran as judged). They are
  the members of the ten families above that run correctly:
  - A restating wrapper over a plain function that hands every value on and gives a
    parameter a default that is not the function's own (`def w(sql="", limit=99)` over
    `def fetch(sql: str = "", limit: int = 10)`: the SDK passes every parameter, so the
    wrapper's own default never applied). Give the wrapper the function's own defaults,
    or only `*args` and `**kwargs`.
  - A method decorator that restates the method's parameters, the object's place with
    them, and hands each on (`def wrapper(self, table, limit=10): return fn(self, table,
    limit)`), over a method that gives a parameter a default, on a method or a class
    method. Give the wrapper only `*args` and `**kwargs` after the object and hand
    them on with it.
  - A held `functools.wraps` wrapper that takes the object under the method's own name
    and hands it on (`def inner(self, *args, **kwargs): return fn(self, *args,
    **kwargs)`, or naming the method's parameters after `self`), called by `def
    outer(*args, **kwargs)` or by `def outer(self, *args, **kwargs)` that hands the
    object on. Give the held wrapper `*args` and `**kwargs` alone.
  - A held `functools.wraps` wrapper that names the method's parameters in the method's
    order, under a method decorator that keeps the object and hands it the values
    alone (the kept-object family). Give the held wrapper `*args` and `**kwargs` alone.
  - A held object named with `functools.update_wrapper` whose `__call__` is a
    `staticmethod` or another callable object and hands every argument on, on a method,
    on a function that takes the SDK's run context, or on a plain function over a
    class-based decorator. Write its `__call__` as a method.
  - A named partial that binds a value by position for a helper, named for the
    function and named by a wrapper on the way as what it wraps
    (`functools.wraps(f)(functools.partial(helper, f))` under a pass-through). Write
    the decorator's wrapper as a function of its own.
  - A decorator on a method, or on a function that takes the SDK's run context, whose
    code names more callables than the kernel reads in one walk (about 512), none of
    which it calls. Keep the decorator's own code to the wrappers it calls.
  - A decorator on a function that takes the SDK's run context that names, or calls, a
    `functools.wraps` helper which takes the context under the function's name for it
    and names the function's parameters after it. Give the helper `*args, **kwargs`
    alone, or do not name it with `functools.wraps`.

  - A method with a positional-only parameter after the object, under a decorator
    that takes the object by name and hands everything on, or under
    `functools.lru_cache` (the positional-only family). Make the parameter one a
    keyword can fill, or take the object in `*args` in the decorator.
  - A method decorator that hands everything on to the method and holds, or only names
    in its body, a `functools.wraps` helper that takes the object as `self` or names
    the method's parameters (the held-helper family). Give the helper `*args,
    **kwargs` alone, or do not name it with `functools.wraps`.
  - A function that takes the SDK's run context as `*ctx` (the context-place family).
    Take it as an ordinary first parameter.

- New in 0.2.7, beside `recusal` 0.18.2, by the kernel's rule L, which it asks for every
  framework that passes an argument ahead of the judged ones (0.2.6 beside `recusal`
  0.18.1 gated it, and it ran as judged):
  - A wrapper that restates the parameters of a function that takes the SDK's run
    context first, the context's place with them, and hands the context on (`def
    wrapper(ctx, table, limit=10): return fn(ctx, table, limit)`), over a function that
    gives a parameter after the context a default (the context-restating family). Give
    the wrapper `*args` and `**kwargs` alone.

  The same rules refuse members of those families that 0.2.5 gated and that did not
  run as judged: a restating method wrapper that drops the object, a held wrapper that
  drops the object, a held object that runs a parameter of its own, a wrapper with a
  parameter of its own bound as the argument of a named partial. The counts are above,
  under "Measured against 0.2.5".

**Open**, stated so you can judge them. Each is described under "What the gate does not
see" or above:

- **A held wrapper the kernel does not take for one.** Two kinds, both read whatever
  they take, as under 0.2.5. The first names nothing as `__wrapped__`: the kernel reads
  it by design, since every correct held wrapper written without `functools.wraps` has
  the same shape. The second is kept anywhere else than the decorator's closure or a
  module global its code names, where the kernel does not look, although it is named
  with `functools.wraps` (an attribute of an object in the closure, as the differential
  generates it with a `types.SimpleNamespace`). Either kind that names the method's
  parameters and drops the object (`def inner(self, table, limit=10): return fn(table,
  limit)`, called by `def outer(*args, **kwargs): return inner(*args, **kwargs)`, over
  `def purge(self, table: str, limit: int = 10)`) is gated, and it runs every judged
  value one place off: judged `{table: "t", limit: 5}`, it ran `self="t"`, `table=5`,
  `limit=10`. The first kind is the row `held-without-wraps` of the kernel's shared
  table, which `tests/test_reading_conformance_openai_agents.py` holds through both
  routes; both kinds are members of the held family, which the differential runs.
  Named with `functools.wraps` and held in the closure or in a module global the code
  names, the same held wrapper is refused since 0.2.6.
- **A partial that a pass-through holds.** `def outer(*args, **kwargs): return
  held(*args, **kwargs)` under `functools.wraps(f)`, where `held` is a
  `functools.partial` in the decorator's closure that is not named for the function: it
  is read whatever the partial binds, as under 0.2.5. A value it binds for a parameter
  of a helper is run and not judged: `functools.partial(helper, f, mode="x")`, over
  `def helper(fn, *args, mode="unsafe", **kwargs)`, runs `mode="x"`. A partial that a
  wrapper names as what it wraps is refused where it binds a value (the named-partial
  family above).
- **A partial that carries no `__wrapped__`.** The kernel's rule for a partial asks
  about one that carries `__wrapped__`. A partial that carries none, under a
  pass-through that names it or behind a wrapper that points its `__wrapped__` at it,
  is judged by the signature the partial shows, as under 0.2.5: the parameters it
  leaves are judged, and a value it binds by position is the application's and is run
  and not judged. A helper that names the function's parameters is trusted with its
  body, which can hand them on in other places. Refused among them: one whose signature
  shows `*args` or `**kwargs`, and one a method wrapper hands the object to besides a
  value bound by position. The differential generates these with the named-partial
  family.
- **A held object the kernel reads.** A held class-based wrapper named for a plain
  function with `functools.update_wrapper` whose `__call__` is a `staticmethod` or
  another callable object with a parameter of its own, over a plain function with no
  class-based decorator under it, no run context and no method: its parameters cannot
  be read from a code object, it is refused only where an argument goes in ahead of
  the judged ones or is bound on the way (the held-object family above), and here its
  own parameter runs at its default, which no policy judged.
- A held wrapper the kernel's walk does not find (one that names nothing as
  `__wrapped__`, one built on first use, one in a slot, a container, a settings object
  or a function's own attribute) is
  gated, and a parameter of its own runs at its default. The same holds for a
  single-dispatch function of another function that a wrapper holds or reaches through
  a helper, and for one a tool body calls: gated, and an implementation registered on it
  runs with its own defaults. The kernel states these as not found. A held wrapper that
  names nothing as `__wrapped__` and takes the object of a method under another name,
  and drops it, is gated and runs every judged value one place off; the kernel's entry
  for 0.17.1 states it as read by design, and
  `test_open_a_held_wrapper_without_wraps_that_takes_the_object_under_another_name`
  holds it.
- **A method decorator that forgets to pass the object on.** Over a method of an ordinary
  class, `@functools.wraps(m) def method(self, *args, **kwargs): return m(*args, **kwargs)`
  over `def run_sql(self, sql, force=False)`, as `Tools().run_sql`. It is gated, and every
  judged value runs one place off: the policy judged `sql="S"` and `force=True`, and the
  method ran with `self="S"`, `sql=True` and `force=False`. The same holds for a class
  method whose decorator takes the object as `cls`, and for a decorator that takes it in
  `*args` (`return m(*args[1:], **kwargs)`). Two forms this page stated here up to 0.2.5
  are refused since 0.2.6, each held by
  `test_closed_a_method_decorator_that_names_the_parameters_and_forgets_the_object`:
  a decorator that names the method's parameters and passes them on without the object
  (`def wrapper(self, sql, force=False): return m(sql, force)`, the restating family),
  and one that keeps the object and calls a held wrapper whose leading place has the
  method's name (`def second(self, sql="x", force=False)`). A decorator that takes the
  object under another name than the method has for it (`self` over a class method's
  `cls`) is refused since 0.2.4, by the kernel's walk of `recusal` 0.17.1. Where a
  restating wrapper drops the object over a method that gives no parameter a default,
  the tool is read and every call raises a `TypeError`, with nothing run. From the
  signature the
  gate cannot tell whether a method decorator passes the object on: one that does is
  the ordinary decorated method, and only the body differs. The mistake is in the
  application's decorator, and the same call misruns without the gate. Pass `self` on
  in the decorator (`return m(self, *args, **kwargs)`), or register the method without
  that decorator. Found by the confirmation review of 0.2.3, in 0.2.2 too; the kernel's
  entry for 0.17.1 states it under "Still read, by design", and
  `test_open_a_method_decorator_that_forgets_the_object` holds each form as gated and
  run one place off.
- **A decorator that forgets to pass the run context on, in its body.** The same two
  shapes over a function that takes the SDK's run context first: a pass-through whose
  body drops it (`@functools.wraps(fn) def w(*args, **kwargs): return fn(*args[1:],
  **kwargs)`), and a wraps pass-through that calls a held closure which takes the
  context and does not pass it on. Each is gated, and every judged value runs one place
  off: judged `{table: "t", limit: 5}`, it ran `ctx="t"`, `table=5`, `limit=10`. The
  signatures are those of a decorator that passes the context on, and only the body
  differs, so the kernel's rules, which read signatures and not bodies, cannot see it;
  0.2.5 and 0.2.6 read them too. Pass the context on in the decorator
  (`return fn(*args, **kwargs)`), or register the function without that decorator.
- A change a tool body makes to another tool's function is seen from the next model
  turn, not by the other calls of the same turn.
- A bounded `functools.lru_cache` named again over a callable that cannot be weakly
  referenced (an object with `__slots__`) is listed on every check, because the kernel
  cannot keep what it found: twice by the kernel's walk and, since 0.2.3, once by the
  gate's. On the review's machine a check of one with 400,000 entries took 52 ms, and 35 ms
  beside 0.2.2. Keeping the answer between checks would need a strong reference the
  kernel avoids on purpose.

**Help make it better.** Read the code, test this adapter against your own stack and tell
us what you find. Reviews, bug reports and pull requests are all welcome:
[how to contribute](https://github.com/philpaz/recusal/blob/main/CONTRIBUTING.md), [open issues](https://github.com/philpaz/recusal/issues).
Please report a security gap [privately](https://github.com/philpaz/recusal/security/advisories/new), not in a public
issue.

## Compatibility

This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
public names are the ones in `recusal_openai_agents.__all__`. When an SDK release changes
what the guardrail is handed, this package gets a release and the kernel does not.

A runnable offline demonstration, with the SDK's scripted model and no API key, is
[`examples/openai_agents_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_agents_gate.py)
and
[`examples/openai_agents_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_agents_audit.py).

## More

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map.svg">
    <img alt="One kernel, eight adapters. Each adapter package depends on recusal: recusal-crewai, recusal-google-adk, recusal-langchain, recusal-langgraph, recusal-openai, recusal-openai-agents, recusal-openai-agents-mcp and recusal-pydantic-ai. recusal-langchain also depends on recusal-langgraph, and recusal-openai-agents-mcp on recusal-openai-agents. The kernel depends on nothing." src="https://raw.githubusercontent.com/philpaz/recusal/main/assets/adapter-map-light.svg" width="880">
  </picture>
</p>

An arrow means "depends on". No arrow leaves the kernel, so a framework's breaking
change is answered by a release of that framework's adapter, not by a release of the
kernel.

- [Framework notes for the OpenAI Agents SDK](https://github.com/philpaz/recusal/blob/main/docs/FRAMEWORKS.md#openai-agents-sdk-function-tools):
  the detail behind this page.
- [All eight adapter packages](https://github.com/philpaz/recusal/tree/main/adapters) and
  [the kernel](https://github.com/philpaz/recusal), which has zero runtime dependencies.
- [Verifying a release](https://github.com/philpaz/recusal/blob/main/docs/VERIFY.md#adapter-packages):
  each release is built in CI, signed with Sigstore and published to PyPI by trusted
  publishing.
- [Changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md),
  [issues](https://github.com/philpaz/recusal/issues),
  [security policy](https://github.com/philpaz/recusal/blob/main/SECURITY.md) and
  [support](https://github.com/philpaz/recusal/blob/main/SUPPORT.md).

Licensed under Apache-2.0.
