recusal-langchain 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,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: recusal-langchain
3
+ Version: 0.1.0
4
+ Summary: Recusal gate for LangChain create_agent: the recusal-langgraph ToolNode gate as tool-call middleware, refusing a call before it runs and optionally putting 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/langchain
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,langchain,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<2,>=1.4.3
24
+ Requires-Dist: recusal-langgraph<1,>=0.1.0
25
+ Requires-Dist: recusal<1,>=0.14.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # recusal-langchain
29
+
30
+ The [Recusal](https://github.com/philpaz/recusal) gate for a
31
+ [LangChain](https://docs.langchain.com/) `create_agent` agent: every tool call the agent
32
+ proposes is judged by your policy before the tool runs, 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 LangChain dependency and
36
+ its own version, so a LangChain release never forces a release of the kernel.
37
+
38
+ A `create_agent` agent executes its tools through a LangGraph `ToolNode`, so this package
39
+ adds no decision logic of its own. It wraps the gate of
40
+ [`recusal-langgraph`](https://github.com/philpaz/recusal/tree/main/adapters/langgraph) as
41
+ LangChain middleware and depends on that package.
42
+
43
+ **Status: not yet published to PyPI.** Until it is, install both from the repository,
44
+ `recusal-langgraph` first since this package requires it:
45
+
46
+ ```bash
47
+ pip install "recusal-langgraph @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langgraph"
48
+ pip install "recusal-langchain @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langchain"
49
+ ```
50
+
51
+ Requires Python 3.10+, `recusal>=0.14.0`, `recusal-langgraph>=0.1.0` and
52
+ `langchain>=1.4.3`. It is tested on every pull request against exactly
53
+ `langchain==1.4.3` with `langgraph==1.2.12` and `langchain-core==1.6.5`, and weekly
54
+ against the newest releases.
55
+
56
+ ## Use
57
+
58
+ ```python
59
+ from langchain.agents import create_agent
60
+ from langchain_core.tools import tool
61
+ from recusal import Finding
62
+ from recusal_langchain import gate_middleware
63
+
64
+
65
+ @tool
66
+ def run_sql(sql: str) -> str:
67
+ """Run a SQL statement."""
68
+ ...
69
+
70
+
71
+ def policy(tool_name, tool_input):
72
+ sql = tool_input.get("sql", "")
73
+ if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
74
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
75
+ return []
76
+
77
+
78
+ agent = create_agent(model=model, tools=[run_sql], middleware=[gate_middleware(policy)])
79
+ ```
80
+
81
+ A refused call is answered with an error `ToolMessage` carrying Recusal's reason, and its
82
+ tool does not run. A policy that raises refuses the call (fail closed). For
83
+ `agent.ainvoke`, use `agate_middleware(policy)`; the sync gate alone raises there.
84
+
85
+ **List the middleware last.** The first middleware in the list is the outermost, so
86
+ anything listed after the gate runs between the gate and the tool.
87
+
88
+ ## Put every decision on the record
89
+
90
+ ```python
91
+ from recusal.audit import AuditLog
92
+ from recusal_langchain import audited_gate_middleware
93
+
94
+ log = AuditLog(path="decisions.jsonl")
95
+ agent = create_agent(
96
+ model=model, tools=[run_sql], middleware=[audited_gate_middleware(policy, log)]
97
+ )
98
+ ```
99
+
100
+ `audited_agate_middleware` is the async form. Each call the gate sees, allowed or
101
+ refused, is one hash-chained entry labeled `langchain.create_agent` with LangChain's tool
102
+ call id and a SHA-256 fingerprint of the arguments (never the arguments). If the log
103
+ cannot be written the call is refused. Check the log with
104
+ `recusal audit verify decisions.jsonl`.
105
+
106
+ ## What the gate does not see
107
+
108
+ The gate judges, and records, inside the tool's own lifecycle. A middleware listed after
109
+ it that rewrites the arguments is still judged and recorded as rewritten. A middleware
110
+ listed after it that swaps the tool object, or answers in the tool's place, removes the
111
+ judging copy, and that call is neither judged nor recorded. That is why the gate goes
112
+ last.
113
+
114
+ Everything `recusal-langgraph` refuses before the policy runs is refused here too: a tool
115
+ that overrides the standard execution lifecycle, input that does not validate, and a
116
+ callable with a parameter its schema omits.
117
+
118
+ ## Compatibility
119
+
120
+ This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
121
+ public names are the ones in `recusal_langchain.__all__`. It uses only the public names
122
+ of `recusal-langgraph`.
123
+
124
+ A runnable offline demonstration, with a scripted model and no API key, is
125
+ [`examples/langchain_agent_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/langchain_agent_gate.py)
126
+ and
127
+ [`examples/langchain_agent_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/langchain_agent_audit.py).
@@ -0,0 +1,100 @@
1
+ # recusal-langchain
2
+
3
+ The [Recusal](https://github.com/philpaz/recusal) gate for a
4
+ [LangChain](https://docs.langchain.com/) `create_agent` agent: every tool call the agent
5
+ proposes is judged by your policy before the tool runs, 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 LangChain dependency and
9
+ its own version, so a LangChain release never forces a release of the kernel.
10
+
11
+ A `create_agent` agent executes its tools through a LangGraph `ToolNode`, so this package
12
+ adds no decision logic of its own. It wraps the gate of
13
+ [`recusal-langgraph`](https://github.com/philpaz/recusal/tree/main/adapters/langgraph) as
14
+ LangChain middleware and depends on that package.
15
+
16
+ **Status: not yet published to PyPI.** Until it is, install both from the repository,
17
+ `recusal-langgraph` first since this package requires it:
18
+
19
+ ```bash
20
+ pip install "recusal-langgraph @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langgraph"
21
+ pip install "recusal-langchain @ git+https://github.com/philpaz/recusal#subdirectory=adapters/langchain"
22
+ ```
23
+
24
+ Requires Python 3.10+, `recusal>=0.14.0`, `recusal-langgraph>=0.1.0` and
25
+ `langchain>=1.4.3`. It is tested on every pull request against exactly
26
+ `langchain==1.4.3` with `langgraph==1.2.12` and `langchain-core==1.6.5`, and weekly
27
+ against the newest releases.
28
+
29
+ ## Use
30
+
31
+ ```python
32
+ from langchain.agents import create_agent
33
+ from langchain_core.tools import tool
34
+ from recusal import Finding
35
+ from recusal_langchain import gate_middleware
36
+
37
+
38
+ @tool
39
+ def run_sql(sql: str) -> str:
40
+ """Run a SQL statement."""
41
+ ...
42
+
43
+
44
+ def policy(tool_name, tool_input):
45
+ sql = tool_input.get("sql", "")
46
+ if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
47
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
48
+ return []
49
+
50
+
51
+ agent = create_agent(model=model, tools=[run_sql], middleware=[gate_middleware(policy)])
52
+ ```
53
+
54
+ A refused call is answered with an error `ToolMessage` carrying Recusal's reason, and its
55
+ tool does not run. A policy that raises refuses the call (fail closed). For
56
+ `agent.ainvoke`, use `agate_middleware(policy)`; the sync gate alone raises there.
57
+
58
+ **List the middleware last.** The first middleware in the list is the outermost, so
59
+ anything listed after the gate runs between the gate and the tool.
60
+
61
+ ## Put every decision on the record
62
+
63
+ ```python
64
+ from recusal.audit import AuditLog
65
+ from recusal_langchain import audited_gate_middleware
66
+
67
+ log = AuditLog(path="decisions.jsonl")
68
+ agent = create_agent(
69
+ model=model, tools=[run_sql], middleware=[audited_gate_middleware(policy, log)]
70
+ )
71
+ ```
72
+
73
+ `audited_agate_middleware` is the async form. Each call the gate sees, allowed or
74
+ refused, is one hash-chained entry labeled `langchain.create_agent` with LangChain's tool
75
+ call id and a SHA-256 fingerprint of the arguments (never the arguments). If the log
76
+ cannot be written the call is refused. Check the log with
77
+ `recusal audit verify decisions.jsonl`.
78
+
79
+ ## What the gate does not see
80
+
81
+ The gate judges, and records, inside the tool's own lifecycle. A middleware listed after
82
+ it that rewrites the arguments is still judged and recorded as rewritten. A middleware
83
+ listed after it that swaps the tool object, or answers in the tool's place, removes the
84
+ judging copy, and that call is neither judged nor recorded. That is why the gate goes
85
+ last.
86
+
87
+ Everything `recusal-langgraph` refuses before the policy runs is refused here too: a tool
88
+ that overrides the standard execution lifecycle, input that does not validate, and a
89
+ callable with a parameter its schema omits.
90
+
91
+ ## Compatibility
92
+
93
+ This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
94
+ public names are the ones in `recusal_langchain.__all__`. It uses only the public names
95
+ of `recusal-langgraph`.
96
+
97
+ A runnable offline demonstration, with a scripted model and no API key, is
98
+ [`examples/langchain_agent_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/langchain_agent_gate.py)
99
+ and
100
+ [`examples/langchain_agent_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/langchain_agent_audit.py).
@@ -0,0 +1,56 @@
1
+ # The Recusal adapter for LangChain create_agent, 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-langchain"
16
+ dynamic = ["version"]
17
+ description = "Recusal gate for LangChain create_agent: the recusal-langgraph ToolNode gate as tool-call middleware, refusing a call before it runs and optionally putting each decision on a hash-chained audit log."
18
+ readme = "README.md"
19
+ # LangChain'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", "langchain", "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 gate itself. This package wraps its public hooks and nothing private.
39
+ "recusal-langgraph>=0.1.0,<1",
40
+ # The lower bound is the version the pinned CI lane tests; the weekly latest lane
41
+ # (.github/workflows/compat.yml) tests the newest release.
42
+ "langchain>=1.4.3,<2",
43
+ ]
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/philpaz/recusal"
47
+ Documentation = "https://github.com/philpaz/recusal/tree/main/adapters/langchain"
48
+ Repository = "https://github.com/philpaz/recusal"
49
+ Issues = "https://github.com/philpaz/recusal/issues"
50
+ Changelog = "https://github.com/philpaz/recusal/blob/main/CHANGELOG.md"
51
+
52
+ [tool.hatch.version]
53
+ path = "src/recusal_langchain/__init__.py"
54
+
55
+ [tool.hatch.build.targets.wheel]
56
+ packages = ["src/recusal_langchain"]
@@ -0,0 +1,131 @@
1
+ """Prove the INSTALLED recusal-langchain wheel gates a real LangChain create_agent agent.
2
+
3
+ Run it from a directory outside the repository, with an interpreter that has the built
4
+ wheels installed (recusal, recusal-langgraph and recusal-langchain):
5
+
6
+ python /path/to/adapters/langchain/smoke_test.py
7
+
8
+ It fails if a package it imports is the source tree and not an installed distribution:
9
+ a check run from the checkout would prove nothing about the wheels. A scripted model
10
+ proposes the calls; no provider, 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
+
22
+ # Python puts this script's directory first on the import path. Drop it, so nothing in
23
+ # the source tree can stand in for the installed package.
24
+ _HERE = Path(__file__).resolve().parent
25
+ sys.path[:] = [entry for entry in sys.path if Path(entry or ".").resolve() != _HERE]
26
+
27
+ import recusal_langchain # noqa: E402
28
+ import recusal_langgraph # noqa: E402
29
+ from langchain.agents import create_agent # noqa: E402
30
+ from langchain_core.language_models.fake_chat_models import GenericFakeChatModel # noqa: E402
31
+ from langchain_core.messages import AIMessage, HumanMessage, ToolMessage # noqa: E402
32
+ from langchain_core.tools import tool # noqa: E402
33
+ from recusal_langchain import ( # noqa: E402
34
+ SURFACE,
35
+ agate_middleware,
36
+ audited_gate_middleware,
37
+ gate_middleware,
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
+ INPUT = {"messages": [HumanMessage(content="go")]}
50
+
51
+
52
+ @tool
53
+ def run_sql(sql: str) -> str:
54
+ """Record SQL text without connecting to a database."""
55
+ EXECUTED.append(sql)
56
+ return f"recorded: {sql}"
57
+
58
+
59
+ def policy(tool_name, tool_input):
60
+ if str(tool_input.get("sql", "")).upper().startswith("DELETE"):
61
+ return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
62
+ return []
63
+
64
+
65
+ class ScriptedChatModel(GenericFakeChatModel):
66
+ """Offline response stream with a no-op tool binder; no provider is called."""
67
+
68
+ def bind_tools(self, tools, **kwargs): # type: ignore[override]
69
+ return self
70
+
71
+
72
+ def agent(middleware: list):
73
+ model = ScriptedChatModel(
74
+ messages=iter([AIMessage(content="", tool_calls=CALLS), AIMessage(content="done")])
75
+ )
76
+ return create_agent(model=model, tools=[run_sql], middleware=middleware)
77
+
78
+
79
+ def answers(result) -> dict[str, tuple[str, str]]:
80
+ return {
81
+ m.tool_call_id: (m.status, str(m.content))
82
+ for m in result["messages"]
83
+ if isinstance(m, ToolMessage)
84
+ }
85
+
86
+
87
+ def main() -> None:
88
+ for module in (recusal, recusal_langgraph, recusal_langchain):
89
+ origin = Path(module.__file__).resolve()
90
+ assert "site-packages" in origin.parts, f"{module.__name__} is not installed: {origin}"
91
+ assert metadata.version("recusal-langchain") == recusal_langchain.__version__
92
+ requires = metadata.requires("recusal-langchain") or []
93
+ assert any(r.startswith("recusal-langgraph") for r in requires), requires
94
+ assert any(r.startswith("recusal") and "lang" not in r for r in requires), requires
95
+
96
+ # Negative control: without the gate the DELETE runs, so the refusals below are the gate's.
97
+ EXECUTED.clear()
98
+ agent([]).invoke(INPUT)
99
+ assert sorted(EXECUTED) == ["DELETE FROM t", "SELECT 1"], EXECUTED
100
+
101
+ EXECUTED.clear()
102
+ got = answers(agent([gate_middleware(policy)]).invoke(INPUT))
103
+ assert EXECUTED == ["SELECT 1"], EXECUTED
104
+ assert got["c1"] == ("success", "recorded: SELECT 1"), got
105
+ assert got["c2"][0] == "error" and "DELETE is not allowed" in got["c2"][1], got
106
+
107
+ EXECUTED.clear()
108
+ got = answers(asyncio.run(agent([agate_middleware(policy)]).ainvoke(INPUT)))
109
+ assert EXECUTED == ["SELECT 1"], EXECUTED
110
+ assert got["c2"][0] == "error" and "DELETE is not allowed" in got["c2"][1], got
111
+
112
+ EXECUTED.clear()
113
+ with tempfile.TemporaryDirectory() as folder:
114
+ log = AuditLog(path=os.path.join(folder, "audit.jsonl"))
115
+ agent([audited_gate_middleware(policy, log)]).invoke(INPUT)
116
+ assert EXECUTED == ["SELECT 1"], EXECUTED
117
+ by_id = {entry["action"]["tool_use_id"]: entry["action"] for entry in log.entries}
118
+ assert by_id["c2"]["decision"] == "deny" and by_id["c2"]["surface"] == SURFACE, by_id
119
+ assert by_id["c1"]["decision"] != "deny", by_id
120
+ intact, problems = verify(log.entries)
121
+ assert intact, problems
122
+
123
+ print(
124
+ f"recusal-langchain {recusal_langchain.__version__} with recusal-langgraph "
125
+ f"{recusal_langgraph.__version__} and recusal {recusal.__version__}: "
126
+ "installed wheels gate and record"
127
+ )
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
@@ -0,0 +1,31 @@
1
+ """Recusal for LangChain ``create_agent``: judge every tool call before it runs.
2
+
3
+ from langchain.agents import create_agent
4
+ from recusal_langchain import gate_middleware
5
+
6
+ agent = create_agent(model=model, tools=[run_sql], middleware=[gate_middleware(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. ``agate_middleware`` is the form for ``agent.ainvoke``, and
11
+ ``audited_gate_middleware`` and ``audited_agate_middleware`` put each decision on a
12
+ hash-chained audit log. List the middleware last.
13
+
14
+ The gate is ``recusal-langgraph``'s ``ToolNode`` gate, and the decision is made by
15
+ ``recusal.decide``. This package adds only what is LangChain's: the middleware wrapper and
16
+ the surface label on the record.
17
+ """
18
+
19
+ from ._audit import SURFACE, audited_agate_middleware, audited_gate_middleware
20
+ from ._gate import agate_middleware, gate_middleware
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "SURFACE",
26
+ "__version__",
27
+ "agate_middleware",
28
+ "audited_agate_middleware",
29
+ "audited_gate_middleware",
30
+ "gate_middleware",
31
+ ]
@@ -0,0 +1,57 @@
1
+ """The audited middleware: the same decision, with every call on a hash-chained ``AuditLog``.
2
+
3
+ ``audited_gate_middleware(policy, log)`` and ``audited_agate_middleware(policy, log)`` wrap
4
+ the audited ``ToolNode`` hooks of ``recusal-langgraph``, which call the plain gate's own
5
+ judging function with the recording arguments passed through to ``recusal.decide``. There
6
+ is no second decision path. If the log cannot be written the decision becomes a deny, so
7
+ nothing runs unrecorded.
8
+
9
+ Each entry carries the surface ``langchain.create_agent`` and LangChain's tool call id, and
10
+ a SHA-256 fingerprint of the arguments, never the arguments themselves. It is bound to the
11
+ invocation the tool runs with, as the LangGraph audited gate binds it.
12
+
13
+ List the middleware LAST, as with the plain gate. The gate judges, and records, inside the
14
+ tool's own lifecycle, so an argument rewrite by a middleware listed after it is still
15
+ judged and recorded as rewritten; but a middleware listed after it that swaps the tool
16
+ object, or answers in the tool's place, removes the judging copy, and that call is neither
17
+ judged nor recorded.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any, Optional
23
+
24
+ from langchain.agents.middleware import wrap_tool_call
25
+ from recusal_langgraph import Policy, recusal_audited_agate, recusal_audited_gate
26
+
27
+ from recusal.audit import AuditLog
28
+
29
+ #: The surface label every entry carries: the runtime that adjudicated, a ``create_agent``
30
+ #: agent's tool-call middleware.
31
+ SURFACE = "langchain.create_agent"
32
+
33
+
34
+ def audited_gate_middleware(
35
+ policy: Policy,
36
+ log: AuditLog,
37
+ *,
38
+ actor: Optional[str] = None,
39
+ control: Optional[dict[str, Any]] = None,
40
+ ):
41
+ """The audited gate as create_agent middleware. List it LAST in ``middleware=``."""
42
+ return wrap_tool_call(
43
+ recusal_audited_gate(policy, log, actor=actor, control=control, surface=SURFACE)
44
+ )
45
+
46
+
47
+ def audited_agate_middleware(
48
+ policy: Policy,
49
+ log: AuditLog,
50
+ *,
51
+ actor: Optional[str] = None,
52
+ control: Optional[dict[str, Any]] = None,
53
+ ):
54
+ """The audited async gate for ``agent.ainvoke``. List it LAST."""
55
+ return wrap_tool_call(
56
+ recusal_audited_agate(policy, log, actor=actor, control=control, surface=SURFACE)
57
+ )
@@ -0,0 +1,28 @@
1
+ """The gate as ``create_agent`` middleware: the LangGraph ``ToolNode`` gate, wrapped.
2
+
3
+ A LangChain ``create_agent`` agent executes its tools through a LangGraph ``ToolNode``, and
4
+ its tool-call middleware is the same ``wrap_tool_call`` seam. This package therefore adds no
5
+ decision logic of its own: ``gate_middleware(policy)`` is ``recusal_langgraph.recusal_gate``
6
+ handed to LangChain's ``wrap_tool_call``. Everything that gate judges, completes and refuses
7
+ applies here unchanged.
8
+
9
+ List the middleware LAST in ``middleware=``. The first middleware in the list is the
10
+ outermost, so anything listed after the gate runs between the gate and the tool: a
11
+ middleware that swaps the tool object or answers in the tool's place would act on a call
12
+ the gate never saw. Listed last, the gate judges the call exactly as it will run.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from langchain.agents.middleware import wrap_tool_call
18
+ from recusal_langgraph import Policy, recusal_agate, recusal_gate
19
+
20
+
21
+ def gate_middleware(policy: Policy):
22
+ """The gate as ``create_agent`` middleware, for ``agent.invoke``. List it LAST."""
23
+ return wrap_tool_call(recusal_gate(policy))
24
+
25
+
26
+ def agate_middleware(policy: Policy):
27
+ """The async gate, for ``agent.ainvoke``; the sync gate alone raises there. List it LAST."""
28
+ return wrap_tool_call(recusal_agate(policy))
File without changes
@@ -0,0 +1,3 @@
1
+ langgraph==1.2.12
2
+ langchain-core==1.6.5
3
+ langchain==1.4.3