recusal-langgraph 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .venv/
12
+ venv/
13
+ env/
14
+
15
+ # Secrets, never commit
16
+ .env
17
+ .env.*
18
+ *.key
19
+ *.pem
20
+ *.p12
21
+ *service-account*.json
22
+ secrets/
23
+
24
+ # OS / IDE
25
+ .DS_Store
26
+ Thumbs.db
27
+ .vscode/
28
+ .idea/
29
+
30
+ # Local hook activation, the repo ships .claude/settings.json.example only;
31
+ # copying it to settings.json is a deliberate per-clone step, never committed
32
+ .claude/settings.json
33
+ .claude/settings.local.json
34
+
35
+ # Local working docs, not part of the published project
36
+ linkedin.md
37
+ NOTES.md
38
+ RUNBOOK.local.md
39
+ ESSAY.local.md
40
+ SOURCES.local.md
41
+ *.local.md
42
+
43
+ # Engineering Harness local state, internal planning notes
44
+ .claude/harness/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Philip Paz
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: recusal-langgraph
3
+ Version: 0.1.0
4
+ Summary: Recusal gate for LangGraph: judge every ToolNode call at execution time, refuse before it runs, and optionally put each decision on a hash-chained audit log.
5
+ Project-URL: Homepage, https://github.com/philpaz/recusal
6
+ Project-URL: Documentation, https://github.com/philpaz/recusal/tree/main/adapters/langgraph
7
+ Project-URL: Repository, https://github.com/philpaz/recusal
8
+ Project-URL: Issues, https://github.com/philpaz/recusal/issues
9
+ Project-URL: Changelog, https://github.com/philpaz/recusal/blob/main/CHANGELOG.md
10
+ Author-email: Philip Paz <philip.paz@gmail.com>
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent-governance,ai-agents,guardrails,langgraph,recusal,tool-use
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Software Development :: Quality Assurance
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: langchain-core<2,>=1.6.5
24
+ Requires-Dist: langgraph<2,>=1.2.12
25
+ Requires-Dist: recusal<1,>=0.14.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # recusal-langgraph
29
+
30
+ The [Recusal](https://github.com/philpaz/recusal) gate for
31
+ [LangGraph](https://langchain-ai.github.io/langgraph/): every tool call a `ToolNode` is
32
+ about to execute is judged by your policy first, and a refused call never runs.
33
+
34
+ This is a separate distribution from `recusal`. The kernel has zero runtime dependencies
35
+ and a frozen compatibility perimeter; this package carries the LangGraph dependency and
36
+ its own version, so a LangGraph release never forces a release of the kernel.
37
+
38
+ **Status: not yet published to PyPI.** Until it is, install it from the repository:
39
+
40
+ ```bash
41
+ pip install "recusal-langgraph @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langgraph"
42
+ ```
43
+
44
+ Requires Python 3.10+, `recusal>=0.14.0`, `langgraph>=1.2.12` and `langchain-core>=1.6.5`.
45
+ It is tested on every pull request against exactly `langgraph==1.2.12` with
46
+ `langchain-core==1.6.5`, and weekly against the newest releases.
47
+
48
+ ## Use
49
+
50
+ ```python
51
+ from langchain_core.tools import tool
52
+ from langgraph.prebuilt import ToolNode
53
+ from recusal import Finding
54
+ from recusal_langgraph import recusal_gate
55
+
56
+
57
+ @tool
58
+ def run_sql(sql: str) -> str:
59
+ """Run a SQL statement."""
60
+ ...
61
+
62
+
63
+ def policy(tool_name, tool_input):
64
+ sql = tool_input.get("sql", "")
65
+ if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
66
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
67
+ return []
68
+
69
+
70
+ node = ToolNode([run_sql], wrap_tool_call=recusal_gate(policy))
71
+ ```
72
+
73
+ Your `@tool` list goes into `ToolNode` unchanged. Every call in a model message crosses
74
+ the gate separately, immediately before execution. A refused call is answered with an
75
+ error `ToolMessage` carrying Recusal's reason, and its tool does not run. A policy that
76
+ raises refuses the call (fail closed). For an async graph, attach
77
+ `recusal_agate(policy)` with `awrap_tool_call` and run with `ainvoke`.
78
+
79
+ The policy judges the invocation the tool executes, not the dict the model wrote: the
80
+ input is validated once, defaults the model omitted are completed, and those same
81
+ objects are passed to the function. Arguments the host injects (state, store, runtime)
82
+ are left out of judgment, and the model can never supply them.
83
+
84
+ ## Put every decision on the record
85
+
86
+ ```python
87
+ from recusal.audit import AuditLog
88
+ from recusal_langgraph import recusal_audited_gate
89
+
90
+ log = AuditLog(path="decisions.jsonl")
91
+ node = ToolNode([run_sql], wrap_tool_call=recusal_audited_gate(policy, log))
92
+ ```
93
+
94
+ `recusal_audited_agate` is the async form. Each call the gate sees, allowed or refused,
95
+ is one hash-chained entry labeled `langgraph.toolnode` with LangGraph's tool call id and
96
+ a SHA-256 fingerprint of the arguments (never the arguments). If the log cannot be
97
+ written the call is refused. Check the log with `recusal audit verify decisions.jsonl`.
98
+
99
+ The audited gates call the plain gate's own judging function, so there is one decision
100
+ path.
101
+
102
+ ## What the gate refuses, and what it does not see
103
+
104
+ - **Refused before the policy runs:** a tool whose class or instance overrides the
105
+ standard execution lifecycle (it could run without reaching the gate), input that does
106
+ not validate against the tool's schema, and a tool whose callable declares a parameter
107
+ the schema omits, since that is a value no proposal can carry and the policy would
108
+ never see.
109
+ - **Not on the audit log:** a call another `wrap_tool_call` hook answered without
110
+ reaching the gate.
111
+
112
+ This package reads two private LangChain and LangGraph helpers to find the arguments the
113
+ host injects. That is why its framework requirements have an upper bound, and why the
114
+ weekly lane against the newest releases exists.
115
+
116
+ ## Compatibility
117
+
118
+ This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
119
+ public names are the ones in `recusal_langgraph.__all__`. When a LangGraph release
120
+ changes what the hook is handed, this package gets a release and the kernel does not.
121
+
122
+ A runnable offline demonstration, with a scripted graph and no API key, is
123
+ [`examples/langgraph_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/langgraph_gate.py)
124
+ and
125
+ [`examples/langgraph_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/langgraph_audit.py).
@@ -0,0 +1,98 @@
1
+ # recusal-langgraph
2
+
3
+ The [Recusal](https://github.com/philpaz/recusal) gate for
4
+ [LangGraph](https://langchain-ai.github.io/langgraph/): every tool call a `ToolNode` is
5
+ about to execute is judged by your policy first, and a refused call never runs.
6
+
7
+ This is a separate distribution from `recusal`. The kernel has zero runtime dependencies
8
+ and a frozen compatibility perimeter; this package carries the LangGraph dependency and
9
+ its own version, so a LangGraph release never forces a release of the kernel.
10
+
11
+ **Status: not yet published to PyPI.** Until it is, install it from the repository:
12
+
13
+ ```bash
14
+ pip install "recusal-langgraph @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langgraph"
15
+ ```
16
+
17
+ Requires Python 3.10+, `recusal>=0.14.0`, `langgraph>=1.2.12` and `langchain-core>=1.6.5`.
18
+ It is tested on every pull request against exactly `langgraph==1.2.12` with
19
+ `langchain-core==1.6.5`, and weekly against the newest releases.
20
+
21
+ ## Use
22
+
23
+ ```python
24
+ from langchain_core.tools import tool
25
+ from langgraph.prebuilt import ToolNode
26
+ from recusal import Finding
27
+ from recusal_langgraph import recusal_gate
28
+
29
+
30
+ @tool
31
+ def run_sql(sql: str) -> str:
32
+ """Run a SQL statement."""
33
+ ...
34
+
35
+
36
+ def policy(tool_name, tool_input):
37
+ sql = tool_input.get("sql", "")
38
+ if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
39
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
40
+ return []
41
+
42
+
43
+ node = ToolNode([run_sql], wrap_tool_call=recusal_gate(policy))
44
+ ```
45
+
46
+ Your `@tool` list goes into `ToolNode` unchanged. Every call in a model message crosses
47
+ the gate separately, immediately before execution. A refused call is answered with an
48
+ error `ToolMessage` carrying Recusal's reason, and its tool does not run. A policy that
49
+ raises refuses the call (fail closed). For an async graph, attach
50
+ `recusal_agate(policy)` with `awrap_tool_call` and run with `ainvoke`.
51
+
52
+ The policy judges the invocation the tool executes, not the dict the model wrote: the
53
+ input is validated once, defaults the model omitted are completed, and those same
54
+ objects are passed to the function. Arguments the host injects (state, store, runtime)
55
+ are left out of judgment, and the model can never supply them.
56
+
57
+ ## Put every decision on the record
58
+
59
+ ```python
60
+ from recusal.audit import AuditLog
61
+ from recusal_langgraph import recusal_audited_gate
62
+
63
+ log = AuditLog(path="decisions.jsonl")
64
+ node = ToolNode([run_sql], wrap_tool_call=recusal_audited_gate(policy, log))
65
+ ```
66
+
67
+ `recusal_audited_agate` is the async form. Each call the gate sees, allowed or refused,
68
+ is one hash-chained entry labeled `langgraph.toolnode` with LangGraph's tool call id and
69
+ a SHA-256 fingerprint of the arguments (never the arguments). If the log cannot be
70
+ written the call is refused. Check the log with `recusal audit verify decisions.jsonl`.
71
+
72
+ The audited gates call the plain gate's own judging function, so there is one decision
73
+ path.
74
+
75
+ ## What the gate refuses, and what it does not see
76
+
77
+ - **Refused before the policy runs:** a tool whose class or instance overrides the
78
+ standard execution lifecycle (it could run without reaching the gate), input that does
79
+ not validate against the tool's schema, and a tool whose callable declares a parameter
80
+ the schema omits, since that is a value no proposal can carry and the policy would
81
+ never see.
82
+ - **Not on the audit log:** a call another `wrap_tool_call` hook answered without
83
+ reaching the gate.
84
+
85
+ This package reads two private LangChain and LangGraph helpers to find the arguments the
86
+ host injects. That is why its framework requirements have an upper bound, and why the
87
+ weekly lane against the newest releases exists.
88
+
89
+ ## Compatibility
90
+
91
+ This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
92
+ public names are the ones in `recusal_langgraph.__all__`. When a LangGraph release
93
+ changes what the hook is handed, this package gets a release and the kernel does not.
94
+
95
+ A runnable offline demonstration, with a scripted graph and no API key, is
96
+ [`examples/langgraph_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/langgraph_gate.py)
97
+ and
98
+ [`examples/langgraph_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/langgraph_audit.py).
@@ -0,0 +1,55 @@
1
+ # The Recusal adapter for LangGraph, a separate distribution from `recusal`.
2
+ #
3
+ # Why separate: `recusal` has zero runtime dependencies and a frozen compatibility
4
+ # perimeter (STABILITY.md). An adapter follows a framework that releases on its own
5
+ # schedule, so it carries that dependency and its own version here, and a framework's
6
+ # breaking change never forces a release of the kernel.
7
+ #
8
+ # Build backend pinned exactly, the same pin as the kernel's pyproject.toml: a floating
9
+ # backend is unreviewed code in the release path.
10
+ [build-system]
11
+ requires = ["hatchling==1.27.0"]
12
+ build-backend = "hatchling.build"
13
+
14
+ [project]
15
+ name = "recusal-langgraph"
16
+ dynamic = ["version"]
17
+ description = "Recusal gate for LangGraph: judge every ToolNode call at execution time, refuse before it runs, and optionally put each decision on a hash-chained audit log."
18
+ readme = "README.md"
19
+ # LangGraph's own minimum.
20
+ requires-python = ">=3.10"
21
+ license = "Apache-2.0"
22
+ license-files = ["LICENSE"]
23
+ authors = [{ name = "Philip Paz", email = "philip.paz@gmail.com" }]
24
+ keywords = ["recusal", "langgraph", "ai-agents", "agent-governance", "guardrails", "tool-use"]
25
+ classifiers = [
26
+ "Development Status :: 4 - Beta",
27
+ "Intended Audience :: Developers",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3 :: Only",
31
+ "Topic :: Security",
32
+ "Topic :: Software Development :: Quality Assurance",
33
+ "Typing :: Typed",
34
+ ]
35
+ dependencies = [
36
+ # 0.14.0 is the first release where `decide` and `recusal.invocation` are public.
37
+ "recusal>=0.14.0,<1",
38
+ # The lower bound is the version the pinned CI lane tests; the weekly latest lane
39
+ # (.github/workflows/compat.yml) tests the newest release.
40
+ "langgraph>=1.2.12,<2",
41
+ "langchain-core>=1.6.5,<2",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/philpaz/recusal"
46
+ Documentation = "https://github.com/philpaz/recusal/tree/main/adapters/langgraph"
47
+ Repository = "https://github.com/philpaz/recusal"
48
+ Issues = "https://github.com/philpaz/recusal/issues"
49
+ Changelog = "https://github.com/philpaz/recusal/blob/main/CHANGELOG.md"
50
+
51
+ [tool.hatch.version]
52
+ path = "src/recusal_langgraph/__init__.py"
53
+
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["src/recusal_langgraph"]
@@ -0,0 +1,133 @@
1
+ """Prove the INSTALLED recusal-langgraph wheel gates a real LangGraph ToolNode.
2
+
3
+ Run it from a directory outside the repository, with an interpreter that has the built
4
+ wheels installed:
5
+
6
+ python /path/to/adapters/langgraph/smoke_test.py
7
+
8
+ It fails if the package it imports is the source tree and not an installed distribution:
9
+ a check run from the checkout would prove nothing about the wheel. A scripted graph
10
+ proposes the calls; no model, API key or network is used.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import os
17
+ import sys
18
+ import tempfile
19
+ from importlib import metadata
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ # Python puts this script's directory first on the import path. Drop it, so nothing in
24
+ # the source tree can stand in for the installed package.
25
+ _HERE = Path(__file__).resolve().parent
26
+ sys.path[:] = [entry for entry in sys.path if Path(entry or ".").resolve() != _HERE]
27
+
28
+ import recusal_langgraph # noqa: E402
29
+ from langchain_core.messages import AIMessage, ToolMessage # noqa: E402
30
+ from langchain_core.tools import tool # noqa: E402
31
+ from langgraph.graph import START, MessagesState, StateGraph # noqa: E402
32
+ from langgraph.prebuilt import ToolNode, tools_condition # noqa: E402
33
+ from recusal_langgraph import ( # noqa: E402
34
+ SURFACE,
35
+ recusal_agate,
36
+ recusal_audited_gate,
37
+ recusal_gate,
38
+ )
39
+
40
+ import recusal # noqa: E402
41
+ from recusal import Finding # noqa: E402
42
+ from recusal.audit import AuditLog, verify # noqa: E402
43
+
44
+ EXECUTED: list[str] = []
45
+ CALLS = [
46
+ {"name": "run_sql", "args": {"sql": "SELECT 1"}, "id": "c1", "type": "tool_call"},
47
+ {"name": "run_sql", "args": {"sql": "DELETE FROM t"}, "id": "c2", "type": "tool_call"},
48
+ ]
49
+
50
+
51
+ @tool
52
+ def run_sql(sql: str) -> str:
53
+ """Record SQL text without connecting to a database."""
54
+ EXECUTED.append(sql)
55
+ return f"recorded: {sql}"
56
+
57
+
58
+ def policy(tool_name, tool_input):
59
+ if str(tool_input.get("sql", "")).upper().startswith("DELETE"):
60
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
61
+ return []
62
+
63
+
64
+ def graph(node: ToolNode):
65
+ script = iter([AIMessage(content="", tool_calls=CALLS)])
66
+
67
+ def scripted_agent(state: MessagesState) -> dict[str, Any]:
68
+ return {"messages": [next(script, AIMessage(content="done"))]}
69
+
70
+ builder = StateGraph(MessagesState)
71
+ builder.add_node("agent", scripted_agent)
72
+ builder.add_node("tools", node)
73
+ builder.add_edge(START, "agent")
74
+ builder.add_conditional_edges("agent", tools_condition)
75
+ builder.add_edge("tools", "agent")
76
+ return builder.compile()
77
+
78
+
79
+ def answers(messages: list) -> dict[str, tuple[str, str]]:
80
+ return {
81
+ m.tool_call_id: (m.status, str(m.content)) for m in messages if isinstance(m, ToolMessage)
82
+ }
83
+
84
+
85
+ def run(node: ToolNode) -> dict[str, tuple[str, str]]:
86
+ EXECUTED.clear()
87
+ return answers(graph(node).invoke({"messages": []})["messages"])
88
+
89
+
90
+ async def arun(node: ToolNode) -> dict[str, tuple[str, str]]:
91
+ EXECUTED.clear()
92
+ return answers((await graph(node).ainvoke({"messages": []}))["messages"])
93
+
94
+
95
+ def main() -> None:
96
+ for module in (recusal, recusal_langgraph):
97
+ origin = Path(module.__file__).resolve()
98
+ assert "site-packages" in origin.parts, f"{module.__name__} is not installed: {origin}"
99
+ assert metadata.version("recusal-langgraph") == recusal_langgraph.__version__
100
+ requires = metadata.requires("recusal-langgraph") or []
101
+ assert any(r.startswith("recusal") and "lang" not in r for r in requires), requires
102
+
103
+ # Negative control: without the gate the DELETE runs, so the refusals below are the gate's.
104
+ run(ToolNode([run_sql]))
105
+ assert sorted(EXECUTED) == ["DELETE FROM t", "SELECT 1"], EXECUTED
106
+
107
+ got = run(ToolNode([run_sql], wrap_tool_call=recusal_gate(policy)))
108
+ assert EXECUTED == ["SELECT 1"], EXECUTED
109
+ assert got["c1"] == ("success", "recorded: SELECT 1"), got
110
+ assert got["c2"][0] == "error" and "DELETE is not allowed" in got["c2"][1], got
111
+
112
+ got = asyncio.run(arun(ToolNode([run_sql], awrap_tool_call=recusal_agate(policy))))
113
+ assert EXECUTED == ["SELECT 1"], EXECUTED
114
+ assert got["c2"][0] == "error" and "DELETE is not allowed" in got["c2"][1], got
115
+
116
+ with tempfile.TemporaryDirectory() as folder:
117
+ log = AuditLog(path=os.path.join(folder, "audit.jsonl"))
118
+ run(ToolNode([run_sql], wrap_tool_call=recusal_audited_gate(policy, log)))
119
+ assert EXECUTED == ["SELECT 1"], EXECUTED
120
+ by_id = {entry["action"]["tool_use_id"]: entry["action"] for entry in log.entries}
121
+ assert by_id["c2"]["decision"] == "deny" and by_id["c2"]["surface"] == SURFACE, by_id
122
+ assert by_id["c1"]["decision"] != "deny", by_id
123
+ intact, problems = verify(log.entries)
124
+ assert intact, problems
125
+
126
+ print(
127
+ f"recusal-langgraph {recusal_langgraph.__version__} with recusal "
128
+ f"{recusal.__version__}: installed wheel gates and records"
129
+ )
130
+
131
+
132
+ if __name__ == "__main__":
133
+ main()
@@ -0,0 +1,32 @@
1
+ """Recusal for LangGraph: judge every ``ToolNode`` call before it runs.
2
+
3
+ from langgraph.prebuilt import ToolNode
4
+ from recusal_langgraph import recusal_gate
5
+
6
+ node = ToolNode([run_sql], wrap_tool_call=recusal_gate(policy))
7
+
8
+ ``policy(tool_name, tool_input)`` is an ordinary Recusal policy returning findings. A
9
+ refused call is answered with an error ``ToolMessage`` carrying Recusal's reason, and its
10
+ tool does not run. ``recusal_agate`` is the ``awrap_tool_call`` form, and
11
+ ``recusal_audited_gate`` and ``recusal_audited_agate`` put each decision on a hash-chained
12
+ audit log.
13
+
14
+ The decision is made by ``recusal.decide``. This package adds only what is LangGraph's:
15
+ where the hook attaches, how the invocation is completed, and how a refusal is answered.
16
+ """
17
+
18
+ from ._audit import SURFACE, recusal_audited_agate, recusal_audited_gate
19
+ from ._gate import Policy, RecusalRefusal, recusal_agate, recusal_gate
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ __all__ = [
24
+ "SURFACE",
25
+ "Policy",
26
+ "RecusalRefusal",
27
+ "__version__",
28
+ "recusal_agate",
29
+ "recusal_audited_agate",
30
+ "recusal_audited_gate",
31
+ "recusal_gate",
32
+ ]
@@ -0,0 +1,89 @@
1
+ """The audited gate: the same decision, with every call on a hash-chained ``AuditLog``.
2
+
3
+ ``recusal_audited_gate(policy, log)`` and ``recusal_audited_agate(policy, log)`` call the
4
+ plain gate's own judging function with the recording arguments passed through to
5
+ ``recusal.decide``, which writes the entry before returning. There is no second decision
6
+ path. If the log cannot be written the decision becomes a deny, so nothing runs unrecorded.
7
+
8
+ Each entry carries the surface ``langgraph.toolnode`` and LangGraph's tool call id, and a
9
+ SHA-256 fingerprint of the arguments, never the arguments themselves.
10
+
11
+ What each entry is bound to:
12
+
13
+ - a call that is judged: the invocation the tool executes, validated and completed, with
14
+ host-injected arguments left out;
15
+ - a call refused before judgment (a tool that overrides the standard lifecycle, input that
16
+ does not validate, a parameter the schema omits): the arguments as proposed.
17
+
18
+ What is not on the log: a call another ``wrap_tool_call`` hook answered without reaching
19
+ the gate.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any, Optional
25
+
26
+ from recusal.audit import AuditLog
27
+
28
+ from ._gate import Policy, _judge
29
+
30
+ #: The surface label every entry carries: the runtime that adjudicated, LangGraph's ToolNode.
31
+ SURFACE = "langgraph.toolnode"
32
+
33
+
34
+ def _recording(
35
+ request,
36
+ actor: Optional[str],
37
+ control: Optional[dict[str, Any]],
38
+ log: AuditLog,
39
+ surface: str = SURFACE,
40
+ ):
41
+ """The recording arguments for one call, built in one place for both gates."""
42
+ return {
43
+ "audit": log,
44
+ "surface": surface,
45
+ "tool_use_id": request.tool_call["id"],
46
+ "actor": actor,
47
+ "control": control,
48
+ }
49
+
50
+
51
+ def recusal_audited_gate(
52
+ policy: Policy,
53
+ log: AuditLog,
54
+ *,
55
+ actor: Optional[str] = None,
56
+ control: Optional[dict[str, Any]] = None,
57
+ surface: str = SURFACE,
58
+ ):
59
+ """Return a synchronous ToolNode hook that records, then gates, each call.
60
+
61
+ ``surface`` names the runtime on the record; another host of the same hook
62
+ (LangChain's ``create_agent`` middleware) passes its own."""
63
+
64
+ def gate(request, execute):
65
+ refusal, judged = _judge(
66
+ request, policy, **_recording(request, actor, control, log, surface)
67
+ )
68
+ return refusal if refusal is not None else execute(judged)
69
+
70
+ return gate
71
+
72
+
73
+ def recusal_audited_agate(
74
+ policy: Policy,
75
+ log: AuditLog,
76
+ *,
77
+ actor: Optional[str] = None,
78
+ control: Optional[dict[str, Any]] = None,
79
+ surface: str = SURFACE,
80
+ ):
81
+ """Return an asynchronous ToolNode hook for awrap_tool_call, same logic as the sync one."""
82
+
83
+ async def gate(request, execute):
84
+ refusal, judged = _judge(
85
+ request, policy, is_async=True, **_recording(request, actor, control, log, surface)
86
+ )
87
+ return refusal if refusal is not None else await execute(judged)
88
+
89
+ return gate
@@ -0,0 +1,423 @@
1
+ """The gate: judge each ``ToolNode`` call at execution time, on the invocation that runs.
2
+
3
+ The hook is LangGraph-native: a user's existing ``@tool`` list goes unchanged into
4
+ ``ToolNode`` and ``recusal_gate(policy)`` is attached with ``wrap_tool_call``. Every call in
5
+ a model message crosses the gate separately immediately before execution. Denials become
6
+ error ``ToolMessage`` objects carrying Recusal's reason; allow and defer execute normally.
7
+ Async graphs attach ``recusal_agate(policy)`` through ``awrap_tool_call`` and run with
8
+ ``ainvoke``, using the same decision logic.
9
+
10
+ The policy judges the invocation the tool executes, not the dict the model wrote: the hook
11
+ hands execution a per-call copy of the tool whose parse step (``_to_args_and_kwargs``, run by
12
+ ``BaseTool.run``/``arun`` after ToolNode has injected the host's state, store and runtime)
13
+ validates the input once, holds the callable the route executes to the schema (every named
14
+ parameter it declares is a field the schema declares, a key the host injects, or a name the
15
+ framework reserves and fills at call time; any other is a default the model's proposal cannot
16
+ carry and the policy would never see, so the call is refused), completes any schema parameter
17
+ the framework's parse dropped (``_parse_input`` selects the kwargs it returns through the
18
+ argument model's own ``model_dump``, so a field with ``exclude=True`` or a root serializer can
19
+ vanish) from that callable's default, projects every model-controlled argument through a
20
+ projection that runs no serializer of its own, decides, and on allow passes those same
21
+ completed objects to the function. Host arguments are excluded from judgment and can never be
22
+ supplied by the model; a tool whose class or instance overrides the standard lifecycle is
23
+ refused rather than judged in the wrong place.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import dataclasses
29
+ import datetime
30
+ import decimal
31
+ import enum
32
+ import inspect
33
+ import math
34
+ import uuid
35
+ from typing import Any, Callable, List
36
+
37
+ from langchain_core.messages import ToolMessage
38
+ from langchain_core.tools import BaseTool, StructuredTool, Tool, ToolException
39
+ from langchain_core.tools.base import FILTERED_ARGS, _get_runnable_config_param
40
+ from langgraph.prebuilt.tool_node import _get_all_injected_args
41
+ from pydantic import BaseModel, ValidationError
42
+
43
+ from recusal import Finding, decide
44
+
45
+ #: A Recusal policy: ``policy(tool_name, tool_input)`` returns a list of findings.
46
+ Policy = Callable[[str, dict], List[Any]]
47
+
48
+
49
+ class RecusalRefusal(ToolException):
50
+ """Raised inside a judging copy's parse step: the call is refused and the message is the
51
+ reason. ``BaseTool.run``/``arun`` turn it into an error ToolMessage through the copy's
52
+ ``handle_tool_error``, which handles only this type and leaves every other
53
+ ``ToolException`` to the original tool's own setting."""
54
+
55
+
56
+ # The execution lifecycle this gate relies on: ``invoke``/``ainvoke`` call ``run``/``arun``,
57
+ # which parse the input through ``_to_args_and_kwargs`` and then call ``_run``/``_arun``.
58
+ # The judging copy replaces that parse step, so a tool that overrides any of these on its
59
+ # class (other than the three standard implementations) or on the instance may execute
60
+ # without ever reaching the seam; such a tool is refused rather than judged in the wrong place.
61
+ _LIFECYCLE = ("invoke", "ainvoke", "run", "arun", "_to_args_and_kwargs")
62
+ _STANDARD = {
63
+ name: {vars(cls)[name] for cls in (BaseTool, StructuredTool, Tool) if name in vars(cls)}
64
+ for name in _LIFECYCLE
65
+ }
66
+
67
+
68
+ def _lifecycle_refusal(tool) -> str | None:
69
+ """Why this tool's execution path cannot be judged at the parse seam, or None."""
70
+ for name in _LIFECYCLE:
71
+ if name in vars(tool):
72
+ return f"`{name}` is overridden on the tool instance"
73
+ if getattr(type(tool), name, None) not in _STANDARD[name]:
74
+ return f"{type(tool).__name__} overrides `{name}`"
75
+ return None
76
+
77
+
78
+ def _host_keys(tool) -> frozenset[str]:
79
+ """The argument names the host supplies, never the model.
80
+
81
+ ToolNode strips every ``InjectedToolArg``-annotated key from the model's arguments and
82
+ adds back only the state, store and runtime it owns (``_inject_tool_args``), and
83
+ ``_parse_input`` sets an ``InjectedToolCallId`` from the call id; a value under one of
84
+ these keys at the parse seam is therefore the host's. Everything else the parse step
85
+ produces, including a field an ``extra="allow"`` schema accepted, is model-controlled and
86
+ is judged.
87
+ """
88
+ injected = _get_all_injected_args(tool)
89
+ return frozenset(injected.all_injected_keys) | frozenset(
90
+ getattr(tool, "_injected_args_keys", ())
91
+ )
92
+
93
+
94
+ def _schema_fields(tool) -> frozenset[str]:
95
+ """The parameter names the tool's ``args_schema`` declares (host-injected ones included;
96
+ they are excluded elsewhere), or none for a tool without a model schema."""
97
+ schema = tool.args_schema
98
+ if isinstance(schema, dict):
99
+ return frozenset(schema.get("properties", {}))
100
+ if isinstance(schema, type) and issubclass(schema, BaseModel):
101
+ return frozenset(schema.model_fields)
102
+ return frozenset()
103
+
104
+
105
+ #: The parameter names the SDK reserves for itself (``run_manager``, ``callbacks``): it strips
106
+ #: them from every schema it generates and fills ``callbacks`` on a function and
107
+ #: ``run_manager`` on ``_run``/``_arun`` at call time, so a value under either name is never
108
+ #: the model's. ``tests/test_langgraph_gate.py`` pins the set against the SDK's own constant.
109
+ _RESERVED = frozenset(FILTERED_ARGS)
110
+
111
+
112
+ def _execution_callable(tool, is_async: bool):
113
+ """The function the active route finally calls, chosen as the SDK chooses it.
114
+
115
+ ``StructuredTool._run`` calls ``func`` and ``_arun`` calls ``coroutine``, falling back to
116
+ ``func`` on a thread when there is none; ``BaseTool.arun`` runs the class's ``_arun`` when
117
+ it overrides the default and ``_run`` otherwise, and ``run`` always runs ``_run``. Bound
118
+ methods are returned, so ``self`` is not among the parameters inspected.
119
+ """
120
+ if isinstance(tool, StructuredTool):
121
+ target = tool.coroutine if is_async and tool.coroutine is not None else tool.func
122
+ if target is None:
123
+ raise TypeError(
124
+ "the tool has no callable for this route, so the invocation cannot be judged"
125
+ )
126
+ return target
127
+ if is_async and type(tool)._arun is not BaseTool._arun:
128
+ return tool._arun
129
+ return tool._run
130
+
131
+
132
+ def _framework_keys(func) -> frozenset[str]:
133
+ """The parameter names the framework fills on ``func`` at call time: the reserved names
134
+ and the parameter annotated ``RunnableConfig``, found exactly as the SDK finds it."""
135
+ config_param = _get_runnable_config_param(func)
136
+ return _RESERVED | ({config_param} if config_param else frozenset())
137
+
138
+
139
+ def _completed(
140
+ kwargs: dict[str, Any], tool, host_keys: frozenset[str], is_async: bool
141
+ ) -> dict[str, Any]:
142
+ """The parsed kwargs, held to the callable the route executes, with every suppressed
143
+ schema parameter restored from that callable's default.
144
+
145
+ Python fills whatever the parsed kwargs leave out from the callable's own defaults, after
146
+ the policy has judged, so the callable is the authority on what will execute. Each named
147
+ parameter it declares must be a field the schema declares (judged), a key the host injects
148
+ (never the model's) or a name the framework fills at call time (:func:`_framework_keys`);
149
+ any other parameter is a value the proposal cannot carry and the policy would never see,
150
+ so the call is refused as unjudgeable, naming the parameter and never its default. A
151
+ positional-only parameter cannot be judged by name and is refused too.
152
+
153
+ ``_parse_input`` returns only the fields present in the validated model's
154
+ ``model_dump()``, so a schema field with ``exclude=True`` or a model-wide serializer that
155
+ omits it never reaches the kwargs, and the function would fill its own Python default
156
+ after the policy judged an invocation without it. Each parameter the schema declares, the
157
+ host does not inject, and the parse did not return is taken from the route's callable's
158
+ default here, and passed explicitly, so the judged invocation is the executed one; a
159
+ suppressed parameter with no default raises ``TypeError`` and the call is refused as
160
+ unjudgeable.
161
+ """
162
+ fields = _schema_fields(tool)
163
+ func = _execution_callable(tool, is_async)
164
+ try:
165
+ parameters = inspect.signature(func).parameters
166
+ except (TypeError, ValueError) as exc:
167
+ raise TypeError(f"the tool's callable cannot be inspected for its parameters ({exc})")
168
+ framework_keys = _framework_keys(func)
169
+ completed = dict(kwargs)
170
+ for name, parameter in parameters.items():
171
+ if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
172
+ continue
173
+ if name in host_keys or name in framework_keys:
174
+ continue
175
+ if parameter.kind is parameter.POSITIONAL_ONLY:
176
+ raise TypeError(
177
+ f"the callable's parameter `{name}` is positional-only, so the invocation "
178
+ "cannot be judged by name"
179
+ )
180
+ if name not in fields:
181
+ raise TypeError(
182
+ f"the callable's parameter `{name}` is absent from the argument schema, so "
183
+ "the invocation cannot be judged; declare it in the schema"
184
+ )
185
+ if name in completed:
186
+ continue
187
+ if parameter.default is parameter.empty:
188
+ raise TypeError(
189
+ f"the schema suppressed `{name}` and the callable has no default for it, so "
190
+ "the invocation cannot be judged"
191
+ )
192
+ completed[name] = parameter.default
193
+ return completed
194
+
195
+
196
+ def _faithful(value: Any, _stack: tuple[int, ...] = ()) -> Any:
197
+ """A detached, serializer-free data projection of one parsed argument, for judgment.
198
+
199
+ The policy receives this projection; the tool receives the original parsed objects. The
200
+ projection reads a Pydantic model field by field (``getattr`` over ``model_fields`` plus
201
+ ``model_extra``), so no ``field_serializer`` or custom ``model_dump`` runs: a serializer
202
+ that displays ``SELECT`` for a field holding ``DELETE`` is exactly what this bypasses.
203
+ Supported, each with a fixed meaning: ``None``, ``bool``, ``int``, ``str``; a finite
204
+ ``float``; ``Enum`` by its value (projected in turn); ``datetime``/``date``/``time`` by
205
+ ``isoformat()``; a finite ``Decimal`` and a ``UUID`` by ``str()``; ``list`` and ``tuple``
206
+ as a new list; ``dict`` with ``str`` keys as a new dict; Pydantic v2 models and
207
+ dataclasses as a new dict of their fields. Anything else (a Pydantic v1 model, a set, an
208
+ arbitrary object, a non-finite number, a cyclic value) raises ``TypeError`` and the call is
209
+ refused: a value that cannot be represented faithfully cannot be judged. Containers are
210
+ new objects, so a policy that mutates what it was given cannot change the invocation.
211
+ """
212
+ if isinstance(value, enum.Enum):
213
+ return _faithful(value.value, _stack)
214
+ if value is None or isinstance(value, (bool, int, str)):
215
+ return value
216
+ if isinstance(value, float):
217
+ if not math.isfinite(value):
218
+ raise TypeError("a non-finite float cannot be judged")
219
+ return value
220
+ if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
221
+ return value.isoformat()
222
+ if isinstance(value, decimal.Decimal):
223
+ if not value.is_finite():
224
+ raise TypeError("a non-finite Decimal cannot be judged")
225
+ return str(value)
226
+ if isinstance(value, uuid.UUID):
227
+ return str(value)
228
+ if id(value) in _stack:
229
+ raise TypeError("a cyclic value cannot be judged")
230
+ stack = _stack + (id(value),)
231
+ if isinstance(value, (list, tuple)):
232
+ return [_faithful(item, stack) for item in value]
233
+ if isinstance(value, dict):
234
+ projected = {}
235
+ for key, item in value.items():
236
+ if not isinstance(key, str):
237
+ raise TypeError(f"a mapping keyed by {type(key).__name__} cannot be judged")
238
+ projected[key] = _faithful(item, stack)
239
+ return projected
240
+ if isinstance(value, BaseModel):
241
+ projected = {
242
+ name: _faithful(getattr(value, name), stack) for name in type(value).model_fields
243
+ }
244
+ for key, item in (value.model_extra or {}).items():
245
+ projected[key] = _faithful(item, stack)
246
+ return projected
247
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
248
+ return {
249
+ field.name: _faithful(getattr(value, field.name), stack)
250
+ for field in dataclasses.fields(value)
251
+ }
252
+ raise TypeError(f"a {type(value).__name__} value cannot be judged faithfully")
253
+
254
+
255
+ #: Error types whose message is written by user code (a validator's ``raise ValueError``
256
+ #: or ``assert``), so it may echo anything the validator could see, including host state.
257
+ _USER_WRITTEN = frozenset({"value_error", "assertion_error"})
258
+
259
+
260
+ def _sanitized(exc: Exception, host_keys: frozenset[str]) -> str:
261
+ """A validation failure reduced to what is demonstrably safe to show the model and to
262
+ put on the record.
263
+
264
+ Pydantic's ``errors(include_input=False, include_context=False)`` already leaves the
265
+ input out, but a message is still forwarded only when it is one of Pydantic's own
266
+ templates for a model-facing field: an error at the model root (a ``model_validator``,
267
+ location ``()``), an error under a host-supplied argument (whose value may be graph
268
+ state), and an error of a user-written type (``value_error``, ``assertion_error``, whose
269
+ text a validator composed and may have built from host context) are reported as
270
+ location and error type only. A non-Pydantic exception is its class name."""
271
+ if isinstance(exc, ValidationError):
272
+ parts = []
273
+ for error in exc.errors(include_url=False, include_context=False, include_input=False):
274
+ loc = tuple(str(part) for part in error.get("loc", ()))
275
+ kind = str(error.get("type"))
276
+ where = ".".join(loc) or "model"
277
+ if not loc or loc[0] in host_keys or kind in _USER_WRITTEN:
278
+ parts.append(f"{where}: {kind}")
279
+ else:
280
+ parts.append(f"{where}: {error.get('msg')}")
281
+ return "; ".join(parts)
282
+ return type(exc).__name__
283
+
284
+
285
+ def _unjudgeable(name: str, detail: str, bound: dict, policy: Policy, record: dict) -> str:
286
+ """The reason for a call that cannot be judged, recorded through ``decide`` like every
287
+ other refusal (so an audited gate logs it)."""
288
+
289
+ def unjudgeable(_name, _input):
290
+ return [Finding.fail("recusal_unjudgeable_input", severity="CRITICAL", message=detail)]
291
+
292
+ try:
293
+ _, reason = decide(name, bound, unjudgeable, safe_errors=True, **record)
294
+ except Exception as exc: # noqa: BLE001, the refusal stands even if the record cannot be written
295
+ reason = (
296
+ f"Recusal failed closed (policy error): RECUSAL_POLICY_ERROR ({type(exc).__name__})"
297
+ )
298
+ return reason
299
+
300
+
301
+ def _judging(tool, call: dict[str, Any], policy: Policy, record: dict[str, Any], is_async: bool):
302
+ """A per-call copy of ``tool`` that judges, then runs, exactly the invocation it parsed.
303
+
304
+ ``BaseTool.run``/``arun`` parse the input through ``_to_args_and_kwargs`` and hand the
305
+ result to ``_run``/``_arun``; ToolNode injects the host's state, store and runtime into
306
+ the input before that (``_inject_tool_args``), whatever hook or middleware ran earlier.
307
+ The copy's parse step therefore sees the final input: it runs the tool's own parser once,
308
+ holds the callable this route executes (``is_async`` names the route) to the schema and
309
+ completes any schema parameter that parse suppressed from that callable's default
310
+ (:func:`_completed`), projects every model-controlled argument with :func:`_faithful`,
311
+ calls ``decide`` once, and on allow returns the very objects it judged, so the tool
312
+ executes what was judged with no second validation and nothing to compare. A deny, an input the parser rejects,
313
+ a positional input, or a value that cannot be projected raises :class:`RecusalRefusal`,
314
+ which the copy's ``handle_tool_error`` turns into the error ToolMessage the model reads;
315
+ any other ``ToolException`` keeps the original tool's handling. The copy serves one call
316
+ id; every execution attempt of that call (a retry, a resume) is judged again.
317
+ """
318
+ name, call_id, fallback = call["name"], call.get("id"), call.get("args")
319
+ copy = tool.model_copy()
320
+ parse = type(tool)._to_args_and_kwargs
321
+ host_keys = _host_keys(tool)
322
+ original_handler = tool.handle_tool_error
323
+
324
+ def proposal(tool_input) -> dict:
325
+ """The model-facing input, for the record of a refusal that judged nothing."""
326
+ if isinstance(tool_input, dict):
327
+ try:
328
+ return _faithful({k: v for k, v in tool_input.items() if k not in host_keys})
329
+ except TypeError:
330
+ pass
331
+ return fallback if isinstance(fallback, dict) else {"input": fallback}
332
+
333
+ def seam(tool_input, tool_call_id):
334
+ if tool_call_id != call_id:
335
+ raise RuntimeError("Recusal: a judging copy of a tool was used for a different call")
336
+ try:
337
+ args, kwargs = parse(copy, tool_input, tool_call_id)
338
+ except Exception as exc: # noqa: BLE001, an input the tool rejects is refused with its reason
339
+ detail = f"arguments do not validate ({_sanitized(exc, host_keys)})"
340
+ raise RecusalRefusal(_unjudgeable(name, detail, proposal(tool_input), policy, record))
341
+ if args:
342
+ detail = "a positional tool input cannot be judged by name"
343
+ raise RecusalRefusal(_unjudgeable(name, detail, proposal(tool_input), policy, record))
344
+ try:
345
+ kwargs = _completed(kwargs, tool, host_keys, is_async)
346
+ judged = {k: _faithful(v) for k, v in kwargs.items() if k not in host_keys}
347
+ except TypeError as exc:
348
+ raise RecusalRefusal(_unjudgeable(name, str(exc), proposal(tool_input), policy, record))
349
+ try:
350
+ decision, reason = decide(name, judged, policy, safe_errors=True, **record)
351
+ except Exception as exc: # noqa: BLE001, a buggy policy must not silently disable the gate
352
+ decision, reason = (
353
+ "deny",
354
+ f"Recusal failed closed (policy error): RECUSAL_POLICY_ERROR ({type(exc).__name__})",
355
+ )
356
+ if decision == "deny":
357
+ raise RecusalRefusal(reason)
358
+ return args, kwargs
359
+
360
+ def handle(exc):
361
+ if isinstance(exc, RecusalRefusal):
362
+ return str(exc)
363
+ if not original_handler:
364
+ raise exc
365
+ if original_handler is True:
366
+ return str(exc)
367
+ if isinstance(original_handler, str):
368
+ return original_handler
369
+ return original_handler(exc)
370
+
371
+ object.__setattr__(copy, "_to_args_and_kwargs", seam)
372
+ object.__setattr__(copy, "handle_tool_error", handle)
373
+ return copy
374
+
375
+
376
+ def _judge(request, policy: Policy, *, is_async: bool = False, **record: Any):
377
+ """Return ``(refusal, request_to_execute)``: a refusal ToolMessage for a call that can
378
+ never reach the seam, else the request with its tool replaced by the judging copy.
379
+
380
+ ``is_async`` names the route the hook runs on (``awrap_tool_call`` executes the tool
381
+ through ``arun``), so the copy holds the callable that route runs. ``record`` goes
382
+ straight to ``decide`` (``audit=``, ``surface=``, ``tool_use_id=``, ...), so a gate that
383
+ puts the decision on a log (examples/langgraph_audit.py) decides, and refuses, exactly as
384
+ this one does: one function, no second copy to drift.
385
+ """
386
+ call = request.tool_call
387
+ name, call_id, raw = call["name"], call.get("id"), call.get("args")
388
+
389
+ def refuse(detail):
390
+ bound = raw if isinstance(raw, dict) else {"input": raw}
391
+ reason = _unjudgeable(name, detail, bound, policy, record)
392
+ return ToolMessage(content=reason, tool_call_id=call_id, name=name, status="error"), None
393
+
394
+ tool = request.tool
395
+ if tool is None:
396
+ return refuse("no tool by that name is registered with this node")
397
+ why = _lifecycle_refusal(tool)
398
+ if why is not None:
399
+ return refuse(
400
+ f"the tool's execution path cannot be judged ({why}); the gate judges inside the "
401
+ "standard BaseTool lifecycle, so build the tool with @tool or StructuredTool"
402
+ )
403
+ return None, request.override(tool=_judging(tool, call, policy, record, is_async))
404
+
405
+
406
+ def recusal_gate(policy: Policy):
407
+ """Return a synchronous ToolNode hook that gates each call before execution."""
408
+
409
+ def gate(request, execute):
410
+ refusal, judged = _judge(request, policy)
411
+ return refusal if refusal is not None else execute(judged)
412
+
413
+ return gate
414
+
415
+
416
+ def recusal_agate(policy: Policy):
417
+ """Return an asynchronous ToolNode hook for awrap_tool_call."""
418
+
419
+ async def gate(request, execute):
420
+ refusal, judged = _judge(request, policy, is_async=True)
421
+ return refusal if refusal is not None else await execute(judged)
422
+
423
+ return gate
File without changes
@@ -0,0 +1,2 @@
1
+ langgraph==1.2.12
2
+ langchain-core==1.6.5