loop-guardrail 1.0.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.
- loop_guardrail-1.0.0/.gitignore +4 -0
- loop_guardrail-1.0.0/CHANGELOG.md +12 -0
- loop_guardrail-1.0.0/CONTRIBUTING.md +29 -0
- loop_guardrail-1.0.0/LICENSE +201 -0
- loop_guardrail-1.0.0/PKG-INFO +39 -0
- loop_guardrail-1.0.0/README.md +17 -0
- loop_guardrail-1.0.0/pyproject.toml +32 -0
- loop_guardrail-1.0.0/src/loop_guardrail/__init__.py +22 -0
- loop_guardrail-1.0.0/src/loop_guardrail/guardrail.py +353 -0
- loop_guardrail-1.0.0/tests/test_guardrail.py +105 -0
- loop_guardrail-1.0.0/uv.lock +8 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here.
|
|
4
|
+
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
|
+
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [1.0.0] - 2026-05-20
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
- Initial standalone release as Apache-2.0 library.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Thanks for considering a contribution.
|
|
4
|
+
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
git clone https://github.com/p-vbordei/loop-guardrail-py.git
|
|
9
|
+
cd loop-guardrail-py
|
|
10
|
+
uv sync
|
|
11
|
+
uv run --with pytest --with pytest-asyncio pytest
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Workflow
|
|
15
|
+
|
|
16
|
+
1. Open an issue first for non-trivial changes.
|
|
17
|
+
2. Fork, branch from `main`, make changes.
|
|
18
|
+
3. Run tests locally before pushing.
|
|
19
|
+
4. Open a PR with a clear description.
|
|
20
|
+
|
|
21
|
+
## Code style
|
|
22
|
+
|
|
23
|
+
- Tests live in `tests/` next to source in `src/`.
|
|
24
|
+
- Prefer small focused PRs over big ones.
|
|
25
|
+
- Tests should be deterministic.
|
|
26
|
+
|
|
27
|
+
## License
|
|
28
|
+
|
|
29
|
+
By contributing you agree your contribution will be licensed under the project's existing license (Apache-2.0).
|
|
@@ -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
|
|
95
|
+
Derivative 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
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying 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 describing the origin of the Work and
|
|
141
|
+
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 accept and charge a
|
|
167
|
+
fee for acceptance of support, warranty, indemnity, or other liability
|
|
168
|
+
obligations and/or rights consistent with this License. However, in
|
|
169
|
+
accepting such obligations, You may act only on Your own behalf and on
|
|
170
|
+
Your sole responsibility, not on behalf of any other Contributor, and
|
|
171
|
+
only if You agree to indemnify, defend, and hold each Contributor
|
|
172
|
+
harmless for any liability incurred by, or claims asserted against,
|
|
173
|
+
such Contributor by reason of your accepting any such warranty or
|
|
174
|
+
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 Vlad Bordei
|
|
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,39 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loop-guardrail
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Execution loop detector and guardrail for AI agents
|
|
5
|
+
Project-URL: Homepage, https://github.com/p-vbordei/loop-guardrail-py
|
|
6
|
+
Project-URL: Repository, https://github.com/p-vbordei/loop-guardrail-py
|
|
7
|
+
Project-URL: Issues, https://github.com/p-vbordei/loop-guardrail-py/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/p-vbordei/loop-guardrail-py/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Vlad Bordei <bordeivlad@gmail.com>
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agents,guardrail,llm,loop-detection,safety
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# loop-guardrail
|
|
24
|
+
|
|
25
|
+
Execution loop detector and guardrail for AI agents.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from loop_guardrail import ToolCallGuardrailController, ToolCallGuardrailConfig
|
|
31
|
+
|
|
32
|
+
config = ToolCallGuardrailConfig(hard_stop_enabled=True)
|
|
33
|
+
ctrl = ToolCallGuardrailController(config)
|
|
34
|
+
|
|
35
|
+
# Pre-call check
|
|
36
|
+
dec = ctrl.before_call("terminal", {"cmd": "ls"})
|
|
37
|
+
if dec.action == "block":
|
|
38
|
+
print("Action blocked!")
|
|
39
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# loop-guardrail
|
|
2
|
+
|
|
3
|
+
Execution loop detector and guardrail for AI agents.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from loop_guardrail import ToolCallGuardrailController, ToolCallGuardrailConfig
|
|
9
|
+
|
|
10
|
+
config = ToolCallGuardrailConfig(hard_stop_enabled=True)
|
|
11
|
+
ctrl = ToolCallGuardrailController(config)
|
|
12
|
+
|
|
13
|
+
# Pre-call check
|
|
14
|
+
dec = ctrl.before_call("terminal", {"cmd": "ls"})
|
|
15
|
+
if dec.action == "block":
|
|
16
|
+
print("Action blocked!")
|
|
17
|
+
```
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "loop-guardrail"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Execution loop detector and guardrail for AI agents"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "Apache-2.0" }
|
|
8
|
+
authors = [{ name = "Vlad Bordei", email = "bordeivlad@gmail.com" }]
|
|
9
|
+
keywords = ["llm", "ai-agents", "guardrail", "loop-detection", "safety"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"License :: OSI Approved :: Apache Software License",
|
|
12
|
+
"Programming Language :: Python :: 3",
|
|
13
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
14
|
+
"Programming Language :: Python :: 3.10",
|
|
15
|
+
"Programming Language :: Python :: 3.11",
|
|
16
|
+
"Programming Language :: Python :: 3.12",
|
|
17
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
18
|
+
]
|
|
19
|
+
dependencies = []
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/p-vbordei/loop-guardrail-py"
|
|
23
|
+
Repository = "https://github.com/p-vbordei/loop-guardrail-py"
|
|
24
|
+
Issues = "https://github.com/p-vbordei/loop-guardrail-py/issues"
|
|
25
|
+
Changelog = "https://github.com/p-vbordei/loop-guardrail-py/blob/main/CHANGELOG.md"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["hatchling"]
|
|
29
|
+
build-backend = "hatchling.build"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/loop_guardrail"]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# loop-guardrail package
|
|
2
|
+
from .guardrail import (
|
|
3
|
+
ToolCallSignature,
|
|
4
|
+
ToolGuardrailDecision,
|
|
5
|
+
ToolCallGuardrailConfig,
|
|
6
|
+
ToolCallGuardrailController,
|
|
7
|
+
classify_tool_failure,
|
|
8
|
+
canonical_tool_args,
|
|
9
|
+
toolguard_synthetic_result,
|
|
10
|
+
append_toolguard_guidance,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"ToolCallSignature",
|
|
15
|
+
"ToolGuardrailDecision",
|
|
16
|
+
"ToolCallGuardrailConfig",
|
|
17
|
+
"ToolCallGuardrailController",
|
|
18
|
+
"classify_tool_failure",
|
|
19
|
+
"canonical_tool_args",
|
|
20
|
+
"toolguard_synthetic_result",
|
|
21
|
+
"append_toolguard_guidance",
|
|
22
|
+
]
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import hashlib
|
|
3
|
+
from typing import Dict, Any, Tuple, Set, Optional
|
|
4
|
+
|
|
5
|
+
IDEMPOTENT_TOOL_NAMES = {
|
|
6
|
+
"read_file",
|
|
7
|
+
"search_files",
|
|
8
|
+
"web_search",
|
|
9
|
+
"web_extract",
|
|
10
|
+
"session_search",
|
|
11
|
+
"browser_snapshot",
|
|
12
|
+
"browser_console",
|
|
13
|
+
"browser_get_images",
|
|
14
|
+
"mcp_filesystem_read_file",
|
|
15
|
+
"mcp_filesystem_read_text_file",
|
|
16
|
+
"mcp_filesystem_read_multiple_files",
|
|
17
|
+
"mcp_filesystem_list_directory",
|
|
18
|
+
"mcp_filesystem_list_directory_with_sizes",
|
|
19
|
+
"mcp_filesystem_directory_tree",
|
|
20
|
+
"mcp_filesystem_get_file_info",
|
|
21
|
+
"mcp_filesystem_search_files",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
MUTATING_TOOL_NAMES = {
|
|
25
|
+
"terminal",
|
|
26
|
+
"execute_code",
|
|
27
|
+
"write_file",
|
|
28
|
+
"patch",
|
|
29
|
+
"todo",
|
|
30
|
+
"memory",
|
|
31
|
+
"skill_manage",
|
|
32
|
+
"browser_click",
|
|
33
|
+
"browser_type",
|
|
34
|
+
"browser_press",
|
|
35
|
+
"browser_scroll",
|
|
36
|
+
"browser_navigate",
|
|
37
|
+
"send_message",
|
|
38
|
+
"cronjob",
|
|
39
|
+
"delegate_task",
|
|
40
|
+
"process",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def canonical_tool_args(args: Dict[str, Any]) -> str:
|
|
45
|
+
if not isinstance(args, dict):
|
|
46
|
+
raise TypeError("tool args must be a dictionary")
|
|
47
|
+
return json.dumps(args, sort_keys=True)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ToolCallSignature:
|
|
51
|
+
def __init__(self, tool_name: str, args_hash: str) -> None:
|
|
52
|
+
self.tool_name = tool_name
|
|
53
|
+
self.args_hash = args_hash
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def from_call(cls, tool_name: str, args: Optional[Dict[str, Any]]) -> "ToolCallSignature":
|
|
57
|
+
canonical = canonical_tool_args(args or {})
|
|
58
|
+
h = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
59
|
+
return cls(tool_name, h)
|
|
60
|
+
|
|
61
|
+
def to_metadata(self) -> Dict[str, str]:
|
|
62
|
+
return {"tool_name": self.tool_name, "args_hash": self.args_hash}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ToolGuardrailDecision:
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
action: str = "allow",
|
|
69
|
+
code: str = "allow",
|
|
70
|
+
message: str = "",
|
|
71
|
+
tool_name: str = "",
|
|
72
|
+
count: int = 0,
|
|
73
|
+
signature: Optional[ToolCallSignature] = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
self.action = action # "allow" | "warn" | "block" | "halt"
|
|
76
|
+
self.code = code
|
|
77
|
+
self.message = message
|
|
78
|
+
self.tool_name = tool_name
|
|
79
|
+
self.count = count
|
|
80
|
+
self.signature = signature
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def allows_execution(self) -> bool:
|
|
84
|
+
return self.action in ("allow", "warn")
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def should_halt(self) -> bool:
|
|
88
|
+
return self.action in ("block", "halt")
|
|
89
|
+
|
|
90
|
+
def to_metadata(self) -> Dict[str, Any]:
|
|
91
|
+
data = {
|
|
92
|
+
"action": self.action,
|
|
93
|
+
"code": self.code,
|
|
94
|
+
"message": self.message,
|
|
95
|
+
"tool_name": self.tool_name,
|
|
96
|
+
"count": self.count,
|
|
97
|
+
}
|
|
98
|
+
if self.signature is not None:
|
|
99
|
+
data["signature"] = self.signature.to_metadata()
|
|
100
|
+
return data
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class ToolCallGuardrailConfig:
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
warnings_enabled: bool = True,
|
|
107
|
+
hard_stop_enabled: bool = False,
|
|
108
|
+
exact_failure_warn_after: int = 2,
|
|
109
|
+
exact_failure_block_after: int = 5,
|
|
110
|
+
same_tool_failure_warn_after: int = 3,
|
|
111
|
+
same_tool_failure_halt_after: int = 8,
|
|
112
|
+
no_progress_warn_after: int = 2,
|
|
113
|
+
no_progress_block_after: int = 5,
|
|
114
|
+
idempotent_tools: Optional[Set[str]] = None,
|
|
115
|
+
mutating_tools: Optional[Set[str]] = None,
|
|
116
|
+
) -> None:
|
|
117
|
+
self.warnings_enabled = warnings_enabled
|
|
118
|
+
self.hard_stop_enabled = hard_stop_enabled
|
|
119
|
+
self.exact_failure_warn_after = exact_failure_warn_after
|
|
120
|
+
self.exact_failure_block_after = exact_failure_block_after
|
|
121
|
+
self.same_tool_failure_warn_after = same_tool_failure_warn_after
|
|
122
|
+
self.same_tool_failure_halt_after = same_tool_failure_halt_after
|
|
123
|
+
self.no_progress_warn_after = no_progress_warn_after
|
|
124
|
+
self.no_progress_block_after = no_progress_block_after
|
|
125
|
+
self.idempotent_tools = idempotent_tools if idempotent_tools is not None else IDEMPOTENT_TOOL_NAMES
|
|
126
|
+
self.mutating_tools = mutating_tools if mutating_tools is not None else MUTATING_TOOL_NAMES
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def file_mutation_result_landed(tool_name: str, result: Any) -> bool:
|
|
130
|
+
if tool_name not in ("write_file", "patch") or not isinstance(result, str):
|
|
131
|
+
return False
|
|
132
|
+
try:
|
|
133
|
+
data = json.loads(result.strip())
|
|
134
|
+
if not isinstance(data, dict) or "error" in data or data.get("error"):
|
|
135
|
+
return False
|
|
136
|
+
if tool_name == "write_file":
|
|
137
|
+
return "bytes_written" in data
|
|
138
|
+
if tool_name == "patch":
|
|
139
|
+
return data.get("success") is True
|
|
140
|
+
except Exception:
|
|
141
|
+
return False
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def classify_tool_failure(tool_name: str, result: Optional[str]) -> Tuple[bool, str]:
|
|
146
|
+
if result is None:
|
|
147
|
+
return False, ""
|
|
148
|
+
if file_mutation_result_landed(tool_name, result):
|
|
149
|
+
return False, ""
|
|
150
|
+
|
|
151
|
+
if tool_name == "terminal":
|
|
152
|
+
try:
|
|
153
|
+
data = json.loads(result.strip())
|
|
154
|
+
if isinstance(data, dict):
|
|
155
|
+
exit_code = data.get("exit_code")
|
|
156
|
+
if exit_code is not None and exit_code != 0:
|
|
157
|
+
return True, f" [exit {exit_code}]"
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
return False, ""
|
|
161
|
+
|
|
162
|
+
if tool_name == "memory":
|
|
163
|
+
try:
|
|
164
|
+
data = json.loads(result.strip())
|
|
165
|
+
if isinstance(data, dict):
|
|
166
|
+
if data.get("success") is False and "exceed the limit" in str(data.get("error") or ""):
|
|
167
|
+
return True, " [full]"
|
|
168
|
+
except Exception:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
lower = result[:500].lower()
|
|
172
|
+
if '"error"' in lower or '"failed"' in lower or result.startswith("Error"):
|
|
173
|
+
return True, " [error]"
|
|
174
|
+
|
|
175
|
+
return False, ""
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class ToolCallGuardrailController:
|
|
179
|
+
def __init__(self, config: Optional[ToolCallGuardrailConfig] = None) -> None:
|
|
180
|
+
self.config = config or ToolCallGuardrailConfig()
|
|
181
|
+
self.exact_failure_counts: Dict[str, int] = {}
|
|
182
|
+
self.same_tool_failure_counts: Dict[str, int] = {}
|
|
183
|
+
self.no_progress: Dict[str, Dict[str, Any]] = {}
|
|
184
|
+
self.active_halt_decision: Optional[ToolGuardrailDecision] = None
|
|
185
|
+
|
|
186
|
+
def reset_for_turn(self) -> None:
|
|
187
|
+
self.exact_failure_counts.clear()
|
|
188
|
+
self.same_tool_failure_counts.clear()
|
|
189
|
+
self.no_progress.clear()
|
|
190
|
+
self.active_halt_decision = None
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def halt_decision(self) -> Optional[ToolGuardrailDecision]:
|
|
194
|
+
return self.active_halt_decision
|
|
195
|
+
|
|
196
|
+
def before_call(self, tool_name: str, args: Optional[Dict[str, Any]]) -> ToolGuardrailDecision:
|
|
197
|
+
sig = ToolCallSignature.from_call(tool_name, args)
|
|
198
|
+
if not self.config.hard_stop_enabled:
|
|
199
|
+
return ToolGuardrailDecision("allow", "allow", "", tool_name, 0, sig)
|
|
200
|
+
|
|
201
|
+
exact_count = self.exact_failure_counts.get(sig.args_hash, 0)
|
|
202
|
+
if exact_count >= self.config.exact_failure_block_after:
|
|
203
|
+
dec = ToolGuardrailDecision(
|
|
204
|
+
"block",
|
|
205
|
+
"repeated_exact_failure_block",
|
|
206
|
+
f"Blocked {tool_name}: the same tool call failed {exact_count} times with identical arguments. Stop retrying it unchanged; change strategy or explain the blocker.",
|
|
207
|
+
tool_name,
|
|
208
|
+
exact_count,
|
|
209
|
+
sig,
|
|
210
|
+
)
|
|
211
|
+
self.active_halt_decision = dec
|
|
212
|
+
return dec
|
|
213
|
+
|
|
214
|
+
if self.is_idempotent(tool_name):
|
|
215
|
+
record = self.no_progress.get(sig.args_hash)
|
|
216
|
+
if record is not None:
|
|
217
|
+
repeat_count = record["repeat_count"]
|
|
218
|
+
if repeat_count >= self.config.no_progress_block_after:
|
|
219
|
+
dec = ToolGuardrailDecision(
|
|
220
|
+
"block",
|
|
221
|
+
"idempotent_no_progress_block",
|
|
222
|
+
f"Blocked {tool_name}: this read-only call returned the same result {repeat_count} times. Stop repeating it unchanged; use the result already provided or try a different query.",
|
|
223
|
+
tool_name,
|
|
224
|
+
repeat_count,
|
|
225
|
+
sig,
|
|
226
|
+
)
|
|
227
|
+
self.active_halt_decision = dec
|
|
228
|
+
return dec
|
|
229
|
+
|
|
230
|
+
return ToolGuardrailDecision("allow", "allow", "", tool_name, 0, sig)
|
|
231
|
+
|
|
232
|
+
def after_call(
|
|
233
|
+
self,
|
|
234
|
+
tool_name: str,
|
|
235
|
+
args: Optional[Dict[str, Any]],
|
|
236
|
+
result: Optional[str],
|
|
237
|
+
failed: Optional[bool] = None,
|
|
238
|
+
) -> ToolGuardrailDecision:
|
|
239
|
+
sig = ToolCallSignature.from_call(tool_name, args)
|
|
240
|
+
if failed is None:
|
|
241
|
+
failed, _ = classify_tool_failure(tool_name, result)
|
|
242
|
+
|
|
243
|
+
if failed:
|
|
244
|
+
exact_count = self.exact_failure_counts.get(sig.args_hash, 0) + 1
|
|
245
|
+
self.exact_failure_counts[sig.args_hash] = exact_count
|
|
246
|
+
self.no_progress.pop(sig.args_hash, None)
|
|
247
|
+
|
|
248
|
+
same_count = self.same_tool_failure_counts.get(tool_name, 0) + 1
|
|
249
|
+
self.same_tool_failure_counts[tool_name] = same_count
|
|
250
|
+
|
|
251
|
+
if self.config.hard_stop_enabled and same_count >= self.config.same_tool_failure_halt_after:
|
|
252
|
+
dec = ToolGuardrailDecision(
|
|
253
|
+
"halt",
|
|
254
|
+
"same_tool_failure_halt",
|
|
255
|
+
f"Stopped {tool_name}: it failed {same_count} times this turn. Stop retrying the same failing tool path and choose a different approach.",
|
|
256
|
+
tool_name,
|
|
257
|
+
same_count,
|
|
258
|
+
sig,
|
|
259
|
+
)
|
|
260
|
+
self.active_halt_decision = dec
|
|
261
|
+
return dec
|
|
262
|
+
|
|
263
|
+
if self.config.warnings_enabled and exact_count >= self.config.exact_failure_warn_after:
|
|
264
|
+
return ToolGuardrailDecision(
|
|
265
|
+
"warn",
|
|
266
|
+
"repeated_exact_failure_warning",
|
|
267
|
+
f"{tool_name} has failed {exact_count} times with identical arguments. This looks like a loop; inspect the error and change strategy instead of retrying it unchanged.",
|
|
268
|
+
tool_name,
|
|
269
|
+
exact_count,
|
|
270
|
+
sig,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
if self.config.warnings_enabled and same_count >= self.config.same_tool_failure_warn_after:
|
|
274
|
+
return ToolGuardrailDecision(
|
|
275
|
+
"warn",
|
|
276
|
+
"same_tool_failure_warning",
|
|
277
|
+
self.tool_failure_recovery_hint(tool_name, same_count),
|
|
278
|
+
tool_name,
|
|
279
|
+
same_count,
|
|
280
|
+
sig,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
return ToolGuardrailDecision("allow", "allow", "", tool_name, exact_count, sig)
|
|
284
|
+
|
|
285
|
+
self.exact_failure_counts.pop(sig.args_hash, None)
|
|
286
|
+
self.same_tool_failure_counts.pop(tool_name, None)
|
|
287
|
+
|
|
288
|
+
if not self.is_idempotent(tool_name):
|
|
289
|
+
self.no_progress.pop(sig.args_hash, None)
|
|
290
|
+
return ToolGuardrailDecision("allow", "allow", "", tool_name, 0, sig)
|
|
291
|
+
|
|
292
|
+
res_hash = self.compute_result_hash(result)
|
|
293
|
+
previous = self.no_progress.get(sig.args_hash)
|
|
294
|
+
repeat_count = 1
|
|
295
|
+
if previous is not None and previous["result_hash"] == res_hash:
|
|
296
|
+
repeat_count = previous["repeat_count"] + 1
|
|
297
|
+
self.no_progress[sig.args_hash] = {"result_hash": res_hash, "repeat_count": repeat_count}
|
|
298
|
+
|
|
299
|
+
if self.config.warnings_enabled and repeat_count >= self.config.no_progress_warn_after:
|
|
300
|
+
return ToolGuardrailDecision(
|
|
301
|
+
"warn",
|
|
302
|
+
"idempotent_no_progress_warning",
|
|
303
|
+
f"{tool_name} returned the same result {repeat_count} times. Use the result already provided or change the query instead of repeating it unchanged.",
|
|
304
|
+
tool_name,
|
|
305
|
+
repeat_count,
|
|
306
|
+
sig,
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
return ToolGuardrailDecision("allow", "allow", "", tool_name, repeat_count, sig)
|
|
310
|
+
|
|
311
|
+
def is_idempotent(self, tool_name: str) -> bool:
|
|
312
|
+
if tool_name in self.config.mutating_tools:
|
|
313
|
+
return False
|
|
314
|
+
return tool_name in self.config.idempotent_tools
|
|
315
|
+
|
|
316
|
+
def compute_result_hash(self, result: Optional[str]) -> str:
|
|
317
|
+
canonical = result or ""
|
|
318
|
+
try:
|
|
319
|
+
parsed = json.loads(canonical.strip())
|
|
320
|
+
if isinstance(parsed, dict):
|
|
321
|
+
canonical = json.dumps(parsed, sort_keys=True)
|
|
322
|
+
except Exception:
|
|
323
|
+
pass
|
|
324
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
325
|
+
|
|
326
|
+
def tool_failure_recovery_hint(self, tool_name: str, count: int) -> str:
|
|
327
|
+
common = f"{tool_name} has failed {count} times this turn. This looks like a loop. Do not switch to text-only replies; keep using tools, but diagnose before retrying. First inspect the latest error/output and verify your assumptions. "
|
|
328
|
+
if tool_name == "terminal":
|
|
329
|
+
return (
|
|
330
|
+
common
|
|
331
|
+
+ "For terminal failures, run a small diagnostic such as `pwd && ls -la` in the same tool, then try an absolute path, a simpler command, a different working directory, or a different tool such as read_file/write_file/patch."
|
|
332
|
+
)
|
|
333
|
+
return (
|
|
334
|
+
common
|
|
335
|
+
+ "Try different arguments, a narrower query/path, an absolute path when relevant, or a different tool that can make progress. If the blocker is external, report the blocker after one diagnostic attempt instead of repeating the same failing path."
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def toolguard_synthetic_result(decision: ToolGuardrailDecision) -> str:
|
|
340
|
+
return json.dumps(
|
|
341
|
+
{
|
|
342
|
+
"error": decision.message,
|
|
343
|
+
"guardrail": decision.to_metadata(),
|
|
344
|
+
}
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def append_toolguard_guidance(result: str, decision: ToolGuardrailDecision) -> str:
|
|
349
|
+
if decision.action not in ("warn", "halt") or not decision.message:
|
|
350
|
+
return result
|
|
351
|
+
label = "Tool loop hard stop" if decision.action == "halt" else "Tool loop warning"
|
|
352
|
+
suffix = f"\n\n[{label}: {decision.code}; count={decision.count}; {decision.message}]"
|
|
353
|
+
return (result or "") + suffix
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import time
|
|
3
|
+
import pytest
|
|
4
|
+
from loop_guardrail import (
|
|
5
|
+
ToolCallGuardrailController,
|
|
6
|
+
ToolCallGuardrailConfig,
|
|
7
|
+
classify_tool_failure,
|
|
8
|
+
toolguard_synthetic_result,
|
|
9
|
+
append_toolguard_guidance,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
def test_canonical_tool_args():
|
|
13
|
+
# Implicitly tested via ToolCallSignature.from_call
|
|
14
|
+
from loop_guardrail.guardrail import ToolCallSignature, canonical_tool_args
|
|
15
|
+
sig1 = ToolCallSignature.from_call("test", {"b": 2, "a": 1})
|
|
16
|
+
sig2 = ToolCallSignature.from_call("test", {"a": 1, "b": 2})
|
|
17
|
+
assert sig1.args_hash == sig2.args_hash
|
|
18
|
+
|
|
19
|
+
# Test recursive sorting parity
|
|
20
|
+
nested_args1 = {"x": {"y": 2, "z": 1}, "a": 5}
|
|
21
|
+
nested_args2 = {"a": 5, "x": {"z": 1, "y": 2}}
|
|
22
|
+
assert canonical_tool_args(nested_args1) == canonical_tool_args(nested_args2)
|
|
23
|
+
|
|
24
|
+
def test_classify_tool_failure():
|
|
25
|
+
assert classify_tool_failure("terminal", '{"exit_code": 1}') == (True, " [exit 1]")
|
|
26
|
+
assert classify_tool_failure("terminal", '{"exit_code": 0}') == (False, "")
|
|
27
|
+
assert classify_tool_failure("memory", '{"success": false, "error": "exceed the limit"}') == (True, " [full]")
|
|
28
|
+
assert classify_tool_failure("write_file", '{"error": "permission denied"}') == (True, " [error]")
|
|
29
|
+
|
|
30
|
+
def test_warning_flow():
|
|
31
|
+
config = ToolCallGuardrailConfig(
|
|
32
|
+
warnings_enabled=True,
|
|
33
|
+
hard_stop_enabled=False,
|
|
34
|
+
exact_failure_warn_after=2,
|
|
35
|
+
same_tool_failure_warn_after=3,
|
|
36
|
+
no_progress_warn_after=2,
|
|
37
|
+
)
|
|
38
|
+
ctrl = ToolCallGuardrailController(config)
|
|
39
|
+
|
|
40
|
+
# 1. Repeated exact failures
|
|
41
|
+
dec1 = ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
42
|
+
assert dec1.action == "allow"
|
|
43
|
+
|
|
44
|
+
# Turn 2 fails (exact same args) -> warning
|
|
45
|
+
dec2 = ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
46
|
+
assert dec2.action == "warn"
|
|
47
|
+
assert dec2.code == "repeated_exact_failure_warning"
|
|
48
|
+
|
|
49
|
+
# 2. Same tool failure count warning
|
|
50
|
+
ctrl.reset_for_turn()
|
|
51
|
+
ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
52
|
+
ctrl.after_call("terminal", {"cmd": "pwd"}, "error", failed=True)
|
|
53
|
+
dec = ctrl.after_call("terminal", {"cmd": "whoami"}, "error", failed=True)
|
|
54
|
+
assert dec.action == "warn"
|
|
55
|
+
assert dec.code == "same_tool_failure_warning"
|
|
56
|
+
|
|
57
|
+
# 3. Idempotent no progress warning
|
|
58
|
+
ctrl.reset_for_turn()
|
|
59
|
+
ctrl.after_call("read_file", {"path": "a.txt"}, "content", failed=False)
|
|
60
|
+
dec = ctrl.after_call("read_file", {"path": "a.txt"}, "content", failed=False)
|
|
61
|
+
assert dec.action == "warn"
|
|
62
|
+
assert dec.code == "idempotent_no_progress_warning"
|
|
63
|
+
|
|
64
|
+
def test_hard_stop_flow():
|
|
65
|
+
config = ToolCallGuardrailConfig(
|
|
66
|
+
warnings_enabled=True,
|
|
67
|
+
hard_stop_enabled=True,
|
|
68
|
+
exact_failure_block_after=3,
|
|
69
|
+
same_tool_failure_halt_after=3,
|
|
70
|
+
no_progress_block_after=3,
|
|
71
|
+
)
|
|
72
|
+
ctrl = ToolCallGuardrailController(config)
|
|
73
|
+
|
|
74
|
+
# Exact failure block
|
|
75
|
+
ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
76
|
+
ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
77
|
+
|
|
78
|
+
# Check block behavior before call
|
|
79
|
+
dec_before = ctrl.before_call("terminal", {"cmd": "ls"})
|
|
80
|
+
assert dec_before.action == "allow" # count is 2, block is at 3
|
|
81
|
+
|
|
82
|
+
ctrl.after_call("terminal", {"cmd": "ls"}, "error", failed=True)
|
|
83
|
+
dec_before_blocked = ctrl.before_call("terminal", {"cmd": "ls"})
|
|
84
|
+
assert dec_before_blocked.action == "block"
|
|
85
|
+
assert dec_before_blocked.code == "repeated_exact_failure_block"
|
|
86
|
+
|
|
87
|
+
# Same tool failure halt
|
|
88
|
+
ctrl.reset_for_turn()
|
|
89
|
+
ctrl.after_call("terminal", {"cmd": "1"}, "error", failed=True)
|
|
90
|
+
ctrl.after_call("terminal", {"cmd": "2"}, "error", failed=True)
|
|
91
|
+
dec_halt = ctrl.after_call("terminal", {"cmd": "3"}, "error", failed=True)
|
|
92
|
+
assert dec_halt.action == "halt"
|
|
93
|
+
assert dec_halt.code == "same_tool_failure_halt"
|
|
94
|
+
|
|
95
|
+
def test_scale_guardrail_performance():
|
|
96
|
+
ctrl = ToolCallGuardrailController()
|
|
97
|
+
start_time = time.time()
|
|
98
|
+
for i in range(10000):
|
|
99
|
+
tool_name = "web_search" if i % 2 == 0 else "read_file"
|
|
100
|
+
args = {"query": f"term_{i}"}
|
|
101
|
+
ctrl.before_call(tool_name, args)
|
|
102
|
+
failed = i % 2 != 0
|
|
103
|
+
ctrl.after_call(tool_name, args, "Error" if failed else "result", failed=failed)
|
|
104
|
+
duration = time.time() - start_time
|
|
105
|
+
assert duration < 1.0 # Should run in well under 1 second
|