acgs-haystack 0.1.0__py3-none-any.whl
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.
- acgs_haystack-0.1.0.dist-info/METADATA +256 -0
- acgs_haystack-0.1.0.dist-info/RECORD +8 -0
- acgs_haystack-0.1.0.dist-info/WHEEL +4 -0
- acgs_haystack-0.1.0.dist-info/licenses/LICENSE +175 -0
- haystack_integrations/hooks/acgs/__init__.py +20 -0
- haystack_integrations/hooks/acgs/_governance.py +302 -0
- haystack_integrations/hooks/acgs/py.typed +0 -0
- haystack_integrations/hooks/acgs/strategy.py +243 -0
|
@@ -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
|
+
[](https://github.com/acgs-ai/acgs-haystack/actions/workflows/ci.yml)
|
|
29
|
+
[](https://pypi.org/project/acgs-haystack)
|
|
30
|
+
[](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.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
haystack_integrations/hooks/acgs/__init__.py,sha256=nMWTaawsbrcQYpCqNRvEniLNrrOMSI69Zpj5st5pIQc,534
|
|
2
|
+
haystack_integrations/hooks/acgs/_governance.py,sha256=98Sa1in_ntbUDA5DYrMnh9dBPn9hSi5NtXOPsm1mwP8,12370
|
|
3
|
+
haystack_integrations/hooks/acgs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
haystack_integrations/hooks/acgs/strategy.py,sha256=eF_vdMWUMyqaR-wu8IYO48S6YncESZ06uETsULfbwaw,11472
|
|
5
|
+
acgs_haystack-0.1.0.dist-info/METADATA,sha256=XAziVEdD6Fn2HQpWxpSnhsvBd4egKJo4Akipk83_EGQ,10859
|
|
6
|
+
acgs_haystack-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
7
|
+
acgs_haystack-0.1.0.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
|
|
8
|
+
acgs_haystack-0.1.0.dist-info/RECORD,,
|
|
@@ -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,20 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ACGS Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""ACGS governance for the Haystack ``Agent`` ``before_tool`` hook point."""
|
|
5
|
+
|
|
6
|
+
from haystack_integrations.hooks.acgs._governance import (
|
|
7
|
+
GovernanceDecision,
|
|
8
|
+
ToolCallFormatter,
|
|
9
|
+
Verdict,
|
|
10
|
+
format_tool_call,
|
|
11
|
+
)
|
|
12
|
+
from haystack_integrations.hooks.acgs.strategy import ACGSConfirmationStrategy
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ACGSConfirmationStrategy",
|
|
16
|
+
"GovernanceDecision",
|
|
17
|
+
"ToolCallFormatter",
|
|
18
|
+
"Verdict",
|
|
19
|
+
"format_tool_call",
|
|
20
|
+
]
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ACGS Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""
|
|
5
|
+
Framework-neutral evaluation of a single tool call against an ACGS constitution.
|
|
6
|
+
|
|
7
|
+
This module only calls the public API of the ``acgs-lite`` package (``Constitution``,
|
|
8
|
+
``GovernanceEngine.validate`` and the result types it returns). It turns one tool call
|
|
9
|
+
into a text representation, validates that text, and maps the result to one of three
|
|
10
|
+
verdicts that the framework adapters translate into native decisions.
|
|
11
|
+
|
|
12
|
+
The evaluation never raises: any error is converted into a ``DENY`` verdict.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from enum import Enum
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from acgs_lite import (
|
|
26
|
+
Constitution,
|
|
27
|
+
ConstitutionalViolationError,
|
|
28
|
+
GovernanceEngine,
|
|
29
|
+
Rule,
|
|
30
|
+
ValidationResult,
|
|
31
|
+
ViolationAction,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
ToolCallFormatter = Callable[[str, Any], str]
|
|
37
|
+
"""Signature of a function that renders ``(tool_name, arguments)`` as the text ACGS validates."""
|
|
38
|
+
|
|
39
|
+
MAX_ARGUMENT_DEPTH = 32
|
|
40
|
+
"""Nesting depth above which a tool call is rejected instead of being partially rendered."""
|
|
41
|
+
|
|
42
|
+
_DENY_ACTIONS = frozenset({ViolationAction.BLOCK, ViolationAction.BLOCK_AND_NOTIFY, ViolationAction.HALT})
|
|
43
|
+
_REVIEW_ACTIONS = frozenset({ViolationAction.REQUIRE_HUMAN_REVIEW, ViolationAction.ESCALATE})
|
|
44
|
+
|
|
45
|
+
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
|
|
46
|
+
_SEPARATORS = re.compile(r"[\s_\-./:\[\]]+")
|
|
47
|
+
_IDENTIFIER_VALUE = re.compile(r"^[A-Za-z][A-Za-z0-9]*(?:[_-][A-Za-z0-9]+|[A-Z][a-z0-9]+)+$")
|
|
48
|
+
_MAX_IDENTIFIER_VALUE_LENGTH = 64
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Verdict(str, Enum): # noqa: UP042 # StrEnum needs Python 3.11; this module is shared with a 3.10 package
|
|
52
|
+
"""Outcome of evaluating one tool call."""
|
|
53
|
+
|
|
54
|
+
ALLOW = "allow"
|
|
55
|
+
"""No blocking rule matched. Warnings may still have been recorded."""
|
|
56
|
+
|
|
57
|
+
DENY = "deny"
|
|
58
|
+
"""A blocking rule matched, or governance could not be evaluated."""
|
|
59
|
+
|
|
60
|
+
REVIEW = "review"
|
|
61
|
+
"""Only review/escalation rules matched. A human must approve the call."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class GovernanceDecision:
|
|
66
|
+
"""
|
|
67
|
+
Result of evaluating one tool call.
|
|
68
|
+
|
|
69
|
+
:param verdict: The verdict the adapter maps to a native framework decision.
|
|
70
|
+
:param tool_name: Name of the evaluated tool.
|
|
71
|
+
:param reason: Human-readable explanation. It names matched rules but never includes argument values.
|
|
72
|
+
:param rule_ids: IDs of the blocking or review rules that matched, in match order.
|
|
73
|
+
:param warning_rule_ids: IDs of non-blocking (warn) rules that matched.
|
|
74
|
+
:param error: Set when the verdict is ``DENY`` because evaluation itself failed.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
verdict: Verdict
|
|
78
|
+
tool_name: str
|
|
79
|
+
reason: str
|
|
80
|
+
rule_ids: tuple[str, ...] = ()
|
|
81
|
+
warning_rule_ids: tuple[str, ...] = ()
|
|
82
|
+
error: str | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _humanize(identifier: str) -> str:
|
|
86
|
+
"""Split an identifier such as ``skip_audit`` or ``disableLogging`` into lower-case words."""
|
|
87
|
+
spaced = _CAMEL_BOUNDARY.sub(" ", identifier)
|
|
88
|
+
return " ".join(_SEPARATORS.sub(" ", spaced).split()).lower()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _render_scalar(value: Any) -> str:
|
|
92
|
+
"""Render a leaf value on a single line."""
|
|
93
|
+
if isinstance(value, str):
|
|
94
|
+
return " ".join(value.split())
|
|
95
|
+
if value is None or isinstance(value, bool | int | float):
|
|
96
|
+
return json.dumps(value)
|
|
97
|
+
return " ".join(str(value).split())
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _flatten(value: Any, path: str, depth: int) -> Iterator[tuple[str, Any]]:
|
|
101
|
+
"""Yield ``(dotted_path, leaf_value)`` pairs for nested mappings and sequences."""
|
|
102
|
+
if depth > MAX_ARGUMENT_DEPTH:
|
|
103
|
+
msg = f"Tool call arguments are nested deeper than {MAX_ARGUMENT_DEPTH} levels."
|
|
104
|
+
raise ValueError(msg)
|
|
105
|
+
if isinstance(value, Mapping):
|
|
106
|
+
if not value:
|
|
107
|
+
yield path, "{}"
|
|
108
|
+
return
|
|
109
|
+
for key in sorted(value, key=str):
|
|
110
|
+
child = f"{path}.{key}" if path else str(key)
|
|
111
|
+
yield from _flatten(value[key], child, depth + 1)
|
|
112
|
+
elif isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):
|
|
113
|
+
if not value:
|
|
114
|
+
yield path, "[]"
|
|
115
|
+
return
|
|
116
|
+
for index, item in enumerate(value):
|
|
117
|
+
yield from _flatten(item, f"{path}[{index}]", depth + 1)
|
|
118
|
+
else:
|
|
119
|
+
yield path, value
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def format_tool_call(tool_name: str, arguments: Any) -> str:
|
|
123
|
+
r"""
|
|
124
|
+
Render a tool call as the text that ACGS keyword and pattern rules are matched against.
|
|
125
|
+
|
|
126
|
+
The output has one ``path: value`` line per argument leaf, so argument names and values are
|
|
127
|
+
both visible to rules, and multi-line values are collapsed onto one line. Identifiers
|
|
128
|
+
(the tool name, argument names and single-token string values) that contain separators or
|
|
129
|
+
camelCase are repeated in a trailing ``normalized:`` line as plain words, so that a rule
|
|
130
|
+
keyword such as ``skip audit`` also matches a tool named ``skip_audit``.
|
|
131
|
+
|
|
132
|
+
Example::
|
|
133
|
+
|
|
134
|
+
>>> print(format_tool_call("send_email", {"to": "a@example.com", "body": "Hi\nthere"}))
|
|
135
|
+
tool: send_email
|
|
136
|
+
arguments:
|
|
137
|
+
body: Hi there
|
|
138
|
+
to: a@example.com
|
|
139
|
+
normalized: send email
|
|
140
|
+
|
|
141
|
+
:param tool_name: Name of the tool the model wants to call.
|
|
142
|
+
:param arguments: The tool arguments, usually a mapping. Other values are rendered as ``input``.
|
|
143
|
+
:returns: The text passed to ``GovernanceEngine.validate``.
|
|
144
|
+
:raises ValueError: If the arguments are nested deeper than ``MAX_ARGUMENT_DEPTH``.
|
|
145
|
+
"""
|
|
146
|
+
lines = [f"tool: {tool_name}", "arguments:"]
|
|
147
|
+
identifiers = [tool_name]
|
|
148
|
+
leaves = list(_flatten(arguments, "" if isinstance(arguments, Mapping) else "input", 0))
|
|
149
|
+
if isinstance(arguments, Mapping) and not arguments:
|
|
150
|
+
leaves = []
|
|
151
|
+
if not leaves:
|
|
152
|
+
lines.append("(none)")
|
|
153
|
+
for path, leaf in leaves:
|
|
154
|
+
rendered = _render_scalar(leaf)
|
|
155
|
+
lines.append(f"{path}: {rendered}")
|
|
156
|
+
identifiers.append(path)
|
|
157
|
+
if (
|
|
158
|
+
isinstance(leaf, str)
|
|
159
|
+
and len(rendered) <= _MAX_IDENTIFIER_VALUE_LENGTH
|
|
160
|
+
and _IDENTIFIER_VALUE.match(rendered)
|
|
161
|
+
):
|
|
162
|
+
identifiers.append(rendered)
|
|
163
|
+
normalized: list[str] = []
|
|
164
|
+
for identifier in identifiers:
|
|
165
|
+
words = _humanize(identifier)
|
|
166
|
+
if words and words != identifier.lower() and words not in normalized:
|
|
167
|
+
normalized.append(words)
|
|
168
|
+
if normalized:
|
|
169
|
+
lines.append("normalized: " + " | ".join(normalized))
|
|
170
|
+
return "\n".join(lines)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ToolCallGovernor:
|
|
174
|
+
"""
|
|
175
|
+
Evaluate tool calls against an ACGS constitution and return a ``GovernanceDecision``.
|
|
176
|
+
|
|
177
|
+
Verdict mapping, applied to the blocking violations of the validation result:
|
|
178
|
+
|
|
179
|
+
- no violations: ``ALLOW`` (matched warn-only rules are reported in ``warning_rule_ids``);
|
|
180
|
+
- every violation comes from a rule whose workflow action is ``require_human_review`` or
|
|
181
|
+
``escalate_to_senior``: ``REVIEW``;
|
|
182
|
+
- anything else (``block``, ``block_and_notify``, ``halt_and_alert``, a rule ID that is not in
|
|
183
|
+
the constitution, an unknown action, or an invalid result without violations): ``DENY``.
|
|
184
|
+
|
|
185
|
+
A blocking rule is never downgraded to ``REVIEW`` because a review rule matched as well.
|
|
186
|
+
Any exception raised while formatting or validating also yields ``DENY``.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
def __init__(
|
|
190
|
+
self,
|
|
191
|
+
constitution: Constitution | None = None,
|
|
192
|
+
*,
|
|
193
|
+
agent_id: str,
|
|
194
|
+
tool_call_formatter: ToolCallFormatter | None = None,
|
|
195
|
+
) -> None:
|
|
196
|
+
"""
|
|
197
|
+
Create a governor.
|
|
198
|
+
|
|
199
|
+
:param constitution: The constitution to enforce. Defaults to ``Constitution.default()``.
|
|
200
|
+
:param agent_id: Agent identifier passed to ``GovernanceEngine.validate``.
|
|
201
|
+
:param tool_call_formatter: Optional replacement for ``format_tool_call``.
|
|
202
|
+
"""
|
|
203
|
+
self.constitution = constitution if constitution is not None else Constitution.default()
|
|
204
|
+
self.agent_id = agent_id
|
|
205
|
+
self.tool_call_formatter = tool_call_formatter
|
|
206
|
+
self._engine = GovernanceEngine(self.constitution, strict=False)
|
|
207
|
+
self._rules: dict[str, Rule] = {rule.id: rule for rule in self.constitution.rules}
|
|
208
|
+
|
|
209
|
+
def evaluate(self, tool_name: str, arguments: Any) -> GovernanceDecision:
|
|
210
|
+
"""
|
|
211
|
+
Evaluate one tool call. Never raises.
|
|
212
|
+
|
|
213
|
+
:param tool_name: Name of the tool the model wants to call.
|
|
214
|
+
:param arguments: The tool arguments.
|
|
215
|
+
:returns: The governance decision.
|
|
216
|
+
"""
|
|
217
|
+
try:
|
|
218
|
+
formatter = self.tool_call_formatter or format_tool_call
|
|
219
|
+
action = formatter(tool_name, arguments)
|
|
220
|
+
if not isinstance(action, str) or not action.strip():
|
|
221
|
+
msg = "The tool call formatter must return a non-empty string."
|
|
222
|
+
raise TypeError(msg)
|
|
223
|
+
result = self._engine.validate(action, agent_id=self.agent_id, strict=False)
|
|
224
|
+
decision = self._decide(tool_name, result)
|
|
225
|
+
except ConstitutionalViolationError as error:
|
|
226
|
+
rule_id = error.rule_id or "unknown"
|
|
227
|
+
decision = GovernanceDecision(
|
|
228
|
+
verdict=Verdict.DENY,
|
|
229
|
+
tool_name=tool_name,
|
|
230
|
+
reason=f"ACGS rule {rule_id} halted the call.",
|
|
231
|
+
rule_ids=(rule_id,),
|
|
232
|
+
)
|
|
233
|
+
except Exception as error:
|
|
234
|
+
logger.warning(
|
|
235
|
+
"ACGS governance failed for tool '%s'; denying the call (fail-closed).", tool_name, exc_info=True
|
|
236
|
+
)
|
|
237
|
+
decision = GovernanceDecision(
|
|
238
|
+
verdict=Verdict.DENY,
|
|
239
|
+
tool_name=tool_name,
|
|
240
|
+
reason="ACGS governance could not evaluate this tool call, so it was denied.",
|
|
241
|
+
error=f"{type(error).__name__}: {error}",
|
|
242
|
+
)
|
|
243
|
+
self._log(decision)
|
|
244
|
+
return decision
|
|
245
|
+
|
|
246
|
+
def _workflow_action(self, rule_id: str) -> ViolationAction | None:
|
|
247
|
+
rule = self._rules.get(rule_id)
|
|
248
|
+
if rule is None:
|
|
249
|
+
return None
|
|
250
|
+
if rule.workflow_action is not None:
|
|
251
|
+
return rule.workflow_action
|
|
252
|
+
return ViolationAction.BLOCK if rule.severity.blocks() else ViolationAction.WARN # pragma: no cover
|
|
253
|
+
|
|
254
|
+
def _decide(self, tool_name: str, result: ValidationResult) -> GovernanceDecision:
|
|
255
|
+
warnings = tuple(dict.fromkeys(w.rule_id for w in result.warnings))
|
|
256
|
+
rule_ids = tuple(dict.fromkeys(v.rule_id for v in result.violations))
|
|
257
|
+
if not rule_ids:
|
|
258
|
+
if result.valid:
|
|
259
|
+
return GovernanceDecision(
|
|
260
|
+
verdict=Verdict.ALLOW,
|
|
261
|
+
tool_name=tool_name,
|
|
262
|
+
reason="No blocking ACGS rule matched.",
|
|
263
|
+
warning_rule_ids=warnings,
|
|
264
|
+
)
|
|
265
|
+
return GovernanceDecision(
|
|
266
|
+
verdict=Verdict.DENY,
|
|
267
|
+
tool_name=tool_name,
|
|
268
|
+
reason="ACGS reported the call as invalid without naming a rule.",
|
|
269
|
+
warning_rule_ids=warnings,
|
|
270
|
+
)
|
|
271
|
+
actions = [self._workflow_action(rule_id) for rule_id in rule_ids]
|
|
272
|
+
details = "; ".join(self._describe(rule_id) for rule_id in rule_ids)
|
|
273
|
+
if all(action in _REVIEW_ACTIONS for action in actions):
|
|
274
|
+
return GovernanceDecision(
|
|
275
|
+
verdict=Verdict.REVIEW,
|
|
276
|
+
tool_name=tool_name,
|
|
277
|
+
reason=f"Human review required by {details}.",
|
|
278
|
+
rule_ids=rule_ids,
|
|
279
|
+
warning_rule_ids=warnings,
|
|
280
|
+
)
|
|
281
|
+
return GovernanceDecision(
|
|
282
|
+
verdict=Verdict.DENY,
|
|
283
|
+
tool_name=tool_name,
|
|
284
|
+
reason=f"Blocked by {details}.",
|
|
285
|
+
rule_ids=rule_ids,
|
|
286
|
+
warning_rule_ids=warnings,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def _describe(self, rule_id: str) -> str:
|
|
290
|
+
rule = self._rules.get(rule_id)
|
|
291
|
+
if rule is None:
|
|
292
|
+
return f"ACGS rule {rule_id}"
|
|
293
|
+
return f"ACGS rule {rule_id} ({rule.text})"
|
|
294
|
+
|
|
295
|
+
@staticmethod
|
|
296
|
+
def _log(decision: GovernanceDecision) -> None:
|
|
297
|
+
if decision.verdict is Verdict.ALLOW:
|
|
298
|
+
logger.debug("ACGS allowed tool '%s'.", decision.tool_name)
|
|
299
|
+
elif decision.verdict is Verdict.REVIEW:
|
|
300
|
+
logger.info("ACGS requires review for tool '%s': %s", decision.tool_name, decision.rule_ids)
|
|
301
|
+
else:
|
|
302
|
+
logger.info("ACGS denied tool '%s': %s", decision.tool_name, decision.rule_ids or decision.error)
|
|
File without changes
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ACGS Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""ACGS governance as a Haystack Human-in-the-Loop ``ConfirmationStrategy``."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from acgs_lite import Constitution
|
|
12
|
+
from haystack.core.serialization import component_to_dict, default_from_dict, default_to_dict
|
|
13
|
+
from haystack.hooks.human_in_the_loop import ToolExecutionDecision
|
|
14
|
+
from haystack.hooks.human_in_the_loop.types import ConfirmationStrategy
|
|
15
|
+
from haystack.utils.callable_serialization import deserialize_callable, serialize_callable
|
|
16
|
+
from haystack.utils.deserialization import deserialize_component_inplace
|
|
17
|
+
|
|
18
|
+
from haystack_integrations.hooks.acgs._governance import (
|
|
19
|
+
GovernanceDecision,
|
|
20
|
+
ToolCallFormatter,
|
|
21
|
+
ToolCallGovernor,
|
|
22
|
+
Verdict,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
DENY_FEEDBACK_TEMPLATE = "Tool call '{tool_name}' was not executed. {reason}"
|
|
28
|
+
REVIEW_UNAVAILABLE_FEEDBACK_TEMPLATE = (
|
|
29
|
+
"Tool call '{tool_name}' was not executed. {reason} No review strategy is configured, so the call was denied."
|
|
30
|
+
)
|
|
31
|
+
REVIEW_FAILED_FEEDBACK_TEMPLATE = "Tool call '{tool_name}' was not executed because the review step failed."
|
|
32
|
+
MODIFIED_DENIED_FEEDBACK_TEMPLATE = (
|
|
33
|
+
"Tool call '{tool_name}' was not executed. The reviewed parameters were rejected. {reason}"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ACGSConfirmationStrategy:
|
|
38
|
+
"""
|
|
39
|
+
Apply an ACGS constitution to every tool call the Haystack ``Agent`` is about to run.
|
|
40
|
+
|
|
41
|
+
Register it inside Haystack's native ``ConfirmationHook`` under the ``before_tool`` hook point::
|
|
42
|
+
|
|
43
|
+
from haystack.components.agents import Agent
|
|
44
|
+
from haystack.hooks.human_in_the_loop import ConfirmationHook
|
|
45
|
+
from haystack_integrations.hooks.acgs import ACGSConfirmationStrategy
|
|
46
|
+
|
|
47
|
+
agent = Agent(
|
|
48
|
+
chat_generator=...,
|
|
49
|
+
tools=[...],
|
|
50
|
+
hooks={"before_tool": [ConfirmationHook(confirmation_strategies={"*": ACGSConfirmationStrategy()})]},
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
For each tool call the tool name and arguments are rendered with ``format_tool_call`` (or a custom
|
|
54
|
+
``tool_call_formatter``) and validated with ``acgs_lite.GovernanceEngine``. The verdict is mapped to a
|
|
55
|
+
native ``ToolExecutionDecision``:
|
|
56
|
+
|
|
57
|
+
- ``allow``: the call runs with its original parameters;
|
|
58
|
+
- ``deny``: the call is rejected; the ``ConfirmationHook`` adds a tool-result message with the reason so the
|
|
59
|
+
model can react;
|
|
60
|
+
- ``review``: the call is handed to ``review_strategy`` (for example a ``BlockingConfirmationStrategy``).
|
|
61
|
+
Without a ``review_strategy`` it is rejected. If the reviewer modifies the parameters, the modified call is
|
|
62
|
+
evaluated again and rejected unless it is allowed or again only needs review.
|
|
63
|
+
|
|
64
|
+
Any error while evaluating, or while running the review strategy, rejects the call.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
*,
|
|
70
|
+
constitution: Constitution | None = None,
|
|
71
|
+
review_strategy: ConfirmationStrategy | None = None,
|
|
72
|
+
agent_id: str = "haystack-agent",
|
|
73
|
+
tool_call_formatter: ToolCallFormatter | None = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Create the strategy.
|
|
77
|
+
|
|
78
|
+
:param constitution: The ACGS constitution to enforce. Defaults to ``acgs_lite.Constitution.default()``.
|
|
79
|
+
:param review_strategy: Native Haystack confirmation strategy used when a rule requires human review.
|
|
80
|
+
When ``None``, calls that require review are rejected.
|
|
81
|
+
:param agent_id: Agent identifier recorded by ACGS for each validation.
|
|
82
|
+
:param tool_call_formatter: Optional function ``(tool_name, arguments) -> str`` that replaces
|
|
83
|
+
``format_tool_call``. It must be importable to serialize the strategy, and on Haystack versions with a
|
|
84
|
+
deserialization allowlist its module must be allowlisted to deserialize it.
|
|
85
|
+
"""
|
|
86
|
+
self.constitution = constitution if constitution is not None else Constitution.default()
|
|
87
|
+
self.review_strategy = review_strategy
|
|
88
|
+
self.agent_id = agent_id
|
|
89
|
+
self.tool_call_formatter = tool_call_formatter
|
|
90
|
+
self._governor = ToolCallGovernor(self.constitution, agent_id=agent_id, tool_call_formatter=tool_call_formatter)
|
|
91
|
+
|
|
92
|
+
def evaluate(self, tool_name: str, tool_params: dict[str, Any]) -> GovernanceDecision:
|
|
93
|
+
"""
|
|
94
|
+
Evaluate a tool call without executing anything. Never raises.
|
|
95
|
+
|
|
96
|
+
:param tool_name: Name of the tool.
|
|
97
|
+
:param tool_params: Arguments of the tool call.
|
|
98
|
+
:returns: The ACGS governance decision.
|
|
99
|
+
"""
|
|
100
|
+
return self._governor.evaluate(tool_name, tool_params)
|
|
101
|
+
|
|
102
|
+
def run(
|
|
103
|
+
self,
|
|
104
|
+
*,
|
|
105
|
+
tool_name: str,
|
|
106
|
+
tool_description: str,
|
|
107
|
+
tool_params: dict[str, Any],
|
|
108
|
+
tool_call_id: str | None = None,
|
|
109
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
110
|
+
) -> ToolExecutionDecision:
|
|
111
|
+
"""
|
|
112
|
+
Decide whether a tool call may run.
|
|
113
|
+
|
|
114
|
+
:param tool_name: Name of the tool to be executed.
|
|
115
|
+
:param tool_description: Description of the tool.
|
|
116
|
+
:param tool_params: Parameters the model passed to the tool.
|
|
117
|
+
:param tool_call_id: ID of the tool call, used to bind the decision to the call.
|
|
118
|
+
:param confirmation_strategy_context: Request-scoped resources, forwarded to ``review_strategy``.
|
|
119
|
+
:returns: The tool execution decision.
|
|
120
|
+
"""
|
|
121
|
+
decision = self.evaluate(tool_name, tool_params)
|
|
122
|
+
if decision.verdict is not Verdict.REVIEW or self.review_strategy is None:
|
|
123
|
+
return self._decision_without_review(decision, tool_params, tool_call_id)
|
|
124
|
+
try:
|
|
125
|
+
reviewed = self.review_strategy.run(
|
|
126
|
+
tool_name=tool_name,
|
|
127
|
+
tool_description=tool_description,
|
|
128
|
+
tool_params=tool_params,
|
|
129
|
+
tool_call_id=tool_call_id,
|
|
130
|
+
confirmation_strategy_context=confirmation_strategy_context,
|
|
131
|
+
)
|
|
132
|
+
except Exception:
|
|
133
|
+
logger.warning("ACGS review strategy failed for tool '%s'; rejecting the call.", tool_name, exc_info=True)
|
|
134
|
+
return self._reject(tool_name, tool_call_id, REVIEW_FAILED_FEEDBACK_TEMPLATE.format(tool_name=tool_name))
|
|
135
|
+
return self._check_review_result(reviewed, tool_name, tool_params, tool_call_id)
|
|
136
|
+
|
|
137
|
+
async def run_async(
|
|
138
|
+
self,
|
|
139
|
+
*,
|
|
140
|
+
tool_name: str,
|
|
141
|
+
tool_description: str,
|
|
142
|
+
tool_params: dict[str, Any],
|
|
143
|
+
tool_call_id: str | None = None,
|
|
144
|
+
confirmation_strategy_context: dict[str, Any] | None = None,
|
|
145
|
+
) -> ToolExecutionDecision:
|
|
146
|
+
"""
|
|
147
|
+
Async version of ``run``; awaits ``review_strategy.run_async`` when review is needed.
|
|
148
|
+
|
|
149
|
+
:param tool_name: Name of the tool to be executed.
|
|
150
|
+
:param tool_description: Description of the tool.
|
|
151
|
+
:param tool_params: Parameters the model passed to the tool.
|
|
152
|
+
:param tool_call_id: ID of the tool call, used to bind the decision to the call.
|
|
153
|
+
:param confirmation_strategy_context: Request-scoped resources, forwarded to ``review_strategy``.
|
|
154
|
+
:returns: The tool execution decision.
|
|
155
|
+
"""
|
|
156
|
+
decision = self.evaluate(tool_name, tool_params)
|
|
157
|
+
if decision.verdict is not Verdict.REVIEW or self.review_strategy is None:
|
|
158
|
+
return self._decision_without_review(decision, tool_params, tool_call_id)
|
|
159
|
+
try:
|
|
160
|
+
reviewed = await self.review_strategy.run_async(
|
|
161
|
+
tool_name=tool_name,
|
|
162
|
+
tool_description=tool_description,
|
|
163
|
+
tool_params=tool_params,
|
|
164
|
+
tool_call_id=tool_call_id,
|
|
165
|
+
confirmation_strategy_context=confirmation_strategy_context,
|
|
166
|
+
)
|
|
167
|
+
except Exception:
|
|
168
|
+
logger.warning("ACGS review strategy failed for tool '%s'; rejecting the call.", tool_name, exc_info=True)
|
|
169
|
+
return self._reject(tool_name, tool_call_id, REVIEW_FAILED_FEEDBACK_TEMPLATE.format(tool_name=tool_name))
|
|
170
|
+
return self._check_review_result(reviewed, tool_name, tool_params, tool_call_id)
|
|
171
|
+
|
|
172
|
+
def _decision_without_review(
|
|
173
|
+
self, decision: GovernanceDecision, tool_params: dict[str, Any], tool_call_id: str | None
|
|
174
|
+
) -> ToolExecutionDecision:
|
|
175
|
+
tool_name = decision.tool_name
|
|
176
|
+
if decision.verdict is Verdict.ALLOW:
|
|
177
|
+
return ToolExecutionDecision(
|
|
178
|
+
tool_name=tool_name, execute=True, tool_call_id=tool_call_id, final_tool_params=tool_params
|
|
179
|
+
)
|
|
180
|
+
template = (
|
|
181
|
+
REVIEW_UNAVAILABLE_FEEDBACK_TEMPLATE if decision.verdict is Verdict.REVIEW else DENY_FEEDBACK_TEMPLATE
|
|
182
|
+
)
|
|
183
|
+
return self._reject(tool_name, tool_call_id, template.format(tool_name=tool_name, reason=decision.reason))
|
|
184
|
+
|
|
185
|
+
def _check_review_result(
|
|
186
|
+
self, reviewed: Any, tool_name: str, tool_params: dict[str, Any], tool_call_id: str | None
|
|
187
|
+
) -> ToolExecutionDecision:
|
|
188
|
+
if not isinstance(reviewed, ToolExecutionDecision):
|
|
189
|
+
logger.warning("ACGS review strategy returned %s instead of a ToolExecutionDecision.", type(reviewed))
|
|
190
|
+
return self._reject(tool_name, tool_call_id, REVIEW_FAILED_FEEDBACK_TEMPLATE.format(tool_name=tool_name))
|
|
191
|
+
if not reviewed.execute:
|
|
192
|
+
return reviewed
|
|
193
|
+
final_params = reviewed.final_tool_params if reviewed.final_tool_params is not None else tool_params
|
|
194
|
+
if final_params != tool_params:
|
|
195
|
+
recheck = self.evaluate(tool_name, final_params)
|
|
196
|
+
if recheck.verdict is Verdict.DENY:
|
|
197
|
+
return self._reject(
|
|
198
|
+
tool_name,
|
|
199
|
+
tool_call_id,
|
|
200
|
+
MODIFIED_DENIED_FEEDBACK_TEMPLATE.format(tool_name=tool_name, reason=recheck.reason),
|
|
201
|
+
)
|
|
202
|
+
return reviewed
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def _reject(tool_name: str, tool_call_id: str | None, feedback: str) -> ToolExecutionDecision:
|
|
206
|
+
return ToolExecutionDecision(tool_name=tool_name, execute=False, tool_call_id=tool_call_id, feedback=feedback)
|
|
207
|
+
|
|
208
|
+
def to_dict(self) -> dict[str, Any]:
|
|
209
|
+
"""
|
|
210
|
+
Serialize the strategy. The constitution is stored as YAML.
|
|
211
|
+
|
|
212
|
+
:returns: Dictionary with serialized data.
|
|
213
|
+
"""
|
|
214
|
+
return default_to_dict(
|
|
215
|
+
self,
|
|
216
|
+
constitution=self.constitution.to_yaml(),
|
|
217
|
+
review_strategy=(
|
|
218
|
+
component_to_dict(obj=self.review_strategy, name="review_strategy")
|
|
219
|
+
if self.review_strategy is not None
|
|
220
|
+
else None
|
|
221
|
+
),
|
|
222
|
+
agent_id=self.agent_id,
|
|
223
|
+
tool_call_formatter=(
|
|
224
|
+
serialize_callable(self.tool_call_formatter) if self.tool_call_formatter is not None else None
|
|
225
|
+
),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
@classmethod
|
|
229
|
+
def from_dict(cls, data: dict[str, Any]) -> ACGSConfirmationStrategy:
|
|
230
|
+
"""
|
|
231
|
+
Deserialize the strategy.
|
|
232
|
+
|
|
233
|
+
:param data: Dictionary produced by ``to_dict``.
|
|
234
|
+
:returns: The deserialized strategy.
|
|
235
|
+
"""
|
|
236
|
+
init_params = data.get("init_parameters", {})
|
|
237
|
+
if isinstance(init_params.get("constitution"), str):
|
|
238
|
+
init_params["constitution"] = Constitution.from_yaml_str(init_params["constitution"])
|
|
239
|
+
if init_params.get("review_strategy") is not None:
|
|
240
|
+
deserialize_component_inplace(init_params, key="review_strategy")
|
|
241
|
+
if init_params.get("tool_call_formatter") is not None:
|
|
242
|
+
init_params["tool_call_formatter"] = deserialize_callable(init_params["tool_call_formatter"])
|
|
243
|
+
return default_from_dict(cls, data)
|