Metadata-Version: 2.4
Name: recusal-openai
Version: 0.2.4
Summary: Recusal gate for the OpenAI API: judge every function call of a Responses or Chat Completions loop you own, 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
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,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<4,>=3.49.0
Requires-Dist: recusal<1,>=0.18.0
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

[![Website](https://img.shields.io/badge/website-recusal.io-2453c4)](https://recusal.io)
[![PyPI](https://img.shields.io/pypi/v/recusal-openai)](https://pypi.org/project/recusal-openai/)
[![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 a loop you own on the
[OpenAI API](https://platform.openai.com/docs/api-reference): every function call the
model proposes is judged by your policy before your code runs it, and a refused call
never runs. It covers the Responses API and Chat Completions with one decision function.

**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 OpenAI 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
```

Requires Python 3.10+ (the SDK's minimum), `recusal>=0.18.0` and `openai>=3.49.0`. It is
tested on every pull request against exactly `openai==3.49.0`, and weekly against the
newest release. The kernel floor is what checks a decorated tool: beside an older
kernel the package raises `ImportError` instead of gating without that check.

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

## Use

```python
from openai import OpenAI
from recusal import Finding
from recusal_openai import gate_function_calls


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 []


client = OpenAI()
response = client.responses.create(model=..., input=..., tools=...)
answers = gate_function_calls(response, {"run_sql": run_sql}, policy)
# pass ``answers`` as the next request's input
```

`gate_tool_calls(completion, tools, policy)` does the same for Chat Completions and
returns `role: "tool"` messages. A completion requested with `n > 1` carries alternative
messages, so pass `choice=<list position>`; without it the gate refuses the completion
before anything runs.

Each proposed call gets exactly one answer under its own id: the tool's result, or
Recusal's reason. A policy that raises refuses the call (fail closed). The gate always
fails closed: `fail_closed` is not a keyword it takes.

The gate calls your tools synchronously, so each tool is an ordinary function. An
`async def` tool and a generator function (one whose body has a `yield`) are refused with
a reason before the policy runs, so the policy is not consulted for them. The gate reads
how a tool is declared through a `functools.partial`, a `staticmethod`, a bound method
and `functools.lru_cache`. It does not look through a wrapper of your own,
`functools.wraps` included, because such a wrapper may await or consume what it wraps:
that tool is judged and called like any other.

What a tool returns is answered as its `str`, with two exceptions. If it returns a
coroutine, the answer says so and that the gate did not run the coroutine. If it returns
a generator or any other iterator (an async generator, `iter(...)`, `map(...)`, an open
file), the answer is `` Tool `name` ran and returned a generator, which this gate does
not consume: its result is not available `` (`an iterator` or `an async generator` for
the other kinds). The function's own body ran, with whatever side effects it has, so the
answer never says the tool did not run. Return a list or a string instead.

A tool that raises: by default the exception reaches your loop, as it always has. Calls
earlier in the turn have already run and their answers are lost with it; calls later in
the turn do not run. Pass `answer_tool_errors=True` to answer the failed call instead,
with `` Tool `name` raised <ExceptionClass> `` under its own id. The class named is the
exception's nearest built-in one (`TimeoutError`, `ValueError`, `Exception` at worst):
never the message, and never a class name your application or a library chose. The rest
of the turn is then judged and run as usual, **including the calls after the failed
one**, and the traceback goes to the `recusal_openai` logger (to stderr, if your
application configures no logging), not to the model.

The gate binds the decoded arguments to the tool's signature with its defaults applied,
judges that invocation, and calls the tool with exactly those arguments. A default the
model omitted is therefore judged at the value the function would use.

## Put every decision on the record

```python
from recusal.audit import AuditLog
from recusal_openai import audited_function_calls

log = AuditLog(path="decisions.jsonl")
answers = audited_function_calls(response, tools, policy, log)
```

`audited_tool_calls` is the Chat Completions form. Each call the model proposes, run or
refused, is one hash-chained entry labeled `openai.responses.function_call` or
`openai.chat_completions.tool_call` with the API's own call id and a SHA-256 fingerprint
of the arguments (never the arguments). The call id is on the entry exactly as the API
sent it, and is at most 256 characters (see call ids below). A refusal's reason on the
log never quotes an
argument's key or value: a call that does not bind names the parameters the tool declares
and counts the arguments it does not take. A tool you have is on the entry under the
name you gave it. A name you have no tool for is the model's text: it is on the entry,
and in the reason, as sent only if it is 1 to 64 printable characters with no backtick,
and otherwise as a description of its length, such as
`<a tool name of 1000000 characters, not shown>`. If the log cannot be written the call
is refused.
Check the log with `recusal audit verify decisions.jsonl`.

The audited functions call the plain ones, so there is one decision path:
`audited_function_calls(response, tools, policy, log)` is
`gate_function_calls(response, tools, policy, audit=log, surface="openai.responses.function_call")`,
and both forms take `actor=` and `control=` for the entry. Called directly, the plain
functions also take `allow_on_pass=True`, which records a passing call as `allow`
instead of `defer` and changes nothing about what runs.

A loop whose log is optional is one call to the plain function:

```python
from recusal_openai import SURFACE_RESPONSES, gate_function_calls

maybe_log = AuditLog(path="decisions.jsonl") if recording else None
answers = gate_function_calls(response, tools, policy, audit=maybe_log, surface=SURFACE_RESPONSES)
```

`audit=None`, passed explicitly, is the plain gate: nothing is recorded, and `surface=`,
`actor=` and `control=` are accepted and not used. When `audit=` is not passed at
all, `surface=`, `actor=` or `control=` with a value raises `TypeError` before anything
is judged, so a loop that believes it is recording is never silently not recording.
`audit=` with a log and no `surface=` raises the same way. The two audited functions
need a log: `audited_function_calls(response, tools, policy, None)` raises `TypeError`
and runs nothing, because a function named "audited" that recorded nothing would
mislead.

A `surface=` or `control=` the kernel would not record raises `ValueError` naming the
keyword, before any tool call is looked at, with a log and with `audit=None`: a surface
that is empty, starts or ends with a space, is not a string or is the reserved
`claude_code.pretooluse`, and a control that is not a dict. The rule is
`recusal.decide`'s own: the gate asks it and restates nothing. `tool_use_id=` and
`fail_closed=` are not taken and raise `TypeError`: each call is recorded under its own
call id, and the gate always fails closed.

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

- **Refused with a reason, never run.** Each of these is answered under the call's own
  id before the policy runs, and is one entry on the audit log in the audited loop:
  - *The arguments.* Arguments that are not a string (an empty string is a call with no
    arguments), not valid JSON, or not a JSON object. `NaN`, `Infinity` and `-Infinity`
    are not JSON and are refused. So are a number Python reads as infinity (`1e999`) and
    arguments nested more than 64 levels below the arguments object.
  - *A call that is not finished.* A Responses `function_call` item whose `status` is
    anything but `completed` (`in_progress`, `incomplete`); an item with no `status`
    passes. Every function call of a response whose own `status` is anything but
    `completed` (`incomplete`, `failed`, `cancelled`, `in_progress`, `queued`, a value
    a later SDK adds), the finished items in it included; a response with no `status`
    passes. Every tool call of a Chat Completions choice whose `finish_reason` is
    anything but `stop`,
    `tool_calls` or `function_call`: that is `length` (the message was cut off at the
    token limit), `content_filter` and a missing `finish_reason`. Request the turn again
    with a higher token limit instead of running a call that may have been cut off.
  - *A namespaced function call.* A Responses `function_call` item that carries a
    non-empty `namespace` is refused: namespaced calls are not supported. The tools you
    pass and the name the policy sees are bare names, so the gate could not tell two
    functions of the same name in different namespaces apart. Declare such functions
    without a namespace, under names that are unique.
  - *The tool.* A tool the application does not have (a name that is not a string is
    one), arguments that do not bind to the tool, an `async def` tool, a generator
    function, a `functools.lru_cache` tool handed a list or an object, and a tool whose
    signature cannot be judged by name: see the next point.
- **Which tools the gate can judge.** A tool is a plain function, a bound method or a
  `functools.lru_cache` of one, whose every parameter can be passed by name
  and is annotated with a supported data type: `str`, `int`, `float`, `bool`, `Optional`
  of a supported type (also written `T | None`), `list[T]`, and `dict[str, T]`, where
  `T` is a supported type in turn (`list[dict[str, int]]` is supported). Every default
  must be JSON data. A tool cached with `functools.lru_cache` (or `functools.cache`)
  needs arguments the cache can hash: a call that hands it a list or an object, for a
  `list[T]` or `dict[str, T]` parameter or in place of a `str`, is refused with a reason
  before the policy runs. Give a cached tool `str`, `int`, `float` and `bool` parameters
  only. A cache behind a wrapper of your own is not seen: there such a call raises
  `TypeError` as any tool that raises does (see `answer_tool_errors` above). Everything
  else is refused with a reason, among them:
  - a parameter with no annotation, `Any`, `Literal[...]`, a union of two types such as
    `int | float`, a bare `list` or `dict`, an `Enum`, `Annotated[...]`, a dataclass or a
    model;
  - variadic (`*args`, `**kwargs`) and positional-only parameters;
  - a `functools.partial` as it stands, which shows no annotations (the named-partial
    family, below, says which partials are read), and a callable object (an instance with
    `__call__`) unless
    its class annotates the names `__call__` takes (a dataclass whose fields are those
    names, for example), because the kernel reads annotations from the class;
  - a `functools.wraps` wrapper that adds a parameter of its own to the function it
    wraps, and one that takes `*args, **kwargs` and also names a parameter the function
    has: either would run with a value the policy never judged;
  - a decorated tool the kernel does not read to the end, or refuses by one of its
    rules for a wrapper: see below.

  Whether a call to a tool can be judged is the kernel's answer. Whatever it refuses,
  and any error raised while it reads the tool, refuses that one call before the policy
  runs, with the kernel's reason: what was found and what to write instead.

  What to do instead: write a plain function with supported annotations and resolve
  richer types inside its body. Take a `str` and check it against the allowed values in
  place of `Literal` or an `Enum`, pick `float` in place of `int | float`, write
  `dict[str, str]` in place of `dict`, and replace a `functools.partial` or a callable
  object with a plain function that does its work in its own body. The annotations
  decide only whether the gate can judge the tool: the gate binds arguments by name and
  does not check or convert a value's type.
- **The tool's name in a refusal.** A refusal names a tool you have by the name you
  gave it. A name you have no tool for is quoted only if it is 1 to 64 printable
  characters with no backtick. Any other (longer, empty, or holding a backtick, a
  newline, a control or formatting character or a lone surrogate) is described by its
  length, in the answer and on the audit log, as
  `<a tool name of 70 characters, not shown>`, and a name that is not a string as
  `<a tool name that is not a string>`. So a tool name cannot close the backticks a
  refusal sets it in, start a new line, or put more than 64 characters of the model's
  text into an answer or an entry.
- **Call ids.** A call id is the model's text too, and it has to go back exactly as
  sent: in the answer, which is how the API matches it to the call, and on the audit
  entry, which is how the entry is tied to the call. So the gate does not shorten or
  describe it there. It takes a call id of at most 256 characters instead: a longer
  one raises `ValueError` before anything in the turn runs, and writes no entry. That
  bounds what one id can add to an answer or an entry at 256 characters. An id may
  hold any character; on the log it is JSON-escaped, so it cannot start a line. A
  message the gate raises (a duplicate id) quotes an id only if it is printable with
  no backtick, names at most four, and otherwise describes each by its length, as
  `<a call id of 17 characters, not shown>`.
- **Refused by raising, before anything in the turn runs:** an output item or tool call
  of a type the gate does not handle (`custom_tool_call`, the provider's record of a
  hosted tool call, a type a later SDK adds), a Chat Completions message that carries
  the legacy `function_call` field (alone or beside `tool_calls`; the gate reads
  `tool_calls` only, so declare functions with `tools`, not `functions`), a call without
  an id, a call id of more than 256 characters, a duplicate id, and a keyword argument
  the gate does not take (`TypeError` naming it, whether or not the turn has calls): a
  mistyped one, `fail_closed`, `tool_use_id`, `surface`, `actor` or `control` with a
  value when `audit` is not passed at all, and `audit` with a log and no `surface`. A
  `surface` or `control` the kernel would not record raises `ValueError` naming it. A
  turn refused this way writes no audit entry.
- **Not seen: what a wrapper does in its own body.** The gate reads signatures, not
  code. A `functools.wraps` wrapper that restates the function's parameters exactly
  (below) is judged by them, and if its body then does not pass one on, or passes them on in other places,
  the function runs with values the policy did not judge:

  ```python
  def logged(fn):
      @functools.wraps(fn)
      def wrapper(path: str, dry_run: bool = False):
          return fn(path)  # dry_run is not passed on

      return wrapper


  @logged
  def delete_tree(path: str, dry_run: bool = False) -> str: ...
  ```

  A call with `dry_run=true` is judged with `dry_run` true and `delete_tree` runs with
  `dry_run` false. No check of a signature can see this. Give the gate the function
  itself, or a wrapper that passes on every parameter it names. On a method, where the
  object goes in by position, a wrapper that names parameters is refused by a rule of
  the kernel's wherever the method gives a parameter a default (below), since a body
  that kept the object could then run without failing; the body itself is read there
  no more than here.
- **A decorated tool: the reading is the kernel's alone.** Whether a call to a tool can
  be judged is the kernel's answer, and since 0.2.4 all of it is: the gate asks
  `recusal.invocation.judged_parameters` the way it calls a tool itself (every judged
  value by keyword, nothing by position ahead of them, no name left out, and every
  parameter of the tool's own asked by name first), completes the call from the
  parameters and defaults that gives, and passes on the kernel's reason for a refusal
  (`refusal_reason`), whole and alone: what was found, what to write instead, and why a
  plain function that calls the refused one does not remove the cause. The gate holds
  no rule and no reason of its own for a decorated tool. It reads no signature: the
  parameters and defaults it completes a call from are the ones the kernel hands it.
  0.2.3 held one rule (a method's object past a wrapper that names a positional
  parameter), its own completion of defaults (`inspect.signature(...).bind`) and a
  reason for each class of refusal. Two things the gate still reads of a tool itself,
  neither about what a call runs with and both for its own synchronous call: whether
  the tool is declared `async def` or as a generator function, read through a
  `functools.partial`, a `staticmethod`, a bound method and `functools.lru_cache`, and,
  for a callable object, on the `__call__` of its class; and
  whether it is a `functools.lru_cache`, read through a `staticmethod` and a bound
  method. Neither is read through a wrapper of your own. Where the tool's own code raises
  while either is asked (a callable object that answers for any attribute with a
  `__getattr__` that raises, or shows its class through a property that does), that one
  call is refused, and no word of what was raised
  is passed on. Seven refusals for a tool are
  worded by this gate and not by the kernel, since each is about this gate's own call
  or about the model's arguments and not about what a call reaches: "it is declared
  async, and this gate calls tools synchronously", "it is a generator function, and
  calling it would run none of its body", "it is cached with `functools.lru_cache`,
  which cannot take a list or an object as an argument", "arguments do not bind to the
  tool (...)" (which names a required parameter that is missing and counts the
  arguments the tool does not take), "the invocation cannot be copied as JSON
  data for the policy", "unknown tool" and "how it is declared (async, a generator
  function, a cache) cannot be read: the tool's own code raised while it was asked". The kernel reads every callable a call reaches and
  refuses what it cannot follow to the end. Refused:
  - a decorator that holds a second wrapper of the function (in its closure, in a module
    global it names, or on the decorator object) and calls it, where the held wrapper has
    a parameter of its own, takes the tool's parameters in other places, takes the object
    of a method under another name than the function it wraps has for that place, names
    a chain of `__wrapped__` that comes back on itself, or reaches the function through a
    single-dispatch function, a weak proxy or a cache named again;
  - a `functools.lru_cache` named again for another function, whose function cannot be
    told from what the cache refers to;
  - a `functools.singledispatch` function or `singledispatchmethod` on the way, with an
    implementation registered, or with nothing registered but its base (one can be
    registered between the check and the call);
  - a `functools.partialmethod` over a callable object or a class-based decorator;
  - a wrapper handed a bound argument (the object of a method, a positional argument of
    a `functools.partial`) that takes it under another name than the function it wraps
    has for that place, or passes a value of its own there: its signature does not show
    whether it hands the argument on;
  - a declared signature, also where it matches the real parameters: a `__signature__`,
    a `__text_signature__` that is not the interpreter's own, or a callable object that
    shows a `__code__` and names nothing as `__wrapped__`;
  - a `weakref.proxy` anywhere on the way;
  - a callable that answers for `__wrapped__` without holding one (a class-based
    decorator that hands every attribute on with `__getattr__`), or that shows another
    class than its own and has a `__call__` of its own that takes a parameter by name;
  - a class-based decorator that is also a descriptor (its class defines `__get__`);
  - more wrappers than the walk reads;
  - a `functools.partial` as the tool where it shows no annotations, as one shows none
    as it stands, and a tool whose annotations `typing.get_type_hints` cannot resolve;
  - by rules the kernel asks for every framework since `recusal` 0.18.0 (`judge_tool`,
    which the walk alone does not ask), five families of decorators, each stated here
    once, as a family, and not shape by shape. Each family was generated in full, every
    combination of the choices a member has, and every member put to this gate and to
    0.2.3 (Measured against 0.2.3, below): a member that is not as its sentence here
    says fails `tools/differential/openai.py`.
    - **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 (keyword-only where the function's is, and not where it is not), and gives
      none a default the function does not give it (the function's own default, or
      none). Every other is refused, whatever its body does: one that takes the
      parameters in another order, takes one under another kind, gives one a default
      that is not the function's own or leaves one out. Over a method, where it takes
      the object first, it is read only where, besides, the method gives no parameter a
      default: where one has a default, a body that kept the object could pass the
      values on one place off without the call failing. Give the wrapper `*args` and
      `**kwargs` alone, after the object on a method, and hand them on (`def
      wrapper(self, *args, **kwargs): return fn(self, *args, **kwargs)`), which is read.
    - **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` does, and so does the attribute set by hand),
      takes the object by name, under the method's own name for it 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. 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.
    - **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 is
      bound on the way: on a method, and on a plain function with a class-based
      decorator in the same stack, above it or under it. Its parameters cannot be read
      from a code object there, so whether it takes the place of the bound 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 that holds in its closure cells, or
      whose code names, many callables, the ones it never calls too (generated here
      as names in its code; a list of callables in one closure cell is one value, and
      the kernel does not look inside it). Where an argument is bound on the way
      (the decorator is on a method, or stands under a class-based decorator, which
      binds itself), the kernel looks at what the callables on the way hold, stops at
      about 512 callables in one walk, counting the ones the walk stands on, 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 (300, 700 and
      2,000 here). Keep a method 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 is the tool
      or that a wrapper on the way names as what it wraps. Where it binds nothing it is
      read as what it is of is read (generated here: a plain function and a bound
      method, `functools.wraps(m)(functools.partial(m))`). One that binds a value, by position
      (`functools.wraps(f)(functools.partial(helper, f))`, the partial of a helper,
      which 0.2.3 read to the end) or by keyword
      (`functools.wraps(f)(functools.partial(f, limit=7))`), 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. A partial as it stands is refused as
      well, for another reason: it shows no annotations, so its parameters cannot be
      judged by name (and one of a helper that takes `*args` shows those). Three kinds
      of partial are outside the rule and are read (Open): one that a pass-through holds
      in its closure and does not name; one that was given annotations by hand and
      carries no `__wrapped__`; and one that a wrapper carrying the function's
      annotations points its `__wrapped__` at. Of a held partial that is itself named
      for the function this page makes no statement: some forms are read and some
      refused.

  Read to the end, so that a wrapper with a parameter of its own is refused, naming the
  parameter, and one that only passes its arguments on is accepted: `functools.wraps`
  wrappers and `functools.lru_cache` applied directly, `@functools.wraps(f)` written above
  `@functools.lru_cache`, and a class-based decorator built with
  `functools.update_wrapper` (on a method, a class-based decorator with no `__get__` and
  a `functools.partial` do not bind the object, and its `self` is refused as not
  annotated). No reason advises calling the refused function from a plain function and
  registering that one: the gate reads a plain function's parameters and never its body,
  so the cause would run inside it as before. Every reason ends by saying so.
- **How a tool is called on this path, and what that means for a shifted call.** The
  SDK runs nothing here. A function call reaches your loop as data, its arguments one
  JSON text: `ResponseFunctionToolCall.arguments: str`
  (`openai/types/responses/response_function_tool_call.py` in `openai` 3.49.0) and
  `Function.arguments: str`
  (`openai/types/chat/chat_completion_message_function_tool_call.py`). The gate decodes
  the text, completes it from the parameters the kernel gives, and calls the tool
  itself, `func(**invocation)` (`_judge` in `_gate.py`), the one call of a tool in the
  package: every judged value is passed by keyword, a default the model left out
  included, and nothing the gate passes goes in by position. The only values that go in
  by position are the ones a callable on the way binds itself: the object of a bound
  method (`self`, or `cls` for a class method) and the positional arguments of a
  `functools.partial`. So what the gate tells the kernel is how it calls: by keyword,
  no argument ahead of the judged ones, no name left out. The tools of
  [`examples/openai_responses_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_gate.py)
  are plain functions, called the same way.

  Every judged default is passed into the call, a `None` default too, as the object the
  function declares: what the policy saw is, name for name, what is passed, and nothing
  is left for a callable on the way to fill. 0.2.3 passed every default as well
  (`bound.apply_defaults()` in its `_judge`), so this is unchanged, and so is what it
  costs: a wrapper whose body asks whether a parameter was left out (`if "limit" in
  kwargs`) always finds it, and a function that validates what it is passed validates a
  default it would not validate if it were left out (behind `pydantic.validate_call`,
  `region: str = None` is passed `None`, and the call raises a `ValidationError` after
  the policy allowed it; declare it `Optional[str]`). No other callable receives the
  arguments: the policy is handed a detached copy, and an audit entry holds a
  fingerprint.

  Where the kernel refuses a wrapper that
  may keep a bound argument because a call by keyword would then fail and a call by
  position would run each judged value one place off, a call this gate makes would fail
  with a `TypeError`, and nothing would run: under this gate such a tool, refused, either
  runs correctly or fails. Such a `TypeError` leaves the gate as any tool's exception
  does (see `answer_tool_errors` above). The kernel's reason for a bound argument can
  advise taking the argument under the name the function has for it and passing it on by
  position. Where another wrapper on the way keeps the object (a method decorator that
  does not pass `self` on), the tool written that way is gated and does not run as
  judged, and the reason says so itself, for a call by keyword: it raises a `TypeError`.

  The SDK also ships a runner of its own that calls registered functions itself
  (`ResponsesToolRunner` in `openai/lib/responses_tool_runner.py`, which calls a
  registered function's `execute` with the decoded arguments as one dict). That is
  another path, and this gate is not on it: it is for a loop you own.
- **A method decorator that names the method's parameters.** `def wrapper(self, table,
  limit=10): return fn(table, limit)` under `functools.wraps(fn)`, over `def purge(self,
  table: str, limit: int = 10)`, passes the values on without the object. This gate
  calls the method by keyword, the object goes in by position, and the body passes the
  values on by position: judged `{table: "t", limit: 5}`, it ran `self="t"`, `table=5`,
  `limit=10` under 0.2.2. Nothing in the wrapper's signature tells it from one that
  hands the object on, so both are refused: by a rule of this gate's own in 0.2.3, and
  since 0.2.4 by the kernel's (the restating family above, on a method, and under a
  `functools.lru_cache`, a cache named again, on a class method and behind a facade
  that passes everything on). Where the method gives no parameter a default, the stack
  is read, and a body that drops the object makes the call raise a `TypeError`, with
  nothing run. Give the wrapper only `*args` and `**kwargs` after the object and hand
  them on with it, or register the method without the decorator.
- **No state between turns.** Within one turn a duplicate or empty call id raises. The
  gate remembers nothing from one turn to the next, so a call id used again in a later
  turn is not detected: each turn is judged, answered and recorded on its own.
- **No helper for streaming.** The gate takes a complete `Response` or `ChatCompletion`.
  An application that streams must assemble the complete response first (the SDK's
  stream helpers return it once the stream ends: `get_final_response()` for Responses,
  `get_final_completion()` for Chat Completions), then hand it to the gate, and must not
  run a function call from a stream event.
- **Never judged: hosted tools.** Web search, file search, code interpreter, image
  generation and remote MCP run on the provider's side. What arrives in your loop is the
  provider's record of the call (`web_search_call`, `mcp_call` and the others in
  `HOSTED_RECORD_TYPES`, which also holds `compaction`, the provider's summary of earlier
  context). By default such an item raises like any other unhandled one. Pass
  `allow_hosted_records=True` to let finished records through: they are not judged, not
  answered and not on the audit log, and the function calls beside them are judged as
  usual. A record whose `status` says it is still in progress raises either way.
- **Not gated yet: remote MCP approvals.** A remote MCP server set to require approval
  sends an `mcp_approval_request` for your loop to answer. This gate does not judge it:
  it raises, with or without `allow_hosted_records`, so the call is never approved
  through this gate.
- **Not read: `async` and `caller`.** A Responses `function_call` item can be marked
  `async` and can carry a `caller` of type `program`. The gate reads neither field: such
  a call is judged by your policy and run like any other.
- **After the decision.** An audit entry records the gate's decision, not what the tool
  then did. A call the gate allowed whose tool raised, returned a coroutine that nothing
  ran, or returned an iterator the gate did not consume, is on the log as allowed. The
  async and generator checks read how a tool is declared; a wrapper of your own that
  hides an `async def` or a generator function behind an ordinary function is caught
  only by what it returns, after the policy has allowed the call and the wrapper has
  been called.

**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 of these runs
correctly when called by keyword, as this gate calls it, and beside `recusal` 0.18.0
this gate refuses each, before the policy is asked and before anything runs. 0.2.2
beside `recusal` 0.15.1 gated each of the parts up to 0.2.3's, and 0.2.3 beside
`recusal` 0.18.0 gated each of the last part. Each was run through this gate, and so
was each remedy below.

- New with `recusal` 0.16.0:
  - A class-based decorator that keeps the function in an attribute and answers every
    other attribute from it with `__getattr__`, over a plain function, which then shows
    its `__code__`. Call `functools.update_wrapper(self, fn)` in its `__init__`.
  - A single-dispatch function that is called with its first argument by position, as a
    method's object goes in, or every value a wrapper that restates the parameters passes
    on in order, with implementations registered only for other types than that
    argument's: it always runs its base. Register the method, or the function, without the
    single-dispatch function.
  - A `__text_signature__` that matches the parameters, under a decorator written as
    `functools.wraps(f)(functools.partial(helper, f))` (without that decorator, 0.2.2
    refused it too). Delete it, and write the decorator's wrapper as a function of its
    own (the last part of this list): since 0.2.4 that decorator is refused as well.
  - A facade method that hands its object on to a function that names that place
    otherwise (`return execute(self, *args, **kwargs)` under `functools.wraps(execute)`,
    over `def execute(database="main", sql: str = "SELECT 1", note: str = "")`), or
    passes a value of its own there (`return search(self.tenant, *args, **kwargs)` over
    `def search(tenant: str = "main", limit: int = 10)`), where that parameter has a
    default. Register the function itself, or write the method out, its parameters passed
    on to the function by keyword.
- New with `recusal` 0.17.0:
  - A `weakref.proxy` of a plain function under a decorator that hands its arguments on.
    Put the function in the proxy's place.
  - A decorator that holds a `weakref.proxy` of a helper that hands its arguments on.
    Hold the helper itself.
  - The same single-dispatch function with nothing ever registered on it. Register the
    method, or the function, without the single-dispatch function.
  - A class-based decorator that answers every other attribute 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__`.
  - An object that shows another class than its own and holds a `__wrapped__` (the shape
    of a `wrapt` proxy), whose own `__call__` names the parameters and hands each on in
    order. Give its `__call__` only `*args` and `**kwargs`, handing them all on.
  - A decorator that holds a wrapper which takes the tool's parameters in another order
    and hands them on by keyword: this gate's call by keyword reaches each by name (0.16.0
    refuses it already under a wrapper that restates the tool's parameters). Give the
    held wrapper the tool's parameters in the tool's order, or as keyword-only ones.
- New with `recusal` 0.17.1:
  - 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 `self` over a class method's `cls`). Take
    the object under the name the method has for it (`self`, or `cls` for a class
    method) 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.
  - A held helper whose chain of `__wrapped__` comes back on itself
    (`helper.__wrapped__ = helper`). Name the function it wraps, once.
  - The two facades under 0.16.0 where that parameter has no default (`def
    execute(database, sql: str = "SELECT 1", note: str = "")`, `def search(tenant: str,
    limit: int = 10)`). Register the function itself, or write the method out.
- New with this package's 0.2.3, by a rule of the gate's own then, which is the
  kernel's since 0.2.4 (above): 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)`), on a method, a
  class method or a facade; a method decorator that takes the method's parameters as
  another kind and hands the object on (`def wrapper(self, *, account, amount=7,
  memo="m0"): return fn(self, account=account, amount=amount, memo=memo)` over a method
  that takes them by position); and a method decorator that takes the object as `self`
  and hands it on, above two or more class-based decorators or decorators written as
  `functools.wraps(f)(functools.partial(helper, f))`, since the rule counts each value
  such a callable binds as one that could move into the object's place. Give the wrapper
  only `*args` and `**kwargs` and hand every argument on, or register the method without
  the decorator.
- New with this package's 0.2.3, by the same rule's reading of the method's function on
  its own: a decorator that holds a second method wrapper and hands the object on to it
  (`def outer(self, *args, **kwargs): return inner(self, *args, **kwargs)` holding `def
  inner(self, *args, **kwargs)`, or holding a keyword-only wrapper that hands the object
  on), on a method or a class method. The kernel's walk reads the bound method; read on
  its own, the held wrapper's `self` is refused. Take the object in `*args` in the held
  wrapper (`def inner(*args, **kwargs): return fn(*args, **kwargs)`).
- New with `recusal` 0.16.0, missed above: a class-based decorator that binds as a method
  (its class defines `__get__`) under `functools.wraps(f)(functools.partial(helper, f))`
  applied to it, whose name the partial now carries to it. Give its class no `__get__`,
  and write the decorator's wrapper as a function of its own (the last part of this
  list).

Refused too, and changing nothing that runs, since this gate's call fails there either
way: such a wrapper that drops the object where the place it leaves has no default (`def
method(self, *args, **kwargs): return execute(*args, **kwargs)` over `def
execute(database: str, ...)`, and a held `def forward(receiver, *args, **kwargs): return
run(*args, **kwargs)` under `functools.wraps`). 0.2.2 beside `recusal` 0.15.1 gated
both, and the call raised `TypeError`. The kernel's entries for 0.16.0, 0.17.0 and 0.17.1
in the changelog have the whole lists for its walk.

- New in 0.2.4, beside `recusal` 0.18.0, each by a rule the kernel asks for every
  framework (0.2.3 beside the same kernel gated each, and it ran as judged). They are
  the members of the five families above that run correctly:
  - A restating wrapper over a plain function that hands every value on, and takes the
    function's parameters in another order (`def w(limit, sql): return fetch(sql=sql,
    limit=limit)`), takes one under another kind (`def w(sql="", *, limit=10): return
    fetch(sql, limit)` over `def fetch(sql: str = "", limit: int = 10)`), or gives one a
    default that is not the function's own (`def w(sql="", limit=99)`: this gate passes
    every judged default, so the wrapper's own never applied). Give the wrapper the
    function's own order, kinds and defaults, or only `*args` and `**kwargs`.
  - A held `functools.wraps` wrapper that takes the object under the method's own name,
    names the method's parameters and hands the object on (`def inner(self, table,
    limit=10): return fn(self, table, limit)`), called by `def outer(*args, **kwargs)`.
    Give the held wrapper `*args` and `**kwargs` alone (`def inner(*args, **kwargs):
    return fn(*args, **kwargs)`).
  - 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,
    or on a plain function with a class-based decorator in the same stack. Write its
    `__call__` as a method.
  - A named partial that binds a value: the partial of a helper
    (`functools.wraps(f)(functools.partial(helper, f))`), and a partial that binds a
    parameter of the tool by keyword (`functools.wraps(f)(functools.partial(f,
    limit=7))`, for which 0.2.3 judged and passed `limit` at the function's own default
    or the model's value, so the partial's never applied). Write the decorator's wrapper
    as a function of its own.
  - A method decorator, or a decorator under a class-based one, 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.

  The same rules refuse members of those families that 0.2.3 gated and that did not
  run as judged: a restating wrapper whose body passes the values on in its own order,
  a held wrapper that drops the object, a held object that runs a parameter of its
  own. The counts are below.

  **Measured against 0.2.3.** `python tools/differential/openai.py --summary` puts the
  same calls to the gate as released (read out of git at the tag
  `recusal-openai-v0.2.3`) and to this one, both beside `recusal` 0.18.0 and `openai`
  3.49.0, each on a fresh tool, through the real entry points and under a policy that
  allows every call, so that each comparison has what was judged and what the tool then
  ran: the 55 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), 3,580 calls of the
  five families above (1,224 of the restating wrappers, 1,386 of the held wrappers, 240
  of the held objects, 18 of the held counts and 712 of the named partials), and every
  call the adapter's own test files make to the gate. The table, the stacks and the
  families are compared twice, through `gate_function_calls` and through
  `gate_tool_calls`, and every count is the same through both. Of the 2,550 calls of
  the test files, 1,206 are not compared: 1,194 are made by one test whose tool counts
  the questions it is asked, so asking the released gate first would change what it
  sees, and 12 are calls for which the released gate raises. The OpenAI SDK has no
  setting that changes how arguments reach a tool on this path (it hands them over as
  one text), so there is none to compare both ways. In no set is a call that 0.2.3
  refused read by 0.2.4, 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 do anything
  else than it does called with no gate, by keyword, with exactly the arguments the
  policy judged. And no call is newly refused for a cause this page does not list. 0.2.4
  newly refuses 10 rows of the table (6 ran as judged, 1 raised and 3 ran a value no
  policy judged under 0.2.3), 7,720 of the generated calls (1,832 ran as judged, 3,194
  raised and 2,694 ran a value no policy judged) and 776 of the calls of the families
  (374 ran as judged, 324 raised and 78 ran a value no policy judged). Read by both: 14
  rows, 3,464 generated calls and 1,210 calls of the families. (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.3 either; the ones that ran a value no policy
  judged are what the move closes.) `--list` prints each.
  `tests/test_differential_openai.py` runs the short form of it, the table, the stacks
  of one and two decorators and every member of the five families, through both entry
  points, in the OpenAI API 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, no function among them
  validates its own arguments, no wrapper among them tells a parameter left out from one
  that was passed, and the test files' calls are compared for the verdict alone.

**Open**, stated so you can judge them. A test named `test_open_` holds each, or the
row of the kernel's shared table that the item names.

- **A method decorator that forgets to pass the object on.**
  `@functools.wraps(m) def method(self, *args, **kwargs): return m(*args, **kwargs)` over
  `def run_sql(self, sql: str, force: bool = False)`, and the same where the decorator
  takes the object in `*args` (`return m(*args[1:], **kwargs)`) or sits under
  `classmethod`. It is gated, and the policy judges the call; this gate calls it by
  keyword, so the method is missing its object, the call raises a `TypeError` out of the
  gate (or is answered as a tool that raised, with `answer_tool_errors=True`), and none
  of it runs. Called by position, as a loop of your own might call it, it would run every
  judged value one place off. From the signature nothing tells it from the ordinary
  decorated method, which the kernel's entry for 0.17.1 states under "Still read, by
  design". So is a wrapper of the method's kinds that drops the object over parameters
  with no default (above, the restating family on a method): gated, and the call raises
  a `TypeError`. Pass `self` on in the decorator.
- **A held wrapper the kernel does not take for one.** Two kinds, both read whatever
  they take. 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`: in an attribute of an object in the closure (a
  `types.SimpleNamespace`, which the differential generates; the review of this change
  found the same for an instance or class attribute, a dict, a tuple, a function's
  attribute, a module's attribute and a `functools.partial` in the closure). 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`, under 0.2.3 as under 0.2.4. The first kind
  is the row `held-without-wraps` of the kernel's shared table, which
  `tests/test_reading_conformance_openai.py` holds through both entry points; 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.4 (the held family above); 0.2.3 gated it and
  stated it here. One that takes the object under another name and drops it (`def
  forward(receiver, *args, **kwargs): return run(*args, **kwargs)`, called by a
  `functools.wraps` pass-through, and naming nothing as `__wrapped__`) is gated, and
  this gate's call raises a `TypeError` (over a facade whose first parameter has a
  default, that parameter runs at its default). Pass the object on in the held wrapper,
  or give it only `*args` and `**kwargs`.
- **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, over a plain function, a method's function and a
  bound method, as under 0.2.3. 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"`. The gate reads signatures, and a held
  partial shows none of what it binds. A partial that is the tool, or 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__` and shows annotations.** The kernel's rule
  for a partial asks about one that carries `__wrapped__`. A partial given the
  function's annotations by hand (`p = functools.partial(f, "bound"); p.__annotations__
  = dict(f.__annotations__)`), as the tool or under a pass-through that names it, and a
  partial that a wrapper points its `__wrapped__` at after `functools.update_wrapper(w,
  f)` (`w.__wrapped__ = functools.partial(f, "bound")`), are judged by the signature the
  partial shows, under 0.2.3 as under 0.2.4. The parameters it leaves are judged, and a
  value it binds by keyword is the default the policy sees. A value it binds by position
  is the application's and is run and not judged: judged `{limit: 5}`, it ran
  `table="t"`, the bound value, beside it. A helper that names the function's
  parameters is trusted with its body: `functools.partial(swap, f)` over `def swap(fn,
  table: str, limit: int = 10): return fn(limit, table)` is read, and runs each value in
  the other's place. 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.
- **The same, where the place the object leaves has a default.** A facade that drops its
  object in `*args` over `def execute(database: str = "main", sql: str = "SELECT 1",
  note: str = "")` is gated, and called by keyword `database` runs at its default, which
  no policy judged; the judged values run in their places. Hand the object on, or
  register the function itself.
- **A held wrapper the kernel's walk does not find.** One that names nothing as
  `__wrapped__`, with a parameter of its own, runs that parameter at its default, which
  no policy judged. So does a held object (a 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 in the stack: its parameters cannot be read from a code object,
  and it is refused only where an argument is bound on the way (the held-object family
  above). The kernel's entry for 0.17.0 lists the other held wrappers its walk
  does not find (one built on first use, one in a slot, a container, a settings object or
  a function's own attribute, one behind a `weakref.ref`).

**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 complete.** Its fixes are released in 0.2.3. 0.2.4, which moves the
reading of a decorated tool to the kernel, came after that review and has not been
through one. 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).

**What 0.2.4 changes.** It requires `recusal` 0.18.0 (0.2.3 allowed 0.17.1), and the
reading of a decorated tool is the kernel's alone: the gate asks `judged_parameters` by
keyword, as it calls a tool, and passes on `refusal_reason`. The rule 0.2.3 had of its
own (a method's object past a wrapper that names a positional parameter), its own
binding of the arguments to the tool's signature and its own reason for each class of
refusal are gone from this package; the kernel asks that rule, and more, for every
framework. So the words of every refusal for a decorated tool change (they are the
kernel's, which say what was found and what to write instead), and more tools are
refused: five families of decorators, stated above, with the members of each that run
correctly, what to write instead, and what was measured against 0.2.3. One shape 0.2.3
stated as open is refused now: a held `functools.wraps` wrapper that takes the object
as `self`, names the method's parameters and drops the object, under a pass-through,
which ran every judged value one place off, where the decorator holds it in its
closure or in a module global its code names; kept anywhere else it is read as
before (Open). How a default reaches the tool is
unchanged: every judged default is passed into the call, as under 0.2.3. It is not a
new review round.

**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.

## How it was tested

The in-depth review was four review rounds against `openai==3.49.0`, and it is the
project's own work. The threat model: the model is untrusted, and it chooses every tool
name, argument, call id, item type and status the gate reads. The application's own
code (its tools, its policy, the keywords it passes) is trusted but ordinary, so the
review also asked what an ordinary mistake in it does to the gate.

Each number below is printed by the command after it, from a clone with
`requirements/adapter-openai.txt` installed, with no API key and no network:

- **A generated corpus, through both loops.** 44,148 turns a model could send (258
  single forms, and a grid of 43,890 crossing tool names, forms of the arguments, and
  status, namespace and `finish_reason` values), each run through the plain and the
  audited loop from the same input. Counted: turns where the two loops disagree on what
  ran, where a tool ran under a name the application does not have, or where the audit
  entries are not one per call. None. `python tools/review/openai/corpus.py --summary`
- **A keyword matrix.** 35,280 combinations of the recording keywords through
  `gate_function_calls`, `gate_tool_calls` and `judge_and_run`. Counted: combinations
  that raised after a tool had run, recorded a call they refused, or answered without
  running a tool the policy allowed. None.
  `python tools/review/openai/keyword_matrix.py --summary`
- **Mutation testing.** 160 hand-written mutations, each switching off one check in a
  copy of the package. A mutation is caught when at least one of the package's tests
  then fails. All 160 are caught. `python tools/review/openai/mutate.py --summary`
- **Probes written against the pinned SDK**, among them tools decorated the ways
  applications decorate them. What a probe found is kept as a test.

What each round found. The findings of rounds one to three are fixed in 0.2.2, are in
the [changelog](https://github.com/philpaz/recusal/blob/main/CHANGELOG.md), and are each
pinned by the test named, in
[`tests/test_openai_responses_gate.py`](https://github.com/philpaz/recusal/blob/main/tests/test_openai_responses_gate.py):

- Round one: the plain loop ran a call the audited loop refused, `{"amount": NaN}` past
  a policy written as `amount > 100`
  (`test_a_number_that_is_not_json_or_not_finite_is_refused_before_the_policy`).
- Round two: a recording keyword without an audit log refused every call as a policy
  error, though no policy had run (`test_no_audit_log_is_the_plain_gate`).
- Round three: the package still allowed a kernel without the check of a decorated
  tool's wrappers (`test_the_package_requires_the_kernel_that_walks_every_callable`),
  and a `surface=` the kernel does not record refused every call with no audit entry
  (`test_a_recording_value_decide_would_refuse_raises_naming_the_keyword`).
- Round four: no changelog item. Its tests pin `judge_and_run` called directly and the
  error raised when the stack runs out during the keyword check
  (`test_judge_and_run_called_directly_answers_a_tool_error_only_when_asked`,
  `test_a_stack_that_runs_out_while_a_recording_value_is_checked_is_not_the_values_fault`).

What this does not show: a large number of generated cases is not a proof. The corpus is
the inputs the review thought of, the mutations are a hand-written list, and the numbers
are for one SDK version. Recusal is a Beta project, not a finished or certified security
product. The results are for the code as it stands: a test reruns a part of each where
the SDK is installed, and the full runs are the commands above.
[What the gate refuses, and what it does not see](https://github.com/philpaz/recusal/blob/main/adapters/openai/README.md#what-the-gate-refuses-and-what-it-does-not-see)
lists what stays outside the gate whatever the tests say, and
[What a review consisted of](https://github.com/philpaz/recusal/blob/main/docs/REVIEW.md#recusal-openai)
has the method in full, the other findings of each round and what each script checks.

## Compatibility

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

A runnable offline demonstration, with SDK-validated responses and no API key, is
[`examples/openai_responses_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_gate.py)
and
[`examples/openai_responses_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/openai_responses_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 API](https://github.com/philpaz/recusal/blob/main/docs/FRAMEWORKS.md#openai-api-your-own-loop):
  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.
