acgs-haystack 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,18 @@
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/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - Unreleased
10
+
11
+ ### Added
12
+
13
+ - `ACGSConfirmationStrategy`, a Haystack Human-in-the-Loop `ConfirmationStrategy` for use with the native
14
+ `ConfirmationHook` at the `before_tool` hook point.
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 or review reject the tool call.
17
+ - Optional `review_strategy` for rules that require human review; modified parameters are evaluated again.
18
+ - `to_dict` / `from_dict` serialization.
@@ -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,256 @@
1
+ Metadata-Version: 2.5
2
+ Name: acgs-haystack
3
+ Version: 0.1.0
4
+ Summary: ACGS rule-based tool-call governance for the Haystack Agent before_tool hook
5
+ Project-URL: Documentation, https://github.com/acgs-ai/acgs-haystack#readme
6
+ Project-URL: Issues, https://github.com/acgs-ai/acgs-haystack/issues
7
+ Project-URL: Source, https://github.com/acgs-ai/acgs-haystack
8
+ Project-URL: Changelog, https://github.com/acgs-ai/acgs-haystack/blob/main/CHANGELOG.md
9
+ Author: Martin Lyu
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: acgs,agents,governance,haystack,human-in-the-loop,tool-calling
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: acgs-lite<4,>=3.0.1
23
+ Requires-Dist: haystack-ai>=3.0.0
24
+ Description-Content-Type: text/markdown
25
+
26
+ # acgs-haystack
27
+
28
+ [![CI](https://github.com/acgs-ai/acgs-haystack/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/acgs-ai/acgs-haystack/actions/workflows/ci.yml)
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/acgs-haystack.svg)](https://pypi.org/project/acgs-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/acgs-haystack.svg)](https://pypi.org/project/acgs-haystack)
31
+
32
+ Rule-based checks for the tool calls a Haystack `Agent` makes, using the [ACGS](https://pypi.org/project/acgs-lite/)
33
+ constitution engine from `acgs-lite`.
34
+
35
+ `acgs-haystack` provides one class, `ACGSConfirmationStrategy`. It plugs into Haystack's own
36
+ `ConfirmationHook` at the `before_tool` hook point, so tool calls are approved, rejected, or sent to a human
37
+ reviewer using the same mechanism as Haystack's Human-in-the-Loop confirmation. It does not wrap the `Agent`,
38
+ its tools, or the chat generator.
39
+
40
+ - [Installation](#installation)
41
+ - [Usage](#usage)
42
+ - [How a tool call is evaluated](#how-a-tool-call-is-evaluated)
43
+ - [Human review](#human-review)
44
+ - [Custom constitutions](#custom-constitutions)
45
+ - [Limitations](#limitations)
46
+ - [Development](#development)
47
+ - [License](#license)
48
+
49
+ ## Installation
50
+
51
+ ```console
52
+ pip install acgs-haystack
53
+ ```
54
+
55
+ Requires Python 3.11+, `haystack-ai>=3.0.0` and `acgs-lite>=3.0.1`.
56
+
57
+ ## Usage
58
+
59
+ The example below runs offline. `ScriptedChatGenerator` stands in for an LLM; in real use, pass any Haystack chat
60
+ generator instead (for example `OpenAIChatGenerator`). The same file is in
61
+ [`examples/quickstart.py`](examples/quickstart.py) and is executed by the test suite.
62
+
63
+ ```python
64
+ from typing import Annotated, Any
65
+
66
+ from haystack import component
67
+ from haystack.components.agents import Agent
68
+ from haystack.dataclasses import ChatMessage, ToolCall
69
+ from haystack.hooks.human_in_the_loop import ConfirmationHook
70
+ from haystack.tools import tool
71
+
72
+ from haystack_integrations.hooks.acgs import ACGSConfirmationStrategy
73
+
74
+
75
+ @tool
76
+ def get_weather(city: Annotated[str, "City name"]) -> str:
77
+ """Return the weather for a city."""
78
+ return f"Sunny in {city}"
79
+
80
+
81
+ @tool
82
+ def send_email(to: Annotated[str, "Recipient"], body: Annotated[str, "Message body"]) -> str:
83
+ """Send an email."""
84
+ return f"Email sent to {to}"
85
+
86
+
87
+ @component
88
+ class ScriptedChatGenerator:
89
+ """Requests two tool calls on the first step, then answers with text."""
90
+
91
+ def __init__(self) -> None:
92
+ self.step = 0
93
+
94
+ @component.output_types(replies=list[ChatMessage])
95
+ def run(self, messages: list[ChatMessage], tools: Any = None, **kwargs: Any) -> dict[str, Any]:
96
+ self.step += 1
97
+ if self.step > 1:
98
+ return {"replies": [ChatMessage.from_assistant("Done.")]}
99
+ calls = [
100
+ ToolCall(id="1", tool_name="get_weather", arguments={"city": "Paris"}),
101
+ ToolCall(id="2", tool_name="send_email", arguments={"to": "ops@example.com", "body": "password: hunter2"}),
102
+ ]
103
+ return {"replies": [ChatMessage.from_assistant(tool_calls=calls)]}
104
+
105
+
106
+ agent = Agent(
107
+ chat_generator=ScriptedChatGenerator(),
108
+ tools=[get_weather, send_email],
109
+ hooks={"before_tool": [ConfirmationHook(confirmation_strategies={"*": ACGSConfirmationStrategy()})]},
110
+ )
111
+
112
+ result = agent.run(messages=[ChatMessage.from_user("Check the weather in Paris and email ops the password.")])
113
+ for message in result["messages"]:
114
+ for tool_result in message.tool_call_results:
115
+ status = "rejected" if tool_result.error else "ran"
116
+ print(f"{tool_result.origin.tool_name}: {status}: {tool_result.result}")
117
+ ```
118
+
119
+ Output:
120
+
121
+ ```text
122
+ send_email: rejected: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
123
+ get_weather: ran: Sunny in Paris
124
+ ```
125
+
126
+ The rejected call never runs. `ConfirmationHook` replaces it with an error tool result carrying the reason, so the
127
+ model sees why the call was refused and can continue. Argument values are not included in the reason.
128
+
129
+ To govern only some tools, use tool names or tuples of tool names instead of `"*"` as keys of
130
+ `confirmation_strategies`. Note that a more specific key takes precedence over `"*"`: a tool with its own entry is
131
+ not checked by an ACGS strategy registered under `"*"`.
132
+
133
+ ## How a tool call is evaluated
134
+
135
+ 1. The tool name and arguments are rendered as text by `format_tool_call`:
136
+
137
+ ```python
138
+ from haystack_integrations.hooks.acgs import format_tool_call
139
+
140
+ print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
141
+ ```
142
+
143
+ ```text
144
+ tool: update_config
145
+ arguments:
146
+ change: disable logging
147
+ dryRun: false
148
+ service: billing
149
+ normalized: update config | dry run
150
+ ```
151
+
152
+ Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
153
+ values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
154
+ Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
155
+ single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
156
+ `skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
157
+ Pass `tool_call_formatter=` to use a different representation.
158
+
159
+ 2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
160
+ (`Constitution.default()` unless you pass one).
161
+
162
+ 3. The result is mapped to a Haystack `ToolExecutionDecision`:
163
+
164
+ | ACGS outcome | Decision |
165
+ |---|---|
166
+ | No blocking rule matched (warn-only rules may match) | execute with the original parameters |
167
+ | Only `require_human_review` / `escalate_to_senior` rules matched | send to `review_strategy`; reject if none is configured |
168
+ | Any `block`, `block_and_notify` or `halt_and_alert` rule matched | reject |
169
+ | A rule ID not found in the constitution, or an invalid result without a rule | reject |
170
+ | Any exception while formatting, validating, or reviewing | reject (fail-closed) |
171
+
172
+ A matched blocking rule is never downgraded to review because a review rule matched as well.
173
+
174
+ `ACGSConfirmationStrategy.evaluate(tool_name, params)` returns the underlying `GovernanceDecision`
175
+ (`verdict`, `reason`, `rule_ids`, `warning_rule_ids`, `error`) without running anything.
176
+
177
+ ## Human review
178
+
179
+ Rules whose workflow action is `require_human_review` or `escalate_to_senior` (in the default constitution:
180
+ `ACGS-002` and `ACGS-005`) produce a review verdict. Pass a native Haystack confirmation strategy to handle it:
181
+
182
+ ```python
183
+ from haystack.hooks.human_in_the_loop import AlwaysAskPolicy, BlockingConfirmationStrategy, SimpleConsoleUI
184
+
185
+ from haystack_integrations.hooks.acgs import ACGSConfirmationStrategy
186
+
187
+ strategy = ACGSConfirmationStrategy(
188
+ review_strategy=BlockingConfirmationStrategy(
189
+ confirmation_policy=AlwaysAskPolicy(), confirmation_ui=SimpleConsoleUI()
190
+ )
191
+ )
192
+ ```
193
+
194
+ The reviewer is only consulted for review verdicts. If the reviewer modifies the parameters, the modified call is
195
+ evaluated again and rejected if a blocking rule matches. Use `AlwaysAskPolicy`: with `NeverAskPolicy` the
196
+ review strategy approves without asking.
197
+
198
+ ## Custom constitutions
199
+
200
+ ```python
201
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
202
+
203
+ from haystack_integrations.hooks.acgs import ACGSConfirmationStrategy
204
+
205
+ constitution = Constitution.from_rules(
206
+ [
207
+ Rule(
208
+ id="NO-DESTRUCTIVE-SQL",
209
+ text="No destructive SQL",
210
+ severity=Severity.CRITICAL,
211
+ keywords=["drop table", "truncate table"],
212
+ ),
213
+ Rule(
214
+ id="REFUND-REVIEW",
215
+ text="Refunds need approval",
216
+ severity=Severity.HIGH,
217
+ keywords=["refund"],
218
+ workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
219
+ ),
220
+ ],
221
+ name="payments",
222
+ )
223
+ strategy = ACGSConfirmationStrategy(constitution=constitution, agent_id="payments-agent")
224
+ ```
225
+
226
+ `Constitution.from_yaml("rules.yaml")` works as well. The strategy supports `to_dict` / `from_dict`, so an
227
+ `Agent` using it can be serialized; the constitution is stored as YAML.
228
+
229
+ ## Limitations
230
+
231
+ - `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
232
+ and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
233
+ patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
234
+ tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
235
+ - Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
236
+ ("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
237
+ (`api-key` does not match the keyword `api_key`).
238
+ - Because argument names are part of the evaluated text, a tool with a parameter named `password` is rejected
239
+ under the default constitution whenever it is called.
240
+ - Tool calls naming a tool the Agent does not have are passed through by `ConfirmationHook` without consulting any
241
+ strategy; Haystack then reports them as unknown tools and they do not run.
242
+ - Other `before_tool` hooks registered after the `ConfirmationHook` can still rewrite tool calls. Register
243
+ the ACGS hook last if other hooks modify tool calls.
244
+
245
+ ## Development
246
+
247
+ ```console
248
+ hatch run fmt-check # ruff lint + format check
249
+ hatch run test:types # mypy --strict
250
+ hatch run test:cov # pytest with coverage (fails under 95%)
251
+ hatch run test-min:all # tests against haystack-ai 3.0.0 and acgs-lite 3.0.1
252
+ ```
253
+
254
+ ## License
255
+
256
+ `acgs-haystack` is distributed under the terms of the [Apache-2.0](LICENSE) license.