beeai-acgs 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.
- beeai_acgs-0.1.0/.gitignore +12 -0
- beeai_acgs-0.1.0/CHANGELOG.md +23 -0
- beeai_acgs-0.1.0/LICENSE +175 -0
- beeai_acgs-0.1.0/PKG-INFO +399 -0
- beeai_acgs-0.1.0/README.md +372 -0
- beeai_acgs-0.1.0/examples/quickstart.py +103 -0
- beeai_acgs-0.1.0/pyproject.toml +145 -0
- beeai_acgs-0.1.0/src/beeai_acgs/__init__.py +25 -0
- beeai_acgs-0.1.0/src/beeai_acgs/_governance.py +310 -0
- beeai_acgs-0.1.0/src/beeai_acgs/middleware.py +403 -0
- beeai_acgs-0.1.0/src/beeai_acgs/py.typed +0 -0
- beeai_acgs-0.1.0/tests/__init__.py +0 -0
- beeai_acgs-0.1.0/tests/conftest.py +3 -0
- beeai_acgs-0.1.0/tests/fakes.py +173 -0
- beeai_acgs-0.1.0/tests/mcp_server.py +28 -0
- beeai_acgs-0.1.0/tests/test_default_constitution.py +90 -0
- beeai_acgs-0.1.0/tests/test_examples.py +83 -0
- beeai_acgs-0.1.0/tests/test_governance.py +286 -0
- beeai_acgs-0.1.0/tests/test_imports.py +22 -0
- beeai_acgs-0.1.0/tests/test_mcp.py +32 -0
- beeai_acgs-0.1.0/tests/test_middleware.py +271 -0
- beeai_acgs-0.1.0/tests/test_review.py +278 -0
- beeai_acgs-0.1.0/tests/test_tampering.py +125 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/). Entries for new releases are generated with `cz bump`.
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## 0.1.0 (2026-10-23)
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `ACGSMiddleware`: a BeeAI run middleware that checks each tool call's name and validated input against an ACGS
|
|
14
|
+
constitution before the tool runs, and sets the denial reason as the tool output. It follows nested runs, so
|
|
15
|
+
tools of `HandoffTool` sub-agents and tools called by other tools are checked as well.
|
|
16
|
+
- Review handling through an injected reviewer (`approver=`, sync or async, `review_timeout=`), with
|
|
17
|
+
`io_confirm_approver` for BeeAI's IO handlers; `on_review="deny"` denies without asking. No reviewer, an error
|
|
18
|
+
or a timeout denies the call.
|
|
19
|
+
- `ACGSMiddleware.permission_requirement()`: an `AskPermissionRequirement` for `RequirementAgent` that asks only
|
|
20
|
+
about calls ACGS sends to review.
|
|
21
|
+
- A final check right before the tool runs: if the input changed after the decision, or a denied call starts
|
|
22
|
+
anyway, the run ends with `ACGSToolCallChangedError`.
|
|
23
|
+
- `ACGSMiddleware.evaluate` and `decide`; the `tool_call_formatter=` option.
|
beeai_acgs-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: beeai-acgs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ACGS rule-based tool-call governance for BeeAI Framework agents, via run middleware
|
|
5
|
+
Project-URL: Homepage, https://github.com/acgs-ai/beeai-acgs
|
|
6
|
+
Project-URL: Documentation, https://github.com/acgs-ai/beeai-acgs#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/acgs-ai/beeai-acgs
|
|
8
|
+
Project-URL: Issues, https://github.com/acgs-ai/beeai-acgs/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/acgs-ai/beeai-acgs/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Martin Lyu
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: acgs,agents,ai,beeai,beeai-framework,governance,human-in-the-loop,middleware,tool-calls
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: <3.14,>=3.11
|
|
24
|
+
Requires-Dist: acgs-lite<4,>=3.0.1
|
|
25
|
+
Requires-Dist: beeai-framework<0.2,>=0.1.85
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# beeai-acgs
|
|
29
|
+
|
|
30
|
+
[](https://github.com/acgs-ai/beeai-acgs/actions/workflows/ci.yml)
|
|
31
|
+
[](https://pypi.org/project/beeai-acgs/)
|
|
32
|
+
[](https://pypi.org/project/beeai-acgs/)
|
|
33
|
+
|
|
34
|
+
`beeai-acgs` checks [BeeAI Framework](https://github.com/i-am-bee/beeai-framework) tool calls against
|
|
35
|
+
[ACGS](https://pypi.org/project/acgs-lite/) constitution rules before the tool runs. `ACGSMiddleware` is a BeeAI
|
|
36
|
+
run middleware: pass it in `middlewares=[...]` and it checks every tool call made inside the run, including calls
|
|
37
|
+
made by sub-agents (`HandoffTool`) and by tools that call other tools.
|
|
38
|
+
|
|
39
|
+
What happens to a call:
|
|
40
|
+
|
|
41
|
+
- Calls that match no blocking rule run unchanged.
|
|
42
|
+
- Calls that match a blocking rule do not run. The model gets the reason as the tool output and can continue.
|
|
43
|
+
- Calls that only match review rules run only if the reviewer you configure returns `True`. Without a reviewer,
|
|
44
|
+
they are denied.
|
|
45
|
+
- A blocking rule always wins. A reviewer is never asked about a blocked call.
|
|
46
|
+
- Any error while evaluating or reviewing a call denies it (fail-closed).
|
|
47
|
+
- If another listener changes a call after the check, or starts a denied call, the run ends with
|
|
48
|
+
`ACGSToolCallChangedError` and the tool does not run.
|
|
49
|
+
|
|
50
|
+
The package is a thin adapter over the public `acgs-lite` API.
|
|
51
|
+
|
|
52
|
+
> [!NOTE]
|
|
53
|
+
> This is a community package. It is not part of the BeeAI Framework and is not maintained, reviewed or endorsed
|
|
54
|
+
> by the BeeAI Framework maintainers.
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install beeai-acgs
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Requires Python 3.11 to 3.13, `beeai-framework>=0.1.85,<0.2` and `acgs-lite>=3.0.1,<4`.
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from beeai_framework.agents.requirement import RequirementAgent
|
|
68
|
+
from beeai_framework.tools import tool
|
|
69
|
+
|
|
70
|
+
from beeai_acgs import ACGSMiddleware
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@tool()
|
|
74
|
+
def send_email(to: str, body: str) -> str:
|
|
75
|
+
"""Send an email."""
|
|
76
|
+
return f"sent to {to}"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# llm is any BeeAI chat model, for example ChatModel.from_name("ollama:granite4:micro").
|
|
80
|
+
agent = RequirementAgent(llm=llm, tools=[send_email], middlewares=[ACGSMiddleware()])
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The middleware works with any BeeAI agent or tool that runs in a `RunContext` (`RequirementAgent`, `ReActAgent`,
|
|
84
|
+
`ToolCallingAgent`, workflows, a direct `tool.run(...)`). To govern a single run instead of every run of an
|
|
85
|
+
agent, use `await agent.run("...").middleware(ACGSMiddleware())`.
|
|
86
|
+
|
|
87
|
+
## Quickstart
|
|
88
|
+
|
|
89
|
+
`examples/quickstart.py` runs offline. A small scripted model stands in for a real one:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
"""Block, allow and review tool calls with beeai-acgs. Runs offline: python examples/quickstart.py"""
|
|
93
|
+
|
|
94
|
+
import asyncio
|
|
95
|
+
import json
|
|
96
|
+
from collections.abc import AsyncGenerator
|
|
97
|
+
from typing import Any
|
|
98
|
+
|
|
99
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
100
|
+
from beeai_framework.agents.requirement import RequirementAgent
|
|
101
|
+
from beeai_framework.backend import AssistantMessage, ChatModel, ChatModelOutput, MessageToolCallContent, ToolMessage
|
|
102
|
+
from beeai_framework.backend.types import ChatModelInput
|
|
103
|
+
from beeai_framework.context import RunContext
|
|
104
|
+
from beeai_framework.tools import tool
|
|
105
|
+
|
|
106
|
+
from beeai_acgs import ACGSMiddleware, ReviewRequest
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class ScriptedChatModel(ChatModel):
|
|
110
|
+
"""Stands in for a real model: each turn is a list of (call_id, tool, arguments)."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, turns: list[list[tuple[str, str, dict[str, Any]]]]) -> None:
|
|
113
|
+
super().__init__(allow_parallel_tool_calls=True)
|
|
114
|
+
self.turns = turns
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def model_id(self) -> str:
|
|
118
|
+
return "scripted"
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def provider_id(self) -> Any:
|
|
122
|
+
return "ollama"
|
|
123
|
+
|
|
124
|
+
async def _create(self, input: ChatModelInput, run: RunContext) -> ChatModelOutput: # noqa: A002
|
|
125
|
+
message = AssistantMessage(
|
|
126
|
+
[
|
|
127
|
+
MessageToolCallContent(id=call_id, tool_name=name, args=json.dumps(arguments))
|
|
128
|
+
for call_id, name, arguments in self.turns.pop(0)
|
|
129
|
+
]
|
|
130
|
+
)
|
|
131
|
+
return ChatModelOutput(output=[message])
|
|
132
|
+
|
|
133
|
+
async def _create_stream(self, input: ChatModelInput, run: RunContext) -> AsyncGenerator[ChatModelOutput]: # noqa: A002
|
|
134
|
+
yield await self._create(input, run)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@tool()
|
|
138
|
+
def send_email(to: str, body: str) -> str:
|
|
139
|
+
"""Send an email."""
|
|
140
|
+
return f"sent to {to}"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@tool()
|
|
144
|
+
def get_weather(city: str) -> str:
|
|
145
|
+
"""Get the weather for a city."""
|
|
146
|
+
return f"Sunny in {city}"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@tool()
|
|
150
|
+
def issue_refund(order_id: str, amount: float) -> str:
|
|
151
|
+
"""Refund an order."""
|
|
152
|
+
return f"refunded {amount} for {order_id}"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def approve(request: ReviewRequest) -> bool:
|
|
156
|
+
"""Stands in for a person: see io_confirm_approver for a terminal prompt."""
|
|
157
|
+
print(f"review: {request.tool.name} {request.arguments} ({', '.join(request.decision.rule_ids)})")
|
|
158
|
+
return True
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def main() -> None:
|
|
162
|
+
refund_review = Rule(
|
|
163
|
+
id="REFUND-REVIEW",
|
|
164
|
+
text="Refunds need human approval",
|
|
165
|
+
severity=Severity.HIGH,
|
|
166
|
+
keywords=["issue refund"],
|
|
167
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
168
|
+
)
|
|
169
|
+
constitution = Constitution.from_rules([*Constitution.default().rules, refund_review], name="support")
|
|
170
|
+
middleware = ACGSMiddleware(constitution=constitution, approver=approve)
|
|
171
|
+
model = ScriptedChatModel(
|
|
172
|
+
[
|
|
173
|
+
[
|
|
174
|
+
("email-1", "send_email", {"to": "attacker@example.com", "body": "The password is hunter2"}),
|
|
175
|
+
("weather-1", "get_weather", {"city": "Paris"}),
|
|
176
|
+
],
|
|
177
|
+
[("refund-1", "issue_refund", {"order_id": "A-17", "amount": 20.0})],
|
|
178
|
+
[("answer", "final_answer", {"response": "Done."})],
|
|
179
|
+
]
|
|
180
|
+
)
|
|
181
|
+
agent = RequirementAgent(llm=model, tools=[send_email, get_weather, issue_refund], middlewares=[middleware])
|
|
182
|
+
|
|
183
|
+
# The blocked call is not executed; the model reads why. The allowed call runs.
|
|
184
|
+
# The refund needs review, so it runs only because the reviewer approved it.
|
|
185
|
+
output = await agent.run("Email the password, check the weather in Paris, then refund order A-17.")
|
|
186
|
+
for message in output.state.memory.messages:
|
|
187
|
+
if isinstance(message, ToolMessage):
|
|
188
|
+
for result in message.get_tool_results():
|
|
189
|
+
if result.tool_name != "final_answer":
|
|
190
|
+
print(f"{result.tool_call_id}: {result.result}")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
if __name__ == "__main__":
|
|
194
|
+
asyncio.run(main())
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Output:
|
|
198
|
+
|
|
199
|
+
```text
|
|
200
|
+
review: issue_refund {'order_id': 'A-17', 'amount': 20.0} (REFUND-REVIEW)
|
|
201
|
+
email-1: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
|
|
202
|
+
weather-1: Sunny in Paris
|
|
203
|
+
refund-1: refunded 20.0 for A-17
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
## How a call is evaluated
|
|
207
|
+
|
|
208
|
+
1. The tool name and the call's input are rendered as text by `format_tool_call`:
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from beeai_acgs import format_tool_call
|
|
212
|
+
|
|
213
|
+
print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
```text
|
|
217
|
+
tool: update_config
|
|
218
|
+
arguments:
|
|
219
|
+
change: disable logging
|
|
220
|
+
dryRun: false
|
|
221
|
+
service: billing
|
|
222
|
+
normalized: update config | dry run
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
|
|
226
|
+
values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
|
|
227
|
+
Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
|
|
228
|
+
single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
|
|
229
|
+
`skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
|
|
230
|
+
Pass `tool_call_formatter=` to use a different representation.
|
|
231
|
+
|
|
232
|
+
The input is the one the tool will run with: the model's arguments validated by the tool's `input_schema`,
|
|
233
|
+
with defaults filled in and unknown fields dropped. If validation fails (the tool then rejects the call
|
|
234
|
+
itself), the arguments are evaluated as sent.
|
|
235
|
+
|
|
236
|
+
2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
|
|
237
|
+
(`Constitution.default()` unless you pass one).
|
|
238
|
+
|
|
239
|
+
3. The result decides what happens to the call:
|
|
240
|
+
|
|
241
|
+
| ACGS outcome | Result |
|
|
242
|
+
|---|---|
|
|
243
|
+
| No blocking rule matched (warn-only rules may match) | The tool runs |
|
|
244
|
+
| Only `require_human_review` / `escalate_to_senior` rules matched | Review (see below) |
|
|
245
|
+
| Any `block`, `block_and_notify` or `halt_and_alert` rule matched | Denied |
|
|
246
|
+
| A rule ID not found in the constitution, or an invalid result without a rule | Denied |
|
|
247
|
+
| Any exception while reading or evaluating the call | Denied (fail-closed) |
|
|
248
|
+
|
|
249
|
+
A matched blocking rule is never downgraded to review because a review rule matched as well.
|
|
250
|
+
|
|
251
|
+
A denied call is not executed. The middleware sets the tool's output to
|
|
252
|
+
`"Tool call '<name>' was not executed. <reason>"`, so the model reads the reason. The reason names the matched
|
|
253
|
+
rules but never repeats argument values. `ACGSMiddleware.evaluate(tool_name, args)` returns the
|
|
254
|
+
`GovernanceDecision` without running anything, and `await ACGSMiddleware.decide(tool, args)` applies the review
|
|
255
|
+
handling as well.
|
|
256
|
+
|
|
257
|
+
## How it hooks in
|
|
258
|
+
|
|
259
|
+
BeeAI emits an internal `start` event for every run before the run's code executes, and a listener can set the
|
|
260
|
+
event's `output` to skip the run. This is the mechanism BeeAI's own `AskPermissionRequirement` and its
|
|
261
|
+
`hol_guard.py` middleware example use. `ACGSMiddleware`:
|
|
262
|
+
|
|
263
|
+
1. listens for `start` events of nested runs, blocking, with the lowest priority, so it decides after other
|
|
264
|
+
listeners have had their say;
|
|
265
|
+
2. for a tool run, evaluates the call and sets the output if the call is denied;
|
|
266
|
+
3. follows every nested run (BeeAI forwards a run's events only to its direct parent), so tools called by
|
|
267
|
+
sub-agents and by other tools are checked as well; each tool call is decided once, even if the middleware is
|
|
268
|
+
bound at several levels;
|
|
269
|
+
4. registers one more listener, again lowest priority, on the tool's own `start` event, which BeeAI emits with
|
|
270
|
+
the validated input right before the tool runs. If the input differs from the checked input, or the call was
|
|
271
|
+
denied, it raises `ACGSToolCallChangedError` and the run ends.
|
|
272
|
+
|
|
273
|
+
## Review
|
|
274
|
+
|
|
275
|
+
Pass a reviewer: a function, sync or async, that receives a `ReviewRequest` (`tool`, `arguments`, `decision`,
|
|
276
|
+
`run_id`, `prompt`) and returns `True` to run the call. Any other return value, an exception, or no answer within
|
|
277
|
+
`review_timeout` seconds (async reviewers only) denies the call.
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
from beeai_acgs import ACGSMiddleware, io_confirm_approver
|
|
281
|
+
|
|
282
|
+
# io_confirm_approver asks in the terminal, or through the handlers set with
|
|
283
|
+
# beeai_framework.utils.io.setup_io_context (as BeeAI's own AskPermissionRequirement does).
|
|
284
|
+
middleware = ACGSMiddleware(constitution=constitution, approver=io_confirm_approver, review_timeout=300)
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`on_review="deny"` denies every call that needs review without asking.
|
|
288
|
+
|
|
289
|
+
With a `RequirementAgent`, `middleware.permission_requirement()` returns an `AskPermissionRequirement` that asks
|
|
290
|
+
only about calls ACGS sends to review. Allowed calls are not asked about and blocked calls are refused without
|
|
291
|
+
asking. A call the reviewer answered is not asked about again by the middleware:
|
|
292
|
+
|
|
293
|
+
```python
|
|
294
|
+
from beeai_framework.agents.requirement import RequirementAgent
|
|
295
|
+
|
|
296
|
+
from beeai_acgs import ACGSMiddleware
|
|
297
|
+
|
|
298
|
+
middleware = ACGSMiddleware(constitution=constitution)
|
|
299
|
+
agent = RequirementAgent(
|
|
300
|
+
llm=llm,
|
|
301
|
+
tools=tools,
|
|
302
|
+
requirements=[middleware.permission_requirement()], # asks with io_confirm_approver by default
|
|
303
|
+
middlewares=[middleware], # keep the middleware: it also covers tools of sub-agents and nested tools
|
|
304
|
+
)
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
## What is covered
|
|
308
|
+
|
|
309
|
+
| Tool | Checked |
|
|
310
|
+
|---|---|
|
|
311
|
+
| `@tool` functions, `Tool` subclasses, BeeAI's built-in tools, `MCPTool`, `OpenAPITool`, `LangChainTool` | Yes |
|
|
312
|
+
| `HandoffTool` (the task text) and the tools of the sub-agent it runs | Yes |
|
|
313
|
+
| Tools called from inside another tool | Yes |
|
|
314
|
+
| Several tool calls in one model turn | Yes, one by one |
|
|
315
|
+
| `RequirementAgent`'s `final_answer` | No (it is the answer, not an action) |
|
|
316
|
+
| `ToolCallingAgent`'s `final_answer` | Yes (a regular tool there; a blocked answer is sent back to the model) |
|
|
317
|
+
| Remote agents (A2A, ACP, Agent Stack, watsonx Orchestrate) | Only the call that starts them; tools they run remotely are not checked |
|
|
318
|
+
| `tool.run(...)` called outside a run that has the middleware | No |
|
|
319
|
+
|
|
320
|
+
## Custom constitutions
|
|
321
|
+
|
|
322
|
+
```python
|
|
323
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
324
|
+
|
|
325
|
+
from beeai_acgs import ACGSMiddleware
|
|
326
|
+
|
|
327
|
+
constitution = Constitution.from_rules(
|
|
328
|
+
[
|
|
329
|
+
Rule(
|
|
330
|
+
id="NO-DESTRUCTIVE-SQL",
|
|
331
|
+
text="No destructive SQL",
|
|
332
|
+
severity=Severity.CRITICAL,
|
|
333
|
+
keywords=["drop table", "truncate table"],
|
|
334
|
+
),
|
|
335
|
+
Rule(
|
|
336
|
+
id="REFUND-REVIEW",
|
|
337
|
+
text="Refunds need approval",
|
|
338
|
+
severity=Severity.HIGH,
|
|
339
|
+
keywords=["refund"],
|
|
340
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
341
|
+
),
|
|
342
|
+
],
|
|
343
|
+
name="payments",
|
|
344
|
+
)
|
|
345
|
+
middleware = ACGSMiddleware(constitution=constitution, agent_id="payments-app")
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
`Constitution.from_yaml("rules.yaml")` works as well.
|
|
349
|
+
|
|
350
|
+
## Options
|
|
351
|
+
|
|
352
|
+
| Argument | Default | Meaning |
|
|
353
|
+
|---|---|---|
|
|
354
|
+
| `constitution` | `Constitution.default()` | Rules to enforce |
|
|
355
|
+
| `agent_id` | `"beeai"` | Agent identifier recorded by ACGS |
|
|
356
|
+
| `on_review` | `"ask"` | `"ask"` puts calls that need review to `approver`; `"deny"` denies them |
|
|
357
|
+
| `approver` | `None` | The reviewer; without one, calls that need review are denied |
|
|
358
|
+
| `review_timeout` | `None` | Seconds to wait for an async reviewer |
|
|
359
|
+
| `tool_call_formatter` | `format_tool_call` | `(tool_name, args) -> str` used as the evaluated text |
|
|
360
|
+
|
|
361
|
+
## Limitations
|
|
362
|
+
|
|
363
|
+
- Only tool calls are checked. User input, model output and tool results are not.
|
|
364
|
+
- Listeners on a tool's `start` event that are not blocking, or that BeeAI runs after this middleware (equal
|
|
365
|
+
lowest priority, registered later), can still act after the final check. The check catches changes to the
|
|
366
|
+
input and a removed denial, not other side effects of such listeners.
|
|
367
|
+
- A denied call does not stop other calls of the same model turn.
|
|
368
|
+
- Remote agents run their own tools; see [What is covered](#what-is-covered).
|
|
369
|
+
- Tested with `RequirementAgent`, `ReActAgent`, `ToolCallingAgent`, `HandoffTool` sub-agents, nested tool calls,
|
|
370
|
+
a direct `tool.run`, a local stdio MCP server and `AskPermissionRequirement`, all with a scripted model,
|
|
371
|
+
against beeai-framework 0.1.85. Real providers, workflows, serve adapters and remote agents are not tested.
|
|
372
|
+
- `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
|
|
373
|
+
and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
|
|
374
|
+
patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
|
|
375
|
+
tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
|
|
376
|
+
- Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
|
|
377
|
+
("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
|
|
378
|
+
(`api-key` does not match the keyword `api_key`).
|
|
379
|
+
- Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied
|
|
380
|
+
under the default constitution whenever it is called.
|
|
381
|
+
|
|
382
|
+
## Development
|
|
383
|
+
|
|
384
|
+
```bash
|
|
385
|
+
uv sync --group dev # or use hatch: hatch run prepare
|
|
386
|
+
hatch run format # ruff format + ruff check --fix
|
|
387
|
+
hatch run lint # ruff check + ruff format --check
|
|
388
|
+
hatch run typecheck # mypy --strict
|
|
389
|
+
hatch run cov # pytest with a 100% branch-coverage gate, network disabled
|
|
390
|
+
hatch run min:cov # the same tests against beeai-framework 0.1.85 and acgs-lite 3.0.1
|
|
391
|
+
pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
|
|
395
|
+
and the changelog.
|
|
396
|
+
|
|
397
|
+
## License
|
|
398
|
+
|
|
399
|
+
Apache-2.0. See [LICENSE](LICENSE).
|