recusal-google-adk 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.
- recusal_google_adk-0.1.0/.gitignore +44 -0
- recusal_google_adk-0.1.0/LICENSE +201 -0
- recusal_google_adk-0.1.0/PKG-INFO +118 -0
- recusal_google_adk-0.1.0/README.md +92 -0
- recusal_google_adk-0.1.0/pyproject.toml +54 -0
- recusal_google_adk-0.1.0/smoke_test.py +152 -0
- recusal_google_adk-0.1.0/src/recusal_google_adk/__init__.py +41 -0
- recusal_google_adk-0.1.0/src/recusal_google_adk/_audit.py +81 -0
- recusal_google_adk-0.1.0/src/recusal_google_adk/_gate.py +359 -0
- recusal_google_adk-0.1.0/src/recusal_google_adk/py.typed +0 -0
- recusal_google_adk-0.1.0/tested-with.txt +2 -0
|
@@ -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,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: recusal-google-adk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Recusal gate for Google ADK: judge every tool call in a before-tool callback or a runner plugin, 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/google-adk
|
|
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,google-adk,guardrails,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.11
|
|
23
|
+
Requires-Dist: google-adk<3,>=2.13.0
|
|
24
|
+
Requires-Dist: recusal<1,>=0.14.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# recusal-google-adk
|
|
28
|
+
|
|
29
|
+
The [Recusal](https://github.com/philpaz/recusal) gate for
|
|
30
|
+
[Google ADK](https://google.github.io/adk-docs/): every tool call an agent proposes is
|
|
31
|
+
judged by your policy before the tool runs, and a refused call never runs.
|
|
32
|
+
|
|
33
|
+
This is a separate distribution from `recusal`. The kernel has zero runtime dependencies
|
|
34
|
+
and a frozen compatibility perimeter; this package carries the ADK dependency and its own
|
|
35
|
+
version, so an ADK release never forces a release of the kernel.
|
|
36
|
+
|
|
37
|
+
**Status: not yet published to PyPI.** Until it is, install it from the repository:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install "recusal-google-adk @ git+https://github.com/philpaz/recusal#subdirectory=adapters/google-adk"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Requires Python 3.11+ (the ADK's minimum), `recusal>=0.14.0` and `google-adk>=2.13.0`. It
|
|
44
|
+
is tested on every pull request against exactly `google-adk==2.13.0` with
|
|
45
|
+
`google-genai==2.34.0`, and weekly against the newest releases.
|
|
46
|
+
|
|
47
|
+
## Use
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from google.adk.agents import LlmAgent
|
|
51
|
+
from recusal import Finding
|
|
52
|
+
from recusal_google_adk import gated_agent
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def policy(tool_name, tool_input):
|
|
56
|
+
sql = tool_input.get("sql", "")
|
|
57
|
+
if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
|
|
58
|
+
return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
|
|
59
|
+
return []
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
agent = gated_agent(LlmAgent(name="assistant", model=model, tools=[run_sql]), policy)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`gated_agent` returns a copy of the agent with the gate appended as the last before-tool
|
|
66
|
+
callback, and gates its `sub_agents` and the agent behind every `AgentTool` the same way.
|
|
67
|
+
A refused call is answered to the model as `{"error": reason}`. The tool does not run. A
|
|
68
|
+
policy that raises refuses the call (fail closed).
|
|
69
|
+
|
|
70
|
+
The gate prepares the invocation the way the ADK will (defaults completed, values
|
|
71
|
+
validated), judges a detached copy, and the tool runs with exactly what was judged.
|
|
72
|
+
|
|
73
|
+
For an app whose agents you do not build yourself, `RecusalPlugin(policy)` is the same
|
|
74
|
+
gate as a runner plugin: `InMemoryRunner(agent, plugins=[RecusalPlugin(policy)])`. Plugin
|
|
75
|
+
callbacks run before any agent's own, so the plugin judges a call only when nothing it
|
|
76
|
+
cannot see runs after it. If the executing agent has another before-tool callback, or a
|
|
77
|
+
later plugin overrides `before_tool_callback`, it refuses the call and names the fix.
|
|
78
|
+
|
|
79
|
+
## Put every decision on the record
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from recusal.audit import AuditLog
|
|
83
|
+
from recusal_google_adk import audited_agent
|
|
84
|
+
|
|
85
|
+
log = AuditLog(path="decisions.jsonl")
|
|
86
|
+
agent = audited_agent(LlmAgent(name="assistant", model=model, tools=[run_sql]), policy, log)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`audited_plugin(policy, log)` is the plugin form. Each call a gate sees, allowed or
|
|
90
|
+
refused, is one hash-chained entry labeled `google_adk.before_tool_callback` with the
|
|
91
|
+
ADK's function call id and a SHA-256 fingerprint of the arguments (never the arguments).
|
|
92
|
+
If the log cannot be written the call is refused. Check the log with
|
|
93
|
+
`recusal audit verify decisions.jsonl`.
|
|
94
|
+
|
|
95
|
+
The audited forms are the plain ones with a recording passed in, so there is one decision
|
|
96
|
+
path.
|
|
97
|
+
|
|
98
|
+
## What the gate refuses, and what it does not see
|
|
99
|
+
|
|
100
|
+
- **`gated_agent` raises at construction** for an agent that can run something the
|
|
101
|
+
callback never sees: an agent with a `code_executor` (model-written code runs outside
|
|
102
|
+
the tool path), an `LlmAgent` subclass, or an agent class it does not know how to gate.
|
|
103
|
+
- **Refused before the policy runs:** a tool that is not a stock `FunctionTool`, a
|
|
104
|
+
signature that cannot be judged by name, an unknown or missing parameter, and arguments
|
|
105
|
+
that do not validate.
|
|
106
|
+
- **Not on the audit log:** a call another before-tool callback answered before the gate
|
|
107
|
+
ran. The tool did not run either.
|
|
108
|
+
|
|
109
|
+
## Compatibility
|
|
110
|
+
|
|
111
|
+
This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
|
|
112
|
+
public names are the ones in `recusal_google_adk.__all__`. When an ADK release changes
|
|
113
|
+
what the callback is handed, this package gets a release and the kernel does not.
|
|
114
|
+
|
|
115
|
+
A runnable offline demonstration, with a scripted model and no API key, is
|
|
116
|
+
[`examples/google_adk_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/google_adk_gate.py)
|
|
117
|
+
and
|
|
118
|
+
[`examples/google_adk_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/google_adk_audit.py).
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# recusal-google-adk
|
|
2
|
+
|
|
3
|
+
The [Recusal](https://github.com/philpaz/recusal) gate for
|
|
4
|
+
[Google ADK](https://google.github.io/adk-docs/): every tool call an agent proposes is
|
|
5
|
+
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 ADK dependency and its own
|
|
9
|
+
version, so an ADK 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-google-adk @ git+https://github.com/philpaz/recusal#subdirectory=adapters/google-adk"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Requires Python 3.11+ (the ADK's minimum), `recusal>=0.14.0` and `google-adk>=2.13.0`. It
|
|
18
|
+
is tested on every pull request against exactly `google-adk==2.13.0` with
|
|
19
|
+
`google-genai==2.34.0`, and weekly against the newest releases.
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from google.adk.agents import LlmAgent
|
|
25
|
+
from recusal import Finding
|
|
26
|
+
from recusal_google_adk import gated_agent
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def policy(tool_name, tool_input):
|
|
30
|
+
sql = tool_input.get("sql", "")
|
|
31
|
+
if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
|
|
32
|
+
return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
|
|
33
|
+
return []
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
agent = gated_agent(LlmAgent(name="assistant", model=model, tools=[run_sql]), policy)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`gated_agent` returns a copy of the agent with the gate appended as the last before-tool
|
|
40
|
+
callback, and gates its `sub_agents` and the agent behind every `AgentTool` the same way.
|
|
41
|
+
A refused call is answered to the model as `{"error": reason}`. The tool does not run. A
|
|
42
|
+
policy that raises refuses the call (fail closed).
|
|
43
|
+
|
|
44
|
+
The gate prepares the invocation the way the ADK will (defaults completed, values
|
|
45
|
+
validated), judges a detached copy, and the tool runs with exactly what was judged.
|
|
46
|
+
|
|
47
|
+
For an app whose agents you do not build yourself, `RecusalPlugin(policy)` is the same
|
|
48
|
+
gate as a runner plugin: `InMemoryRunner(agent, plugins=[RecusalPlugin(policy)])`. Plugin
|
|
49
|
+
callbacks run before any agent's own, so the plugin judges a call only when nothing it
|
|
50
|
+
cannot see runs after it. If the executing agent has another before-tool callback, or a
|
|
51
|
+
later plugin overrides `before_tool_callback`, it refuses the call and names the fix.
|
|
52
|
+
|
|
53
|
+
## Put every decision on the record
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from recusal.audit import AuditLog
|
|
57
|
+
from recusal_google_adk import audited_agent
|
|
58
|
+
|
|
59
|
+
log = AuditLog(path="decisions.jsonl")
|
|
60
|
+
agent = audited_agent(LlmAgent(name="assistant", model=model, tools=[run_sql]), policy, log)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`audited_plugin(policy, log)` is the plugin form. Each call a gate sees, allowed or
|
|
64
|
+
refused, is one hash-chained entry labeled `google_adk.before_tool_callback` with the
|
|
65
|
+
ADK's function call id and a SHA-256 fingerprint of the arguments (never the arguments).
|
|
66
|
+
If the log cannot be written the call is refused. Check the log with
|
|
67
|
+
`recusal audit verify decisions.jsonl`.
|
|
68
|
+
|
|
69
|
+
The audited forms are the plain ones with a recording passed in, so there is one decision
|
|
70
|
+
path.
|
|
71
|
+
|
|
72
|
+
## What the gate refuses, and what it does not see
|
|
73
|
+
|
|
74
|
+
- **`gated_agent` raises at construction** for an agent that can run something the
|
|
75
|
+
callback never sees: an agent with a `code_executor` (model-written code runs outside
|
|
76
|
+
the tool path), an `LlmAgent` subclass, or an agent class it does not know how to gate.
|
|
77
|
+
- **Refused before the policy runs:** a tool that is not a stock `FunctionTool`, a
|
|
78
|
+
signature that cannot be judged by name, an unknown or missing parameter, and arguments
|
|
79
|
+
that do not validate.
|
|
80
|
+
- **Not on the audit log:** a call another before-tool callback answered before the gate
|
|
81
|
+
ran. The tool did not run either.
|
|
82
|
+
|
|
83
|
+
## Compatibility
|
|
84
|
+
|
|
85
|
+
This package is outside the kernel's frozen perimeter (`STABILITY.md`, Integrations). Its
|
|
86
|
+
public names are the ones in `recusal_google_adk.__all__`. When an ADK release changes
|
|
87
|
+
what the callback is handed, this package gets a release and the kernel does not.
|
|
88
|
+
|
|
89
|
+
A runnable offline demonstration, with a scripted model and no API key, is
|
|
90
|
+
[`examples/google_adk_gate.py`](https://github.com/philpaz/recusal/blob/main/examples/google_adk_gate.py)
|
|
91
|
+
and
|
|
92
|
+
[`examples/google_adk_audit.py`](https://github.com/philpaz/recusal/blob/main/examples/google_adk_audit.py).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# The Recusal adapter for Google ADK, 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-google-adk"
|
|
16
|
+
dynamic = ["version"]
|
|
17
|
+
description = "Recusal gate for Google ADK: judge every tool call in a before-tool callback or a runner plugin, refuse before it runs, and optionally put each decision on a hash-chained audit log."
|
|
18
|
+
readme = "README.md"
|
|
19
|
+
# The ADK's own minimum.
|
|
20
|
+
requires-python = ">=3.11"
|
|
21
|
+
license = "Apache-2.0"
|
|
22
|
+
license-files = ["LICENSE"]
|
|
23
|
+
authors = [{ name = "Philip Paz", email = "philip.paz@gmail.com" }]
|
|
24
|
+
keywords = ["recusal", "google-adk", "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
|
+
"google-adk>=2.13.0,<3",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[project.urls]
|
|
44
|
+
Homepage = "https://github.com/philpaz/recusal"
|
|
45
|
+
Documentation = "https://github.com/philpaz/recusal/tree/main/adapters/google-adk"
|
|
46
|
+
Repository = "https://github.com/philpaz/recusal"
|
|
47
|
+
Issues = "https://github.com/philpaz/recusal/issues"
|
|
48
|
+
Changelog = "https://github.com/philpaz/recusal/blob/main/CHANGELOG.md"
|
|
49
|
+
|
|
50
|
+
[tool.hatch.version]
|
|
51
|
+
path = "src/recusal_google_adk/__init__.py"
|
|
52
|
+
|
|
53
|
+
[tool.hatch.build.targets.wheel]
|
|
54
|
+
packages = ["src/recusal_google_adk"]
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Prove the INSTALLED recusal-google-adk wheel gates a real Google ADK agent.
|
|
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/google-adk/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. No model, API key or
|
|
10
|
+
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, AsyncGenerator
|
|
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_google_adk # noqa: E402
|
|
29
|
+
from google.adk.agents import LlmAgent # noqa: E402
|
|
30
|
+
from google.adk.models import BaseLlm, LlmRequest, LlmResponse # noqa: E402
|
|
31
|
+
from google.adk.runners import InMemoryRunner # noqa: E402
|
|
32
|
+
from google.adk.tools import FunctionTool # noqa: E402
|
|
33
|
+
from google.genai import types # noqa: E402
|
|
34
|
+
from recusal_google_adk import ( # noqa: E402
|
|
35
|
+
SURFACE,
|
|
36
|
+
RecusalPlugin,
|
|
37
|
+
audited_agent,
|
|
38
|
+
audited_plugin,
|
|
39
|
+
gated_agent,
|
|
40
|
+
is_gated,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
import recusal # noqa: E402
|
|
44
|
+
from recusal import Finding # noqa: E402
|
|
45
|
+
from recusal.audit import AuditLog, verify # noqa: E402
|
|
46
|
+
|
|
47
|
+
EXECUTED: list[str] = []
|
|
48
|
+
CALLS = [("c1", "SELECT 1"), ("c2", "DELETE FROM t")]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run_sql(sql: str) -> str:
|
|
52
|
+
"""Record SQL text without connecting to a database."""
|
|
53
|
+
EXECUTED.append(sql)
|
|
54
|
+
return f"recorded: {sql}"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def policy(tool_name, tool_input):
|
|
58
|
+
if str(tool_input.get("sql", "")).upper().startswith("DELETE"):
|
|
59
|
+
return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
|
|
60
|
+
return []
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ScriptedLlm(BaseLlm):
|
|
64
|
+
"""Proposes the scripted calls on its first turn, then answers "done"."""
|
|
65
|
+
|
|
66
|
+
turns: int = 0
|
|
67
|
+
|
|
68
|
+
async def generate_content_async(
|
|
69
|
+
self, llm_request: LlmRequest, stream: bool = False
|
|
70
|
+
) -> AsyncGenerator[LlmResponse, None]:
|
|
71
|
+
self.turns += 1
|
|
72
|
+
if self.turns == 1:
|
|
73
|
+
parts = [
|
|
74
|
+
types.Part(
|
|
75
|
+
function_call=types.FunctionCall(id=ident, name="run_sql", args={"sql": sql})
|
|
76
|
+
)
|
|
77
|
+
for ident, sql in CALLS
|
|
78
|
+
]
|
|
79
|
+
else:
|
|
80
|
+
parts = [types.Part(text="done")]
|
|
81
|
+
yield LlmResponse(content=types.Content(role="model", parts=parts))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def agent() -> LlmAgent:
|
|
85
|
+
return LlmAgent(
|
|
86
|
+
name="assistant", model=ScriptedLlm(model="scripted"), tools=[FunctionTool(run_sql)]
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def _run(target: Any, plugins: Any) -> dict[str, Any]:
|
|
91
|
+
runner = InMemoryRunner(agent=target, app_name="smoke", plugins=plugins)
|
|
92
|
+
session = await runner.session_service.create_session(app_name="smoke", user_id="user")
|
|
93
|
+
message = types.Content(role="user", parts=[types.Part(text="go")])
|
|
94
|
+
responses: dict[str, Any] = {}
|
|
95
|
+
async for event in runner.run_async(user_id="user", session_id=session.id, new_message=message):
|
|
96
|
+
for part in event.content.parts if event.content and event.content.parts else []:
|
|
97
|
+
if part.function_response is not None:
|
|
98
|
+
responses[part.function_response.id] = part.function_response.response
|
|
99
|
+
return responses
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def run(target: Any, plugins: Any = None) -> dict[str, Any]:
|
|
103
|
+
EXECUTED.clear()
|
|
104
|
+
return asyncio.run(_run(target, plugins))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def main() -> None:
|
|
108
|
+
for module in (recusal, recusal_google_adk):
|
|
109
|
+
origin = Path(module.__file__).resolve()
|
|
110
|
+
assert "site-packages" in origin.parts, f"{module.__name__} is not installed: {origin}"
|
|
111
|
+
assert metadata.version("recusal-google-adk") == recusal_google_adk.__version__
|
|
112
|
+
requires = metadata.requires("recusal-google-adk") or []
|
|
113
|
+
assert any(r.startswith("recusal") and "google" not in r for r in requires), requires
|
|
114
|
+
|
|
115
|
+
# Negative control: without the gate the DELETE runs, so the refusals below are the gate's.
|
|
116
|
+
assert not is_gated(agent())
|
|
117
|
+
run(agent())
|
|
118
|
+
assert sorted(EXECUTED) == ["DELETE FROM t", "SELECT 1"], EXECUTED
|
|
119
|
+
|
|
120
|
+
gated = gated_agent(agent(), policy)
|
|
121
|
+
assert is_gated(gated)
|
|
122
|
+
answers = run(gated)
|
|
123
|
+
assert EXECUTED == ["SELECT 1"], EXECUTED
|
|
124
|
+
assert "DELETE is not allowed" in answers["c2"]["error"], answers
|
|
125
|
+
assert "error" not in answers["c1"], answers
|
|
126
|
+
|
|
127
|
+
answers = run(agent(), plugins=[RecusalPlugin(policy)])
|
|
128
|
+
assert EXECUTED == ["SELECT 1"], EXECUTED
|
|
129
|
+
assert "DELETE is not allowed" in answers["c2"]["error"], answers
|
|
130
|
+
|
|
131
|
+
for via_plugin in (False, True):
|
|
132
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
133
|
+
log = AuditLog(path=os.path.join(folder, "audit.jsonl"))
|
|
134
|
+
if via_plugin:
|
|
135
|
+
run(agent(), plugins=[audited_plugin(policy, log)])
|
|
136
|
+
else:
|
|
137
|
+
run(audited_agent(agent(), policy, log))
|
|
138
|
+
assert EXECUTED == ["SELECT 1"], EXECUTED
|
|
139
|
+
by_id = {entry["action"]["tool_use_id"]: entry["action"] for entry in log.entries}
|
|
140
|
+
assert by_id["c2"]["decision"] == "deny" and by_id["c2"]["surface"] == SURFACE, by_id
|
|
141
|
+
assert by_id["c1"]["decision"] != "deny", by_id
|
|
142
|
+
intact, problems = verify(log.entries)
|
|
143
|
+
assert intact, problems
|
|
144
|
+
|
|
145
|
+
print(
|
|
146
|
+
f"recusal-google-adk {recusal_google_adk.__version__} with recusal "
|
|
147
|
+
f"{recusal.__version__}: installed wheel gates and records"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
if __name__ == "__main__":
|
|
152
|
+
main()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Recusal for Google ADK: judge every tool call before it runs.
|
|
2
|
+
|
|
3
|
+
from google.adk.agents import LlmAgent
|
|
4
|
+
from recusal_google_adk import gated_agent
|
|
5
|
+
|
|
6
|
+
agent = gated_agent(LlmAgent(name="assistant", model=model, tools=[run_sql]), policy)
|
|
7
|
+
|
|
8
|
+
``policy(tool_name, tool_input)`` is an ordinary Recusal policy returning findings. A
|
|
9
|
+
refused call is answered to the model as ``{"error": reason}`` and its tool does not run.
|
|
10
|
+
``RecusalPlugin(policy)`` is the same gate for every agent a runner drives, and
|
|
11
|
+
``audited_agent`` and ``audited_plugin`` put each decision on a hash-chained audit log.
|
|
12
|
+
|
|
13
|
+
The decision is made by ``recusal.decide``. This package adds only what is the ADK's:
|
|
14
|
+
where the callback attaches, how the invocation is prepared, and how a refusal is answered.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from ._audit import SURFACE, audited_agent, audited_plugin, recording
|
|
18
|
+
from ._gate import (
|
|
19
|
+
Policy,
|
|
20
|
+
Recording,
|
|
21
|
+
RecusalPlugin,
|
|
22
|
+
gated_agent,
|
|
23
|
+
is_gated,
|
|
24
|
+
recusal_before_tool,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"SURFACE",
|
|
31
|
+
"Policy",
|
|
32
|
+
"Recording",
|
|
33
|
+
"RecusalPlugin",
|
|
34
|
+
"__version__",
|
|
35
|
+
"audited_agent",
|
|
36
|
+
"audited_plugin",
|
|
37
|
+
"gated_agent",
|
|
38
|
+
"is_gated",
|
|
39
|
+
"recording",
|
|
40
|
+
"recusal_before_tool",
|
|
41
|
+
]
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""The audited gate: the same decision, with every call on a hash-chained ``AuditLog``.
|
|
2
|
+
|
|
3
|
+
``audited_agent(agent, policy, log)`` and ``audited_plugin(policy, log)`` are
|
|
4
|
+
``gated_agent`` and ``RecusalPlugin`` with a ``recording`` that hands the plain gate's own
|
|
5
|
+
refusal function the arguments ``recusal.decide`` records with. There is no second
|
|
6
|
+
decision path. If the log cannot be written, or the recording raises, the call is refused,
|
|
7
|
+
so nothing runs unrecorded.
|
|
8
|
+
|
|
9
|
+
Each entry carries the surface ``google_adk.before_tool_callback`` and the ADK's function
|
|
10
|
+
call id, and a SHA-256 fingerprint of the arguments, never the arguments themselves.
|
|
11
|
+
|
|
12
|
+
What each entry is bound to:
|
|
13
|
+
|
|
14
|
+
- a call that is judged: the prepared invocation the tool is called with, defaults
|
|
15
|
+
completed and values validated;
|
|
16
|
+
- a call refused before judgment (a tool that is not a stock ``FunctionTool``, a signature
|
|
17
|
+
the gate cannot judge, arguments that do not validate, a plugin that is not the last
|
|
18
|
+
before-tool seam): the arguments as proposed.
|
|
19
|
+
|
|
20
|
+
What is not on the log: a call another before-tool callback answered before the gate ran
|
|
21
|
+
(the tool did not run either), and anything ``gated_agent`` refuses to gate at
|
|
22
|
+
construction, which raises before any agent exists.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from typing import Any, Optional
|
|
28
|
+
|
|
29
|
+
from google.adk.agents import BaseAgent
|
|
30
|
+
|
|
31
|
+
from recusal.audit import AuditLog
|
|
32
|
+
|
|
33
|
+
from ._gate import Policy, Recording, RecusalPlugin, gated_agent
|
|
34
|
+
|
|
35
|
+
#: The surface label every entry carries: the ADK hook that adjudicated.
|
|
36
|
+
SURFACE = "google_adk.before_tool_callback"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def recording(
|
|
40
|
+
log: AuditLog, *, actor: Optional[str] = None, control: Optional[dict[str, Any]] = None
|
|
41
|
+
) -> Recording:
|
|
42
|
+
"""The recording arguments for each call, built in one place for both forms of the gate.
|
|
43
|
+
|
|
44
|
+
The ADK gives every function call an id (it generates one when the model sends none);
|
|
45
|
+
a blank id is recorded as no id rather than refused."""
|
|
46
|
+
|
|
47
|
+
def for_call(tool_context: Any) -> dict[str, Any]:
|
|
48
|
+
ident = getattr(tool_context, "function_call_id", None)
|
|
49
|
+
return {
|
|
50
|
+
"audit": log,
|
|
51
|
+
"surface": SURFACE,
|
|
52
|
+
"tool_use_id": ident if isinstance(ident, str) and ident else None,
|
|
53
|
+
"actor": actor,
|
|
54
|
+
"control": control,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return for_call
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def audited_agent(
|
|
61
|
+
agent: BaseAgent,
|
|
62
|
+
policy: Policy,
|
|
63
|
+
log: AuditLog,
|
|
64
|
+
*,
|
|
65
|
+
actor: Optional[str] = None,
|
|
66
|
+
control: Optional[dict[str, Any]] = None,
|
|
67
|
+
) -> BaseAgent:
|
|
68
|
+
"""``gated_agent`` with every decision, of the agent and of every agent under it, on
|
|
69
|
+
``log``."""
|
|
70
|
+
return gated_agent(agent, policy, recording(log, actor=actor, control=control))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def audited_plugin(
|
|
74
|
+
policy: Policy,
|
|
75
|
+
log: AuditLog,
|
|
76
|
+
*,
|
|
77
|
+
actor: Optional[str] = None,
|
|
78
|
+
control: Optional[dict[str, Any]] = None,
|
|
79
|
+
) -> RecusalPlugin:
|
|
80
|
+
"""``RecusalPlugin`` with every decision on ``log``; list it last, as with the plain one."""
|
|
81
|
+
return RecusalPlugin(policy, recording=recording(log, actor=actor, control=control))
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""The gate: one refusal function, and the two ways to attach it to a Google ADK agent.
|
|
2
|
+
|
|
3
|
+
The hook is the ADK's own. An ``LlmAgent`` runs its ``before_tool_callback`` immediately
|
|
4
|
+
before each tool call, with the tool, the arguments the tool will receive and the tool
|
|
5
|
+
context; a callback that returns a dict answers the call instead of running the tool.
|
|
6
|
+
``recusal_before_tool(policy)`` judges the call with ``recusal.decide`` and, on a refusal,
|
|
7
|
+
returns ``{"error": reason}`` so the model reads Recusal's reason on its next turn and the
|
|
8
|
+
tool never runs. Every call in a model turn is judged separately.
|
|
9
|
+
|
|
10
|
+
Two ways to attach it:
|
|
11
|
+
|
|
12
|
+
- ``gated_agent(agent, policy)`` returns a copy of the agent with the gate appended as the
|
|
13
|
+
LAST before-tool callback, and gates its ``sub_agents`` and the agent behind every
|
|
14
|
+
``AgentTool`` the same way. Last, because callbacks run in order and a callback listed
|
|
15
|
+
after the gate could change the arguments the gate judged; a callback listed before it
|
|
16
|
+
that answers the call itself means the tool did not run.
|
|
17
|
+
- ``RecusalPlugin(policy)`` is the same gate as a runner plugin, for every agent the runner
|
|
18
|
+
drives. Plugin callbacks run before any agent's callbacks, so the plugin cannot be placed
|
|
19
|
+
after an agent's own ``before_tool_callback``, which could change the arguments the
|
|
20
|
+
plugin judged. Its contract is therefore explicit: it judges a call only when nothing it
|
|
21
|
+
cannot see runs after it, that is, when the executing agent carries no before-tool
|
|
22
|
+
callback other than a Recusal gate and no plugin listed after it overrides
|
|
23
|
+
``before_tool_callback``; otherwise it refuses the call, naming the callback or plugin,
|
|
24
|
+
and the fix. A call whose invocation context does not expose the executing agent is
|
|
25
|
+
refused too.
|
|
26
|
+
|
|
27
|
+
What the callback cannot see, so ``gated_agent`` refuses rather than skips it:
|
|
28
|
+
|
|
29
|
+
- a ``code_executor`` on the agent: model-written code runs outside the tool path;
|
|
30
|
+
- a ``sub_agent`` or an ``AgentTool`` whose agent is not itself gated: its tool calls run
|
|
31
|
+
under its own callbacks, not the parent's (``gated_agent`` gates them recursively, and
|
|
32
|
+
refuses an agent class it does not know how to gate);
|
|
33
|
+
- an ``LlmAgent`` subclass: it can add behavior the gate was not written for.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import copy
|
|
39
|
+
import inspect
|
|
40
|
+
from typing import Any, Callable, List, Optional
|
|
41
|
+
|
|
42
|
+
from google.adk.agents import BaseAgent, LlmAgent
|
|
43
|
+
from google.adk.agents.loop_agent import LoopAgent
|
|
44
|
+
from google.adk.agents.parallel_agent import ParallelAgent
|
|
45
|
+
from google.adk.agents.sequential_agent import SequentialAgent
|
|
46
|
+
from google.adk.plugins import BasePlugin
|
|
47
|
+
from google.adk.tools import AgentTool, BaseTool, FunctionTool, ToolContext
|
|
48
|
+
|
|
49
|
+
from recusal import Finding, decide
|
|
50
|
+
from recusal.invocation import unsupported_signature as _unsupported_signature
|
|
51
|
+
|
|
52
|
+
#: A Recusal policy: ``policy(tool_name, tool_input)`` returns a list of findings.
|
|
53
|
+
Policy = Callable[[str, dict], List[Any]]
|
|
54
|
+
#: Given the call's ``ToolContext``, the recording arguments ``decide`` takes for it
|
|
55
|
+
#: (``audit=``, ``surface=``, ``tool_use_id=``, ...). ``recusal_google_adk.recording``
|
|
56
|
+
#: builds one.
|
|
57
|
+
Recording = Callable[[Any], dict]
|
|
58
|
+
|
|
59
|
+
#: Workflow agents run no tools of their own; their ``sub_agents`` do. ``gated_agent``
|
|
60
|
+
#: gates those and leaves the workflow agent's own class alone.
|
|
61
|
+
_WORKFLOW_AGENTS = (SequentialAgent, ParallelAgent, LoopAgent)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
#: The FunctionTool methods that prepare and run an invocation. A tool class is supported
|
|
65
|
+
#: only while every one of them is FunctionTool's own (the ADK's built-in subclasses such as
|
|
66
|
+
#: transfer_to_agent inherit them; a user subclass that overrides preprocessing is refused).
|
|
67
|
+
_STOCK_LIFECYCLE = (
|
|
68
|
+
"_preprocess_args",
|
|
69
|
+
"_preprocess_args_with_validation",
|
|
70
|
+
"_validate_args",
|
|
71
|
+
"run_async",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _prepared(tool: Any, args: dict[str, Any]) -> tuple[Optional[dict[str, Any]], Optional[str]]:
|
|
76
|
+
"""Prepare the invocation the tool will execute, in place, and return a detached copy
|
|
77
|
+
for judgment; or ``(None, reason)`` when it cannot be prepared faithfully.
|
|
78
|
+
|
|
79
|
+
Supported: a ``google.adk.tools.FunctionTool`` whose class keeps FunctionTool's own
|
|
80
|
+
preparation and run methods (``_STOCK_LIFECYCLE``; the ADK's built-in subclasses do, a
|
|
81
|
+
user subclass that overrides preprocessing does not) and whose parameters, outside the
|
|
82
|
+
ones the ADK injects (``_ignore_params``),
|
|
83
|
+
all carry a supported data annotation and JSON defaults. Omitted parameters are completed
|
|
84
|
+
from the signature's defaults INTO the raw arguments first, then the tool's own
|
|
85
|
+
``_preprocess_args_with_validation`` runs once, so a default such as ``int = "100"`` is
|
|
86
|
+
prepared exactly as explicit input would be; the converted values are written back into
|
|
87
|
+
``args`` (the ADK calls the tool with this dict) and the policy judges a deep copy. On
|
|
88
|
+
the supported set the ADK's execution-time preparation returns equal values, with the
|
|
89
|
+
validation feature on (coercion) or off (none), so judged equals received. A validation
|
|
90
|
+
failure is refused as such, without the SDK's text, which carries input values.
|
|
91
|
+
"""
|
|
92
|
+
if not isinstance(tool, FunctionTool):
|
|
93
|
+
return (
|
|
94
|
+
None,
|
|
95
|
+
f"only a google.adk.tools.FunctionTool can be judged, not {type(tool).__name__}",
|
|
96
|
+
)
|
|
97
|
+
for method in _STOCK_LIFECYCLE:
|
|
98
|
+
if getattr(type(tool), method) is not getattr(FunctionTool, method):
|
|
99
|
+
return (
|
|
100
|
+
None,
|
|
101
|
+
f"{type(tool).__name__} overrides FunctionTool.{method}, so its preparation "
|
|
102
|
+
"is not the stock one",
|
|
103
|
+
)
|
|
104
|
+
func = tool.func
|
|
105
|
+
skip = tuple(getattr(tool, "_ignore_params", ()) or ())
|
|
106
|
+
why = _unsupported_signature(func, skip)
|
|
107
|
+
if why is not None:
|
|
108
|
+
return None, f"its signature cannot be judged ({why})"
|
|
109
|
+
parameters = inspect.signature(func).parameters
|
|
110
|
+
raw: dict[str, Any] = {}
|
|
111
|
+
for name, parameter in parameters.items():
|
|
112
|
+
if name in skip or name in args:
|
|
113
|
+
continue
|
|
114
|
+
if parameter.default is parameter.empty:
|
|
115
|
+
return None, f"required parameter `{name}` was not supplied"
|
|
116
|
+
raw[name] = copy.deepcopy(parameter.default)
|
|
117
|
+
unknown = sorted(k for k in args if k not in parameters)
|
|
118
|
+
if unknown:
|
|
119
|
+
return None, f"unknown parameter(s) {unknown!r}"
|
|
120
|
+
raw.update(args)
|
|
121
|
+
converted, errors = tool._preprocess_args_with_validation(raw)
|
|
122
|
+
if errors:
|
|
123
|
+
return None, f"{len(errors)} argument(s) do not validate against the tool's parameters"
|
|
124
|
+
args.clear()
|
|
125
|
+
args.update(converted)
|
|
126
|
+
return copy.deepcopy(converted), None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _unjudgeable(tool_name: str, detail: str, proposal: Any, record: dict) -> str:
|
|
130
|
+
"""The reason for a call the gate refuses before any policy runs.
|
|
131
|
+
|
|
132
|
+
Without recording arguments it is the plain text. With them
|
|
133
|
+
(the audited gate) the refusal goes through ``decide`` like every other, so
|
|
134
|
+
it is one entry on the log, bound to the arguments as the model proposed them, and the
|
|
135
|
+
reason the model reads is the one on the record.
|
|
136
|
+
"""
|
|
137
|
+
if not record:
|
|
138
|
+
return f"Recusal refused `{tool_name}`: {detail}"
|
|
139
|
+
bound = proposal if isinstance(proposal, dict) else {"input": proposal}
|
|
140
|
+
|
|
141
|
+
def unjudgeable(_name, _input):
|
|
142
|
+
return [Finding.fail("recusal_unjudgeable_input", severity="CRITICAL", message=detail)]
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
_, reason = decide(tool_name, bound, unjudgeable, safe_errors=True, **record)
|
|
146
|
+
except Exception as exc: # noqa: BLE001, the refusal stands even if the record cannot be written
|
|
147
|
+
return f"Recusal failed closed (policy error): RECUSAL_POLICY_ERROR ({type(exc).__name__})"
|
|
148
|
+
return reason
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _record_for(recording: Optional[Recording], tool_context: Any) -> dict:
|
|
152
|
+
"""The recording arguments for this call, or none when the gate keeps no record."""
|
|
153
|
+
return dict(recording(tool_context)) if recording is not None else {}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _refusal(tool: Any, args: Any, policy: Policy, **record: Any) -> Optional[str]:
|
|
157
|
+
"""Return the reason a call is refused, or None to run it.
|
|
158
|
+
|
|
159
|
+
The ADK hands the callback the same ``args`` dict the tool will be called with; the
|
|
160
|
+
invocation is prepared in place (:func:`_prepared`) and the policy judges a detached
|
|
161
|
+
copy of exactly what will run. A non-dict is refused: the tool would not accept it
|
|
162
|
+
either, and the policy cannot read it.
|
|
163
|
+
|
|
164
|
+
``record`` goes straight to ``decide``, so a gate that puts the decision on a log
|
|
165
|
+
(``audited_agent``, ``audited_plugin``) decides, and refuses, exactly as this one does. The
|
|
166
|
+
entry for a judged call carries the fingerprint of the prepared invocation the tool
|
|
167
|
+
is called with; a call refused before judgment is bound to the arguments as proposed
|
|
168
|
+
(:func:`_prepared` changes ``args`` only when it succeeds).
|
|
169
|
+
"""
|
|
170
|
+
tool_name = getattr(tool, "name", "?")
|
|
171
|
+
if not isinstance(args, dict):
|
|
172
|
+
return _unjudgeable(tool_name, "arguments are not a mapping", args, record)
|
|
173
|
+
try:
|
|
174
|
+
invocation, why = _prepared(tool, args)
|
|
175
|
+
except Exception as exc: # noqa: BLE001, a preparation the gate cannot complete is refused
|
|
176
|
+
return _unjudgeable(
|
|
177
|
+
tool_name, f"the invocation cannot be prepared ({type(exc).__name__})", args, record
|
|
178
|
+
)
|
|
179
|
+
if invocation is None:
|
|
180
|
+
return _unjudgeable(tool_name, str(why), args, record)
|
|
181
|
+
try:
|
|
182
|
+
decision, reason = decide(tool_name, invocation, policy, safe_errors=True, **record)
|
|
183
|
+
except Exception as exc: # noqa: BLE001, a buggy policy must not silently disable the gate
|
|
184
|
+
return f"Recusal failed closed (policy error): RECUSAL_POLICY_ERROR ({type(exc).__name__})"
|
|
185
|
+
return reason if decision == "deny" else None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def recusal_before_tool(policy: Policy, recording: Optional[Recording] = None):
|
|
189
|
+
"""Return a ``before_tool_callback`` that judges each tool call before it runs.
|
|
190
|
+
|
|
191
|
+
A refusal is returned as the tool's response, ``{"error": reason}``, so the model sees
|
|
192
|
+
why on its next turn; ``None`` lets the ADK run the tool. ``recording`` puts every
|
|
193
|
+
decision on an audit log (``recusal_google_adk.recording``).
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def gate(tool: BaseTool, args: dict[str, Any], tool_context: ToolContext):
|
|
197
|
+
try:
|
|
198
|
+
record = _record_for(recording, tool_context)
|
|
199
|
+
except Exception as exc: # noqa: BLE001, a gate that cannot record must not run the call
|
|
200
|
+
return {
|
|
201
|
+
"error": "Recusal failed closed (policy error): "
|
|
202
|
+
f"RECUSAL_POLICY_ERROR ({type(exc).__name__})"
|
|
203
|
+
}
|
|
204
|
+
reason = _refusal(tool, args, policy, **record)
|
|
205
|
+
if reason is not None:
|
|
206
|
+
return {"error": reason}
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
gate.recusal_gate = True # type: ignore[attr-defined]
|
|
210
|
+
return gate
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class RecusalPlugin(BasePlugin):
|
|
214
|
+
"""The same gate as a runner plugin: every agent the runner drives.
|
|
215
|
+
``InMemoryRunner(agent, plugins=[..., RecusalPlugin(policy)])``.
|
|
216
|
+
|
|
217
|
+
Plugin callbacks run before any agent's before-tool callbacks, and plugins run in list
|
|
218
|
+
order, so the plugin judges a call only when nothing that could change the arguments
|
|
219
|
+
runs after it (``_ordering_reason``); otherwise it refuses the call before judgment.
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
def __init__(
|
|
223
|
+
self, policy: Policy, name: str = "recusal", recording: Optional[Recording] = None
|
|
224
|
+
):
|
|
225
|
+
super().__init__(name=name)
|
|
226
|
+
self._policy = policy
|
|
227
|
+
self._recording = recording
|
|
228
|
+
|
|
229
|
+
async def before_tool_callback(
|
|
230
|
+
self, *, tool: BaseTool, tool_args: dict[str, Any], tool_context: ToolContext
|
|
231
|
+
) -> Optional[dict[str, Any]]:
|
|
232
|
+
try:
|
|
233
|
+
record = _record_for(self._recording, tool_context)
|
|
234
|
+
except Exception as exc: # noqa: BLE001, a gate that cannot record must not run the call
|
|
235
|
+
return {
|
|
236
|
+
"error": "Recusal failed closed (policy error): "
|
|
237
|
+
f"RECUSAL_POLICY_ERROR ({type(exc).__name__})"
|
|
238
|
+
}
|
|
239
|
+
reason = _ordering_reason(self, tool_context)
|
|
240
|
+
if reason is not None:
|
|
241
|
+
return {"error": _unjudgeable(tool.name, reason, tool_args, record)}
|
|
242
|
+
reason = _refusal(tool, tool_args, self._policy, **record)
|
|
243
|
+
return {"error": reason} if reason is not None else None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _ordering_reason(plugin: RecusalPlugin, tool_context: Any) -> Optional[str]:
|
|
247
|
+
"""Why the plugin is not the last before-tool seam for this call, or None if it is.
|
|
248
|
+
|
|
249
|
+
The executing agent is read from the invocation context behind ``tool_context``; its
|
|
250
|
+
before-tool callbacks run after every plugin, so any callback that is not a Recusal gate
|
|
251
|
+
could change the arguments the plugin judged. A plugin listed after this one whose class
|
|
252
|
+
overrides ``before_tool_callback`` runs after it too. Either is refused with the fix
|
|
253
|
+
named; so is a context that does not expose the agent.
|
|
254
|
+
"""
|
|
255
|
+
invocation = getattr(tool_context, "_invocation_context", None)
|
|
256
|
+
agent = getattr(invocation, "agent", None)
|
|
257
|
+
if agent is None:
|
|
258
|
+
return "the invocation context does not expose the executing agent"
|
|
259
|
+
if not isinstance(agent, LlmAgent):
|
|
260
|
+
return (
|
|
261
|
+
f"the executing agent {agent.name!r} is a {type(agent).__name__}, "
|
|
262
|
+
"whose before-tool callbacks this plugin cannot read"
|
|
263
|
+
)
|
|
264
|
+
for callback in _callbacks(agent):
|
|
265
|
+
if not getattr(callback, "recusal_gate", False):
|
|
266
|
+
name = getattr(callback, "__name__", type(callback).__name__)
|
|
267
|
+
return (
|
|
268
|
+
f"agent {agent.name!r} runs a before_tool_callback ({name}) after this "
|
|
269
|
+
"plugin; gate it with gated_agent(agent, policy)"
|
|
270
|
+
)
|
|
271
|
+
plugins = list(getattr(getattr(invocation, "plugin_manager", None), "plugins", []))
|
|
272
|
+
position = next((i for i, p in enumerate(plugins) if p is plugin), None)
|
|
273
|
+
for later in plugins[position + 1 :] if position is not None else []:
|
|
274
|
+
if isinstance(later, RecusalPlugin):
|
|
275
|
+
continue
|
|
276
|
+
if type(later).before_tool_callback is not BasePlugin.before_tool_callback:
|
|
277
|
+
return (
|
|
278
|
+
f"plugin {later.name!r} runs a before_tool_callback after this plugin; "
|
|
279
|
+
"list RecusalPlugin last"
|
|
280
|
+
)
|
|
281
|
+
return None
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _callbacks(agent: LlmAgent) -> list:
|
|
285
|
+
existing = agent.before_tool_callback
|
|
286
|
+
if existing is None:
|
|
287
|
+
return []
|
|
288
|
+
return list(existing) if isinstance(existing, list) else [existing]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _carries_gate(agent: LlmAgent) -> bool:
|
|
292
|
+
return any(getattr(cb, "recusal_gate", False) for cb in _callbacks(agent))
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _ungateable_reason(agent: Any) -> Optional[str]:
|
|
296
|
+
"""Why an agent can run something the callback never sees, or None if it cannot."""
|
|
297
|
+
if isinstance(agent, _WORKFLOW_AGENTS):
|
|
298
|
+
return None
|
|
299
|
+
if type(agent) is not LlmAgent:
|
|
300
|
+
return (
|
|
301
|
+
f"{type(agent).__name__} is not a plain LlmAgent; a subclass can run tools or "
|
|
302
|
+
"code the before-tool callback never sees"
|
|
303
|
+
)
|
|
304
|
+
if agent.code_executor is not None:
|
|
305
|
+
return "it has a code_executor; model-written code runs outside the tool path"
|
|
306
|
+
return None
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def is_gated(agent: Any, _seen: Optional[set] = None) -> bool:
|
|
310
|
+
"""True if every tool call this agent, its sub-agents and its agent tools can make
|
|
311
|
+
passes through a Recusal before-tool callback."""
|
|
312
|
+
seen = set() if _seen is None else _seen
|
|
313
|
+
if id(agent) in seen:
|
|
314
|
+
return True
|
|
315
|
+
seen.add(id(agent))
|
|
316
|
+
if _ungateable_reason(agent) is not None:
|
|
317
|
+
return False
|
|
318
|
+
if isinstance(agent, LlmAgent):
|
|
319
|
+
if not _carries_gate(agent):
|
|
320
|
+
return False
|
|
321
|
+
for tool in agent.tools:
|
|
322
|
+
if isinstance(tool, AgentTool) and not is_gated(tool.agent, seen):
|
|
323
|
+
return False
|
|
324
|
+
return all(is_gated(sub, seen) for sub in agent.sub_agents)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def gated_agent(
|
|
328
|
+
agent: BaseAgent, policy: Policy, recording: Optional[Recording] = None
|
|
329
|
+
) -> BaseAgent:
|
|
330
|
+
"""Return a copy of the agent whose every tool call is judged by Recusal.
|
|
331
|
+
|
|
332
|
+
The gate is appended as the LAST before-tool callback; ``sub_agents`` and the agent
|
|
333
|
+
behind every ``AgentTool`` are gated the same way. Raises ValueError if the agent, or
|
|
334
|
+
any agent under it, can run something the callback cannot see. ``recording`` puts
|
|
335
|
+
every decision of every gate it installs on an audit log.
|
|
336
|
+
"""
|
|
337
|
+
reason = _ungateable_reason(agent)
|
|
338
|
+
if reason is not None:
|
|
339
|
+
raise ValueError(f"Recusal cannot gate agent {agent.name!r}: {reason}")
|
|
340
|
+
update: dict[str, Any] = {
|
|
341
|
+
"sub_agents": [gated_agent(sub, policy, recording) for sub in agent.sub_agents]
|
|
342
|
+
}
|
|
343
|
+
if isinstance(agent, LlmAgent):
|
|
344
|
+
tools: list[Any] = []
|
|
345
|
+
for tool in agent.tools:
|
|
346
|
+
if isinstance(tool, AgentTool):
|
|
347
|
+
tools.append(
|
|
348
|
+
AgentTool(
|
|
349
|
+
gated_agent(tool.agent, policy, recording),
|
|
350
|
+
skip_summarization=tool.skip_summarization,
|
|
351
|
+
)
|
|
352
|
+
)
|
|
353
|
+
else:
|
|
354
|
+
tools.append(tool)
|
|
355
|
+
update["tools"] = tools
|
|
356
|
+
update["before_tool_callback"] = _callbacks(agent) + [
|
|
357
|
+
recusal_before_tool(policy, recording)
|
|
358
|
+
]
|
|
359
|
+
return agent.clone(update=update)
|
|
File without changes
|