strands-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.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .coverage
8
+ coverage.xml
9
+ htmlcov/
10
+ .mypy_cache/
11
+ .pytest_cache/
12
+ .ruff_cache/
@@ -0,0 +1,17 @@
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 (unreleased)
10
+
11
+ ### Added
12
+
13
+ - `ACGSIntervention`, a Strands `InterventionHandler` that maps ACGS verdicts to `Proceed`, `Deny` and `Confirm`
14
+ in `before_tool_call`.
15
+ - `format_tool_call`, the documented text representation of a tool call that ACGS rules are evaluated against.
16
+ - Fail-closed handling: errors during evaluation return `Deny`, and `on_error` is `"deny"`.
17
+ - `on_review` (`"confirm"` or `"deny"`) and `confirm_evaluate` options for rules that require human review.
@@ -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,278 @@
1
+ Metadata-Version: 2.5
2
+ Name: strands-acgs
3
+ Version: 0.1.0
4
+ Summary: ACGS rule-based tool-call governance for Strands Agents, as an intervention handler
5
+ Project-URL: Homepage, https://github.com/acgs-ai/strands-acgs
6
+ Project-URL: Documentation, https://github.com/acgs-ai/strands-acgs#readme
7
+ Project-URL: Repository, https://github.com/acgs-ai/strands-acgs
8
+ Project-URL: Issues, https://github.com/acgs-ai/strands-acgs/issues
9
+ Project-URL: Changelog, https://github.com/acgs-ai/strands-acgs/blob/main/CHANGELOG.md
10
+ Author: Martin Lyu
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: acgs,agents,ai,governance,intervention,strands
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: acgs-lite<4,>=3.0.1
24
+ Requires-Dist: strands-agents>=1.43.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: commitizen<5.0.0,>=4.0.0; extra == 'dev'
27
+ Requires-Dist: hatch; extra == 'dev'
28
+ Requires-Dist: mypy<2.0.0,>=1.15.0; extra == 'dev'
29
+ Requires-Dist: pre-commit<5.0.0,>=4.0.0; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio<2.0.0,>=0.25.0; extra == 'dev'
31
+ Requires-Dist: pytest-cov<8.0.0,>=6.0.0; extra == 'dev'
32
+ Requires-Dist: pytest<10.0.0,>=8.0.0; extra == 'dev'
33
+ Requires-Dist: ruff<1.0.0,>=0.11.0; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # strands-acgs
37
+
38
+ [![CI](https://github.com/acgs-ai/strands-acgs/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/acgs-ai/strands-acgs/actions/workflows/ci.yml)
39
+ [![PyPI - Version](https://img.shields.io/pypi/v/strands-acgs.svg)](https://pypi.org/project/strands-acgs)
40
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/strands-acgs.svg)](https://pypi.org/project/strands-acgs)
41
+
42
+ Rule-based checks for the tool calls a [Strands Agents](https://strandsagents.com) agent makes, using the
43
+ [ACGS](https://pypi.org/project/acgs-lite/) constitution engine from `acgs-lite`.
44
+
45
+ `strands-acgs` provides one class, `ACGSIntervention`, an `InterventionHandler` that implements
46
+ `before_tool_call`. It returns the native intervention actions `Proceed`, `Deny` and `Confirm`, so denials and
47
+ human review use the Strands intervention and interrupt system. It does not wrap the agent, the model, or the tools.
48
+
49
+ - [Installation](#installation)
50
+ - [Usage](#usage)
51
+ - [How a tool call is evaluated](#how-a-tool-call-is-evaluated)
52
+ - [Human review](#human-review)
53
+ - [Custom constitutions](#custom-constitutions)
54
+ - [Limitations](#limitations)
55
+ - [Development](#development)
56
+ - [License](#license)
57
+
58
+ ## Installation
59
+
60
+ ```console
61
+ pip install strands-acgs
62
+ ```
63
+
64
+ Requires Python 3.10+, `strands-agents>=1.43.0` (the first release with interventions) and `acgs-lite>=3.0.1`.
65
+
66
+ ## Usage
67
+
68
+ The example below runs offline. `ScriptedModel` stands in for an LLM; in real use, pass any Strands model
69
+ provider instead, or omit `model` to use the default. The same file is in
70
+ [`examples/quickstart.py`](examples/quickstart.py) and is executed by the test suite.
71
+
72
+ ```python
73
+ import json
74
+ from typing import Any
75
+
76
+ from strands import Agent, tool
77
+ from strands.models import Model
78
+
79
+ from strands_acgs import ACGSIntervention
80
+
81
+
82
+ @tool
83
+ def get_weather(city: str) -> str:
84
+ """Return the weather for a city.
85
+
86
+ Args:
87
+ city: City name.
88
+ """
89
+ return f"Sunny in {city}"
90
+
91
+
92
+ @tool
93
+ def send_email(to: str, body: str) -> str:
94
+ """Send an email.
95
+
96
+ Args:
97
+ to: Recipient.
98
+ body: Message body.
99
+ """
100
+ return f"Email sent to {to}"
101
+
102
+
103
+ class ScriptedModel(Model):
104
+ """Requests two tool calls on the first turn, then answers with text."""
105
+
106
+ def __init__(self) -> None:
107
+ self.turn = 0
108
+
109
+ def update_config(self, **model_config: Any) -> None:
110
+ pass
111
+
112
+ def get_config(self) -> Any:
113
+ return {}
114
+
115
+ async def structured_output(self, *args: Any, **kwargs: Any) -> Any:
116
+ raise NotImplementedError
117
+
118
+ async def stream(self, messages: Any, *args: Any, **kwargs: Any) -> Any:
119
+ self.turn += 1
120
+ yield {"messageStart": {"role": "assistant"}}
121
+ if self.turn > 1:
122
+ yield {"contentBlockStart": {"start": {}}}
123
+ yield {"contentBlockDelta": {"delta": {"text": "Done."}}}
124
+ yield {"contentBlockStop": {}}
125
+ yield {"messageStop": {"stopReason": "end_turn"}}
126
+ return
127
+ calls = [
128
+ ("1", "get_weather", {"city": "Paris"}),
129
+ ("2", "send_email", {"to": "ops@example.com", "body": "password: hunter2"}),
130
+ ]
131
+ for tool_use_id, name, tool_input in calls:
132
+ yield {"contentBlockStart": {"start": {"toolUse": {"name": name, "toolUseId": tool_use_id}}}}
133
+ yield {"contentBlockDelta": {"delta": {"toolUse": {"input": json.dumps(tool_input)}}}}
134
+ yield {"contentBlockStop": {}}
135
+ yield {"messageStop": {"stopReason": "tool_use"}}
136
+
137
+
138
+ agent = Agent(
139
+ model=ScriptedModel(),
140
+ tools=[get_weather, send_email],
141
+ interventions=[ACGSIntervention()],
142
+ callback_handler=None,
143
+ )
144
+
145
+ agent("Check the weather in Paris and email ops the password.")
146
+ for message in agent.messages:
147
+ for block in message["content"]:
148
+ if "toolResult" in block:
149
+ result = block["toolResult"]
150
+ print(f"{result['toolUseId']}: {result['status']}: {result['content'][0]['text']}")
151
+ ```
152
+
153
+ Output:
154
+
155
+ ```text
156
+ 1: success: Sunny in Paris
157
+ 2: error: DENIED: Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
158
+ ```
159
+
160
+ The denied call never runs. Strands cancels it and returns an error tool result with the reason, so the model sees
161
+ why the call was refused. Argument values are not included in the reason.
162
+
163
+ ## How a tool call is evaluated
164
+
165
+ 1. `event.tool_use["name"]` and `event.tool_use["input"]` are rendered as text by `format_tool_call`:
166
+
167
+ ```python
168
+ from strands_acgs import format_tool_call
169
+
170
+ print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
171
+ ```
172
+
173
+ ```text
174
+ tool: update_config
175
+ arguments:
176
+ change: disable logging
177
+ dryRun: false
178
+ service: billing
179
+ normalized: update config | dry run
180
+ ```
181
+
182
+ Each input leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
183
+ values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
184
+ Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
185
+ single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
186
+ `skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
187
+ Pass `tool_call_formatter=` to use a different representation.
188
+
189
+ 2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
190
+ (`Constitution.default()` unless you pass one).
191
+
192
+ 3. The result is mapped to an intervention action:
193
+
194
+ | ACGS outcome | Action |
195
+ |---|---|
196
+ | No blocking rule matched (warn-only rules may match) | `Proceed` |
197
+ | Only `require_human_review` / `escalate_to_senior` rules matched | `Confirm` (or `Deny` with `on_review="deny"`) |
198
+ | Any `block`, `block_and_notify` or `halt_and_alert` rule matched | `Deny` |
199
+ | A rule ID not found in the constitution, or an invalid result without a rule | `Deny` |
200
+ | Any exception while reading or evaluating the tool call | `Deny` (fail-closed) |
201
+
202
+ A matched blocking rule is never downgraded to review because a review rule matched as well. The handler's
203
+ `on_error` is `"deny"`, so an exception that escapes the handler is also turned into a denial by Strands.
204
+
205
+ `ACGSIntervention.evaluate(tool_name, tool_input)` returns the underlying `GovernanceDecision`
206
+ (`verdict`, `reason`, `rule_ids`, `warning_rule_ids`, `error`) without running anything.
207
+
208
+ ## Human review
209
+
210
+ Rules whose workflow action is `require_human_review` or `escalate_to_senior` (in the default constitution:
211
+ `ACGS-002` and `ACGS-005`) produce `Confirm`. Strands then stops the invocation with
212
+ `stop_reason == "interrupt"`; resume it with the human's answer:
213
+
214
+ ```python
215
+ result = agent("Turn off logging for the billing service")
216
+ if result.stop_reason == "interrupt":
217
+ interrupt = result.interrupts[0] # interrupt.name == "acgs-governance"
218
+ print(interrupt.reason) # which rule asked for review
219
+ answer = "yes" # collect this from a person
220
+ result = agent([{"interruptResponse": {"interruptId": interrupt.id, "response": answer}}])
221
+ ```
222
+
223
+ By default `True`, `"y"` and `"yes"` approve; anything else cancels the call. Pass
224
+ `confirm_evaluate=` to change that, or `on_review="deny"` to deny review verdicts without asking.
225
+
226
+ ## Custom constitutions
227
+
228
+ ```python
229
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
230
+
231
+ from strands_acgs import ACGSIntervention
232
+
233
+ constitution = Constitution.from_rules(
234
+ [
235
+ Rule(id="NO-DESTRUCTIVE-SQL", text="No destructive SQL", severity=Severity.CRITICAL,
236
+ keywords=["drop table", "truncate table"]),
237
+ Rule(id="REFUND-REVIEW", text="Refunds need approval", severity=Severity.HIGH,
238
+ keywords=["refund"], workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW),
239
+ ],
240
+ name="payments",
241
+ )
242
+ handler = ACGSIntervention(constitution=constitution, agent_id="payments-agent")
243
+ ```
244
+
245
+ `Constitution.from_yaml("rules.yaml")` works as well. To register several handlers on one agent, give each a
246
+ distinct `name`.
247
+
248
+ ## Limitations
249
+
250
+ - `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
251
+ and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
252
+ patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
253
+ tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
254
+ - Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
255
+ ("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
256
+ (`api-key` does not match the keyword `api_key`).
257
+ - Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied under
258
+ the default constitution whenever it is called.
259
+ - Interventions run in registration order and see changes made by earlier `Transform` actions. Handlers or
260
+ plain hooks that modify `tool_use` after this handler are not re-checked, so register `ACGSIntervention` after
261
+ any handler that rewrites tool input.
262
+
263
+ ## Development
264
+
265
+ ```console
266
+ hatch run prepare # format, lint, mypy --strict, tests with coverage (fails under 95%)
267
+ hatch run lint # ruff check + format check
268
+ hatch run typecheck # mypy --strict
269
+ hatch run cov # pytest with coverage
270
+ hatch run min:test # tests against strands-agents 1.43.0 and acgs-lite 3.0.1
271
+ pre-commit install # format/lint/typecheck/test on commit, commitizen on commit messages
272
+ ```
273
+
274
+ Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/) and are checked by commitizen.
275
+
276
+ ## License
277
+
278
+ `strands-acgs` is distributed under the terms of the [Apache-2.0](LICENSE) license.