agentscope-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.
- agentscope_acgs-0.1.0/.gitignore +12 -0
- agentscope_acgs-0.1.0/CHANGELOG.md +20 -0
- agentscope_acgs-0.1.0/LICENSE +175 -0
- agentscope_acgs-0.1.0/PKG-INFO +417 -0
- agentscope_acgs-0.1.0/README.md +389 -0
- agentscope_acgs-0.1.0/examples/quickstart.py +116 -0
- agentscope_acgs-0.1.0/pyproject.toml +152 -0
- agentscope_acgs-0.1.0/src/agentscope_acgs/__init__.py +9 -0
- agentscope_acgs-0.1.0/src/agentscope_acgs/_governance.py +310 -0
- agentscope_acgs-0.1.0/src/agentscope_acgs/middleware.py +176 -0
- agentscope_acgs-0.1.0/src/agentscope_acgs/py.typed +0 -0
- agentscope_acgs-0.1.0/tests/__init__.py +0 -0
- agentscope_acgs-0.1.0/tests/conftest.py +3 -0
- agentscope_acgs-0.1.0/tests/fakes.py +209 -0
- agentscope_acgs-0.1.0/tests/test_default_constitution.py +90 -0
- agentscope_acgs-0.1.0/tests/test_examples.py +104 -0
- agentscope_acgs-0.1.0/tests/test_governance.py +286 -0
- agentscope_acgs-0.1.0/tests/test_imports.py +12 -0
- agentscope_acgs-0.1.0/tests/test_middleware.py +256 -0
|
@@ -0,0 +1,20 @@
|
|
|
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-28)
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- `ACGSMiddleware`: an AgentScope 2.x agent middleware. Its `on_check_permission` hook checks each tool call's
|
|
14
|
+
name and validated input against an ACGS constitution and returns `DENY` for blocking rules, `ASK` (AgentScope
|
|
15
|
+
user confirmation, `bypass_immune=True`) for review-only matches, and AgentScope's own decision otherwise. Any
|
|
16
|
+
error denies the call.
|
|
17
|
+
- `on_review="deny"` denies review calls without asking; review calls are also denied in `PermissionMode.DONT_ASK`.
|
|
18
|
+
- An execution check in `on_acting`: a tool runs only if the middleware allowed that exact call (call ID, tool
|
|
19
|
+
name and raw input); anything else gets a `denied` tool result.
|
|
20
|
+
- `ACGSMiddleware.evaluate`; the `tool_call_formatter=` option.
|
|
@@ -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,417 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agentscope-acgs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ACGS rule-based tool-call governance for AgentScope agents, via agent middleware
|
|
5
|
+
Project-URL: Homepage, https://github.com/acgs-ai/agentscope-acgs
|
|
6
|
+
Project-URL: Documentation, https://github.com/acgs-ai/agentscope-acgs#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/acgs-ai/agentscope-acgs
|
|
8
|
+
Project-URL: Issues, https://github.com/acgs-ai/agentscope-acgs/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/acgs-ai/agentscope-acgs/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Martin Lyu
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: acgs,agents,agentscope,ai,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: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: <3.15,>=3.11
|
|
25
|
+
Requires-Dist: acgs-lite<4,>=3.0.1
|
|
26
|
+
Requires-Dist: agentscope<2.1,>=2.0.6
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# agentscope-acgs
|
|
30
|
+
|
|
31
|
+
[](https://github.com/acgs-ai/agentscope-acgs/actions/workflows/ci.yml)
|
|
32
|
+
[](https://pypi.org/project/agentscope-acgs/)
|
|
33
|
+
[](https://pypi.org/project/agentscope-acgs/)
|
|
34
|
+
|
|
35
|
+
`agentscope-acgs` checks [AgentScope](https://github.com/agentscope-ai/agentscope) 2.x tool calls against
|
|
36
|
+
[ACGS](https://pypi.org/project/acgs-lite/) constitution rules before the tool runs. `ACGSMiddleware` is an
|
|
37
|
+
AgentScope agent middleware: pass it in `Agent(middlewares=[...])` and it answers AgentScope's permission check
|
|
38
|
+
for every tool call.
|
|
39
|
+
|
|
40
|
+
What happens to a call:
|
|
41
|
+
|
|
42
|
+
- Calls that match no blocking rule go on to AgentScope's own permission engine, whose decision is kept.
|
|
43
|
+
- Calls that match a blocking rule are denied. The model gets the reason as a `denied` tool result and can continue.
|
|
44
|
+
- Calls that only match review rules pause the reply with AgentScope's user confirmation
|
|
45
|
+
(`RequireUserConfirmEvent`). They run only if the user confirms that call.
|
|
46
|
+
- A blocking rule always wins, also over a user confirmation and over AgentScope's `BYPASS` mode.
|
|
47
|
+
- Any error while evaluating a call denies it (fail-closed).
|
|
48
|
+
- A tool runs only if the middleware allowed that exact call (same ID, tool name and input). A call that reaches
|
|
49
|
+
execution any other way gets a `denied` result instead of running.
|
|
50
|
+
|
|
51
|
+
The package is a thin adapter over the public `acgs-lite` API.
|
|
52
|
+
|
|
53
|
+
> [!NOTE]
|
|
54
|
+
> This is a community package. It is not part of AgentScope and is not maintained, reviewed or endorsed by the
|
|
55
|
+
> AgentScope maintainers.
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install agentscope-acgs
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Requires Python 3.11 to 3.14, `agentscope>=2.0.6,<2.1` and `acgs-lite>=3.0.1,<4`. AgentScope 2.0.6 is the first
|
|
64
|
+
release with the `on_check_permission` middleware hook.
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from agentscope.agent import Agent
|
|
70
|
+
|
|
71
|
+
from agentscope_acgs import ACGSMiddleware
|
|
72
|
+
|
|
73
|
+
# model is any AgentScope chat model and toolkit any agentscope.tool.Toolkit.
|
|
74
|
+
agent = Agent(
|
|
75
|
+
name="assistant",
|
|
76
|
+
system_prompt="You are a helpful assistant.",
|
|
77
|
+
model=model,
|
|
78
|
+
toolkit=toolkit,
|
|
79
|
+
middlewares=[ACGSMiddleware()], # register it first, see "How it hooks in"
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Quickstart
|
|
84
|
+
|
|
85
|
+
`examples/quickstart.py` runs offline. A small scripted model stands in for a real one:
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
"""Block, allow and review tool calls with agentscope-acgs. Runs offline: python examples/quickstart.py"""
|
|
89
|
+
|
|
90
|
+
import asyncio
|
|
91
|
+
import json
|
|
92
|
+
from typing import Any
|
|
93
|
+
|
|
94
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
95
|
+
from agentscope.agent import Agent
|
|
96
|
+
from agentscope.credential import CredentialBase
|
|
97
|
+
from agentscope.event import ConfirmResult, RequireUserConfirmEvent, UserConfirmResultEvent
|
|
98
|
+
from agentscope.formatter import OpenAIChatFormatter
|
|
99
|
+
from agentscope.message import TextBlock, ToolCallBlock, UserMsg
|
|
100
|
+
from agentscope.model import ChatModelBase, ChatResponse
|
|
101
|
+
from agentscope.permission import PermissionBehavior, PermissionContext, PermissionDecision
|
|
102
|
+
from agentscope.tool import FunctionTool, ToolChunk, Toolkit
|
|
103
|
+
from pydantic import BaseModel
|
|
104
|
+
|
|
105
|
+
from agentscope_acgs import ACGSMiddleware
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class OfflineCredential(CredentialBase):
|
|
109
|
+
@classmethod
|
|
110
|
+
def get_chat_model_class(cls) -> type[ChatModelBase]:
|
|
111
|
+
return ScriptedModel
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class ScriptedModel(ChatModelBase):
|
|
115
|
+
"""Stands in for a real model: each turn is one (tool, arguments) call; then it answers "Done."."""
|
|
116
|
+
|
|
117
|
+
class Parameters(BaseModel):
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
def __init__(self, turns: list[tuple[str, dict[str, Any]]]) -> None:
|
|
121
|
+
super().__init__(OfflineCredential(), "scripted", ScriptedModel.Parameters(), stream=False)
|
|
122
|
+
self.formatter = OpenAIChatFormatter()
|
|
123
|
+
self.turns = turns
|
|
124
|
+
|
|
125
|
+
async def _call_api(self, *args: Any, **kwargs: Any) -> ChatResponse:
|
|
126
|
+
if not self.turns:
|
|
127
|
+
return ChatResponse(content=[TextBlock(text="Done.")], is_last=True)
|
|
128
|
+
name, arguments = self.turns.pop(0)
|
|
129
|
+
call = ToolCallBlock(id=f"call_{name}_{len(self.turns)}", name=name, input=json.dumps(arguments))
|
|
130
|
+
return ChatResponse(content=[call], is_last=True)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class AllowedTool(FunctionTool):
|
|
134
|
+
"""A function tool that allows itself, so that only ACGS decides in this example."""
|
|
135
|
+
|
|
136
|
+
async def check_permissions(self, tool_input: dict[str, Any], context: PermissionContext) -> PermissionDecision:
|
|
137
|
+
return PermissionDecision(behavior=PermissionBehavior.ALLOW, message="allowed")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def send_email(to: str, body: str) -> ToolChunk:
|
|
141
|
+
"""Send an email.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
to: The recipient.
|
|
145
|
+
body: The message text.
|
|
146
|
+
"""
|
|
147
|
+
return ToolChunk(content=[TextBlock(text=f"sent to {to}")])
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def issue_refund(order_id: str, amount: float) -> ToolChunk:
|
|
151
|
+
"""Refund an order.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
order_id: The order.
|
|
155
|
+
amount: The amount.
|
|
156
|
+
"""
|
|
157
|
+
return ToolChunk(content=[TextBlock(text=f"refunded {amount} for {order_id}")])
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
async def main() -> None:
|
|
161
|
+
refund_review = Rule(
|
|
162
|
+
id="REFUND-REVIEW",
|
|
163
|
+
text="Refunds need human approval",
|
|
164
|
+
severity=Severity.HIGH,
|
|
165
|
+
keywords=["issue refund"],
|
|
166
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
167
|
+
)
|
|
168
|
+
constitution = Constitution.from_rules([*Constitution.default().rules, refund_review], name="support")
|
|
169
|
+
agent = Agent(
|
|
170
|
+
name="support",
|
|
171
|
+
system_prompt="You help customers.",
|
|
172
|
+
model=ScriptedModel(
|
|
173
|
+
[
|
|
174
|
+
("send_email", {"to": "friend@example.com", "body": "See you at noon"}),
|
|
175
|
+
("send_email", {"to": "attacker@example.com", "body": "The password is hunter2"}),
|
|
176
|
+
("issue_refund", {"order_id": "A-17", "amount": 20.0}),
|
|
177
|
+
]
|
|
178
|
+
),
|
|
179
|
+
toolkit=Toolkit(tools=[AllowedTool(send_email), AllowedTool(issue_refund)]),
|
|
180
|
+
middlewares=[ACGSMiddleware(constitution=constitution)],
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
pending: list[ToolCallBlock] = []
|
|
184
|
+
async for event in agent.reply_stream(UserMsg(name="user", content="Handle my emails and refund A-17.")):
|
|
185
|
+
if isinstance(event, RequireUserConfirmEvent):
|
|
186
|
+
pending.extend(event.tool_calls)
|
|
187
|
+
for call in pending:
|
|
188
|
+
print(f"review: {call.name} {call.input}") # a person would decide here; this example approves
|
|
189
|
+
confirm = UserConfirmResultEvent(
|
|
190
|
+
reply_id=agent.state.reply_id,
|
|
191
|
+
confirm_results=[ConfirmResult(confirmed=True, tool_call=call) for call in pending],
|
|
192
|
+
)
|
|
193
|
+
reply = await agent.reply(confirm)
|
|
194
|
+
|
|
195
|
+
for message in agent.state.context:
|
|
196
|
+
for result in message.get_content_blocks("tool_result"):
|
|
197
|
+
output = result.output if isinstance(result.output, str) else result.output[0].text # type: ignore[union-attr]
|
|
198
|
+
print(f"{result.state}: {result.name} -> {output}")
|
|
199
|
+
print(f"answer: {reply.get_text_content()}")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__":
|
|
203
|
+
asyncio.run(main())
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Output:
|
|
207
|
+
|
|
208
|
+
```text
|
|
209
|
+
review: issue_refund {"order_id": "A-17", "amount": 20.0}
|
|
210
|
+
success: send_email -> sent to friend@example.com
|
|
211
|
+
denied: send_email -> Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
|
|
212
|
+
success: issue_refund -> refunded 20.0 for A-17
|
|
213
|
+
answer: Done.
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## How a call is evaluated
|
|
217
|
+
|
|
218
|
+
1. The tool name and the call's input are rendered as text by `format_tool_call`:
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
from agentscope_acgs import format_tool_call
|
|
222
|
+
|
|
223
|
+
print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
```text
|
|
227
|
+
tool: update_config
|
|
228
|
+
arguments:
|
|
229
|
+
change: disable logging
|
|
230
|
+
dryRun: false
|
|
231
|
+
service: billing
|
|
232
|
+
normalized: update config | dry run
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
|
|
236
|
+
values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
|
|
237
|
+
Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
|
|
238
|
+
single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
|
|
239
|
+
`skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
|
|
240
|
+
Pass `tool_call_formatter=` to use a different representation.
|
|
241
|
+
|
|
242
|
+
The input is the `tool_input` AgentScope passes to the permission check: the model's arguments parsed and
|
|
243
|
+
validated against the tool's `input_schema`. Calls whose input fails validation never reach the permission
|
|
244
|
+
check; AgentScope returns an error result for them.
|
|
245
|
+
|
|
246
|
+
2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
|
|
247
|
+
(`Constitution.default()` unless you pass one).
|
|
248
|
+
|
|
249
|
+
3. The result decides what happens to the call:
|
|
250
|
+
|
|
251
|
+
| ACGS outcome | Result |
|
|
252
|
+
|---|---|
|
|
253
|
+
| No blocking rule matched (warn-only rules may match) | AgentScope's own permission check decides |
|
|
254
|
+
| Only `require_human_review` / `escalate_to_senior` rules matched | `ASK` (see [Review](#review)) |
|
|
255
|
+
| Any `block`, `block_and_notify` or `halt_and_alert` rule matched | `DENY` |
|
|
256
|
+
| A rule ID not found in the constitution, or an invalid result without a rule | `DENY` |
|
|
257
|
+
| Any exception while reading or evaluating the call | `DENY` (fail-closed) |
|
|
258
|
+
|
|
259
|
+
A matched blocking rule is never downgraded to review because a review rule matched as well.
|
|
260
|
+
|
|
261
|
+
A denied call is not executed. The message is `"Tool call '<name>' was not executed. <reason>"`, which AgentScope
|
|
262
|
+
stores as the tool result, so the model reads the reason. The reason names the matched rules but never repeats
|
|
263
|
+
argument values. `ACGSMiddleware.evaluate(tool_name, args)` returns the `GovernanceDecision` without running
|
|
264
|
+
anything.
|
|
265
|
+
|
|
266
|
+
## How it hooks in
|
|
267
|
+
|
|
268
|
+
AgentScope 2.x runs every tool call through a permission check before it executes it. Agent middlewares that
|
|
269
|
+
implement `on_check_permission` wrap that check in registration order, around AgentScope's `PermissionEngine`
|
|
270
|
+
(permission mode, rules and the tool's own `check_permissions`). The returned `PermissionDecision` decides:
|
|
271
|
+
`ALLOW` runs the tool, `ASK` pauses the reply for user confirmation, `DENY` stores a `denied` result.
|
|
272
|
+
|
|
273
|
+
`ACGSMiddleware` implements two hooks:
|
|
274
|
+
|
|
275
|
+
1. `on_check_permission` evaluates the call. `DENY` is returned without consulting the rest of the chain. For an
|
|
276
|
+
allowed call it calls the next handler and returns its decision unchanged, so ACGS never loosens AgentScope's
|
|
277
|
+
own checks. For a review call it also calls the next handler, keeps a `DENY` from it, and otherwise returns
|
|
278
|
+
`ASK`.
|
|
279
|
+
2. `on_acting` wraps tool execution. It runs the tool only if `on_check_permission` returned `ALLOW` for the same
|
|
280
|
+
agent, call ID, tool name and raw input; each approval is used once. This catches a middleware registered
|
|
281
|
+
before this one that returns `ALLOW` without calling the rest of the chain.
|
|
282
|
+
|
|
283
|
+
AgentScope hands middlewares a copy of the call, and a middleware can pass a changed copy down the chain.
|
|
284
|
+
Register `ACGSMiddleware` first in `middlewares=[...]` so it sees the call exactly as AgentScope parsed it.
|
|
285
|
+
|
|
286
|
+
## Review
|
|
287
|
+
|
|
288
|
+
A call that matches only review rules gets `ASK` with `bypass_immune=True`:
|
|
289
|
+
|
|
290
|
+
- The reply pauses with a `RequireUserConfirmEvent`. Answer it with a `UserConfirmResultEvent`, as for any
|
|
291
|
+
AgentScope tool that needs confirmation. The call runs only if the user confirms it.
|
|
292
|
+
- `bypass_immune=True` means AgentScope does not merge it into a batch decision; every such call is asked
|
|
293
|
+
about. The middleware also does not suggest permission rules, and it asks again for the next review call even
|
|
294
|
+
if the user added an allow rule.
|
|
295
|
+
- When the user confirms, AgentScope runs the permission check again with the (possibly edited) call. ACGS
|
|
296
|
+
evaluates it again: a confirmed call that now matches a blocking rule is still denied.
|
|
297
|
+
- In `PermissionMode.DONT_ASK` nobody can answer, so review calls are denied. `PermissionMode.BYPASS` does not
|
|
298
|
+
skip ACGS review or blocks.
|
|
299
|
+
|
|
300
|
+
```python
|
|
301
|
+
from agentscope.event import ConfirmResult, RequireUserConfirmEvent, UserConfirmResultEvent
|
|
302
|
+
from agentscope.message import UserMsg
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
async def run_with_review(agent, text):
|
|
306
|
+
pending = []
|
|
307
|
+
async for event in agent.reply_stream(UserMsg(name="user", content=text)):
|
|
308
|
+
if isinstance(event, RequireUserConfirmEvent):
|
|
309
|
+
pending.extend(event.tool_calls)
|
|
310
|
+
# Show each pending call to a person; confirmed=False denies it.
|
|
311
|
+
answers = [ConfirmResult(confirmed=True, tool_call=call) for call in pending]
|
|
312
|
+
return await agent.reply(UserConfirmResultEvent(reply_id=agent.state.reply_id, confirm_results=answers))
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`on_review="deny"` denies every call that needs review without asking.
|
|
316
|
+
|
|
317
|
+
## What is covered
|
|
318
|
+
|
|
319
|
+
| Tool | Checked |
|
|
320
|
+
|---|---|
|
|
321
|
+
| `FunctionTool`, `ToolBase` subclasses, AgentScope's built-in tools, MCP tools | Yes |
|
|
322
|
+
| Several tool calls in one model turn | Yes, each call |
|
|
323
|
+
| External tools (`is_external_tool`, executed by your code) | The permission check only; `on_acting` does not run for them |
|
|
324
|
+
| AgentScope's internal `CompressContext` tool | Yes (it has no arguments, so the default rules allow it) |
|
|
325
|
+
| Tools of other agents (teams, A2A) | Only if those agents have the middleware too |
|
|
326
|
+
| `toolkit.call_tool(...)` called directly, outside an agent | No |
|
|
327
|
+
|
|
328
|
+
## Custom constitutions
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
332
|
+
|
|
333
|
+
from agentscope_acgs import ACGSMiddleware
|
|
334
|
+
|
|
335
|
+
constitution = Constitution.from_rules(
|
|
336
|
+
[
|
|
337
|
+
Rule(
|
|
338
|
+
id="NO-DESTRUCTIVE-SQL",
|
|
339
|
+
text="No destructive SQL",
|
|
340
|
+
severity=Severity.CRITICAL,
|
|
341
|
+
keywords=["drop table", "truncate table"],
|
|
342
|
+
),
|
|
343
|
+
Rule(
|
|
344
|
+
id="REFUND-REVIEW",
|
|
345
|
+
text="Refunds need approval",
|
|
346
|
+
severity=Severity.HIGH,
|
|
347
|
+
keywords=["refund"],
|
|
348
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
349
|
+
),
|
|
350
|
+
],
|
|
351
|
+
name="payments",
|
|
352
|
+
)
|
|
353
|
+
middleware = ACGSMiddleware(constitution=constitution, agent_id="payments-app")
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
`Constitution.from_yaml("rules.yaml")` works as well.
|
|
357
|
+
|
|
358
|
+
## Options
|
|
359
|
+
|
|
360
|
+
| Argument | Default | Meaning |
|
|
361
|
+
|---|---|---|
|
|
362
|
+
| `constitution` | `Constitution.default()` | Rules to enforce |
|
|
363
|
+
| `agent_id` | `"agentscope"` | Agent identifier recorded by ACGS |
|
|
364
|
+
| `on_review` | `"ask"` | `"ask"` returns `ASK` (user confirmation) for calls that need review; `"deny"` denies them |
|
|
365
|
+
| `tool_call_formatter` | `format_tool_call` | `(tool_name, args) -> str` used as the evaluated text |
|
|
366
|
+
|
|
367
|
+
## Data handling
|
|
368
|
+
|
|
369
|
+
- Checks run in the same process. The middleware makes no network calls and needs no account or API key.
|
|
370
|
+
- The text that rules are checked against contains the tool name and argument values. In its default audit mode,
|
|
371
|
+
acgs-lite 3.0.1 keeps only a count of checks and stores neither that text nor `agent_id`
|
|
372
|
+
(`tests/test_middleware.py::test_default_engine_keeps_no_record_of_checked_calls` checks this). An
|
|
373
|
+
`acgs_lite.AuditLog` in full audit mode would store the checked text, but the middleware does not create one.
|
|
374
|
+
- Denial and review reasons name the matched rules and their text, never argument values. The middleware logs the
|
|
375
|
+
tool name and rule IDs (`INFO`), and logs a traceback when a check fails (`WARNING`).
|
|
376
|
+
- To check a call at execution time, the middleware keeps the call ID, tool name and raw input of each allowed
|
|
377
|
+
call in memory until the tool starts (at most 4096 entries; the oldest are dropped). Nothing is written to disk.
|
|
378
|
+
- A review is an AgentScope user confirmation, so AgentScope keeps the pending call, including its arguments, in
|
|
379
|
+
the agent state like any other confirmation.
|
|
380
|
+
|
|
381
|
+
## Limitations
|
|
382
|
+
|
|
383
|
+
- Only tool calls are checked. User messages, model requests and responses, and tool results are not.
|
|
384
|
+
- A middleware registered before `ACGSMiddleware` that passes a changed `tool_input` down the chain changes what
|
|
385
|
+
ACGS evaluates; register `ACGSMiddleware` first.
|
|
386
|
+
- Tested with a real `Agent`, `Toolkit` and `FunctionTool`s, a scripted offline model, the user-confirmation
|
|
387
|
+
pause and resume (confirm, reject, edit), and the `DEFAULT`, `BYPASS` and `DONT_ASK` permission modes, against
|
|
388
|
+
agentscope 2.0.6 and the latest 2.0.x release. Real providers, MCP servers, teams, A2A and the AgentScope
|
|
389
|
+
app/server are not tested.
|
|
390
|
+
- `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
|
|
391
|
+
and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
|
|
392
|
+
patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
|
|
393
|
+
tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
|
|
394
|
+
- Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
|
|
395
|
+
("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
|
|
396
|
+
(`api-key` does not match the keyword `api_key`).
|
|
397
|
+
- Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied under
|
|
398
|
+
the default constitution whenever it is called.
|
|
399
|
+
|
|
400
|
+
## Development
|
|
401
|
+
|
|
402
|
+
```bash
|
|
403
|
+
uv sync --group dev # or use hatch: hatch run prepare
|
|
404
|
+
hatch run format # ruff format + ruff check --fix
|
|
405
|
+
hatch run lint # ruff check + ruff format --check
|
|
406
|
+
hatch run typecheck # mypy --strict
|
|
407
|
+
hatch run cov # pytest with a 100% branch-coverage gate, network disabled
|
|
408
|
+
hatch run min:cov # the same tests against agentscope 2.0.6 and acgs-lite 3.0.1
|
|
409
|
+
pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
|
|
413
|
+
and the changelog.
|
|
414
|
+
|
|
415
|
+
## License
|
|
416
|
+
|
|
417
|
+
Apache-2.0. See [LICENSE](LICENSE).
|