agent-framework-acgs 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.
- agent_framework_acgs/__init__.py +31 -0
- agent_framework_acgs/_governance.py +310 -0
- agent_framework_acgs/middleware.py +371 -0
- agent_framework_acgs/py.typed +0 -0
- agent_framework_acgs-0.1.0.dist-info/METADATA +432 -0
- agent_framework_acgs-0.1.0.dist-info/RECORD +8 -0
- agent_framework_acgs-0.1.0.dist-info/WHEEL +4 -0
- agent_framework_acgs-0.1.0.dist-info/licenses/LICENSE +175 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ACGS Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""ACGS rule-based tool-call governance for Microsoft Agent Framework function tools."""
|
|
5
|
+
|
|
6
|
+
from agent_framework_acgs._governance import GovernanceDecision, ToolCallFormatter, Verdict, format_tool_call
|
|
7
|
+
from agent_framework_acgs.middleware import (
|
|
8
|
+
APPROVAL_PROPERTIES_KEY,
|
|
9
|
+
DECISION_METADATA_KEY,
|
|
10
|
+
ACGSConfigurationError,
|
|
11
|
+
ACGSFunctionMiddleware,
|
|
12
|
+
ACGSGuard,
|
|
13
|
+
ACGSToolCallDenied,
|
|
14
|
+
ACGSToolCheck,
|
|
15
|
+
UngovernedToolsError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"APPROVAL_PROPERTIES_KEY",
|
|
20
|
+
"DECISION_METADATA_KEY",
|
|
21
|
+
"ACGSConfigurationError",
|
|
22
|
+
"ACGSFunctionMiddleware",
|
|
23
|
+
"ACGSGuard",
|
|
24
|
+
"ACGSToolCallDenied",
|
|
25
|
+
"ACGSToolCheck",
|
|
26
|
+
"GovernanceDecision",
|
|
27
|
+
"ToolCallFormatter",
|
|
28
|
+
"UngovernedToolsError",
|
|
29
|
+
"Verdict",
|
|
30
|
+
"format_tool_call",
|
|
31
|
+
]
|
|
@@ -0,0 +1,310 @@
|
|
|
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
|
+
For ``DENY`` it starts with ``Blocked by`` followed by the blocking rules only.
|
|
73
|
+
:param rule_ids: IDs of the blocking or review rules that matched, in match order.
|
|
74
|
+
:param warning_rule_ids: IDs of non-blocking (warn) rules that matched.
|
|
75
|
+
:param error: Set when the verdict is ``DENY`` because evaluation itself failed.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
verdict: Verdict
|
|
79
|
+
tool_name: str
|
|
80
|
+
reason: str
|
|
81
|
+
rule_ids: tuple[str, ...] = ()
|
|
82
|
+
warning_rule_ids: tuple[str, ...] = ()
|
|
83
|
+
error: str | None = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _humanize(identifier: str) -> str:
|
|
87
|
+
"""Split an identifier such as ``skip_audit`` or ``disableLogging`` into lower-case words."""
|
|
88
|
+
spaced = _CAMEL_BOUNDARY.sub(" ", identifier)
|
|
89
|
+
return " ".join(_SEPARATORS.sub(" ", spaced).split()).lower()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _render_scalar(value: Any) -> str:
|
|
93
|
+
"""Render a leaf value on a single line."""
|
|
94
|
+
if isinstance(value, str):
|
|
95
|
+
return " ".join(value.split())
|
|
96
|
+
if value is None or isinstance(value, bool | int | float):
|
|
97
|
+
return json.dumps(value)
|
|
98
|
+
return " ".join(str(value).split())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _flatten(value: Any, path: str, depth: int) -> Iterator[tuple[str, Any]]:
|
|
102
|
+
"""Yield ``(dotted_path, leaf_value)`` pairs for nested mappings and sequences."""
|
|
103
|
+
if depth > MAX_ARGUMENT_DEPTH:
|
|
104
|
+
msg = f"Tool call arguments are nested deeper than {MAX_ARGUMENT_DEPTH} levels."
|
|
105
|
+
raise ValueError(msg)
|
|
106
|
+
if isinstance(value, Mapping):
|
|
107
|
+
if not value:
|
|
108
|
+
yield path, "{}"
|
|
109
|
+
return
|
|
110
|
+
for key in sorted(value, key=str):
|
|
111
|
+
child = f"{path}.{key}" if path else str(key)
|
|
112
|
+
yield from _flatten(value[key], child, depth + 1)
|
|
113
|
+
elif isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):
|
|
114
|
+
if not value:
|
|
115
|
+
yield path, "[]"
|
|
116
|
+
return
|
|
117
|
+
for index, item in enumerate(value):
|
|
118
|
+
yield from _flatten(item, f"{path}[{index}]", depth + 1)
|
|
119
|
+
else:
|
|
120
|
+
yield path, value
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def format_tool_call(tool_name: str, arguments: Any) -> str:
|
|
124
|
+
r"""
|
|
125
|
+
Render a tool call as the text that ACGS keyword and pattern rules are matched against.
|
|
126
|
+
|
|
127
|
+
The output has one ``path: value`` line per argument leaf, so argument names and values are
|
|
128
|
+
both visible to rules, and multi-line values are collapsed onto one line. Identifiers
|
|
129
|
+
(the tool name, argument names and single-token string values) that contain separators or
|
|
130
|
+
camelCase are repeated in a trailing ``normalized:`` line as plain words, so that a rule
|
|
131
|
+
keyword such as ``skip audit`` also matches a tool named ``skip_audit``.
|
|
132
|
+
|
|
133
|
+
Example::
|
|
134
|
+
|
|
135
|
+
>>> print(format_tool_call("send_email", {"to": "a@example.com", "body": "Hi\nthere"}))
|
|
136
|
+
tool: send_email
|
|
137
|
+
arguments:
|
|
138
|
+
body: Hi there
|
|
139
|
+
to: a@example.com
|
|
140
|
+
normalized: send email
|
|
141
|
+
|
|
142
|
+
:param tool_name: Name of the tool the model wants to call.
|
|
143
|
+
:param arguments: The tool arguments, usually a mapping. Other values are rendered as ``input``.
|
|
144
|
+
:returns: The text passed to ``GovernanceEngine.validate``.
|
|
145
|
+
:raises ValueError: If the arguments are nested deeper than ``MAX_ARGUMENT_DEPTH``.
|
|
146
|
+
"""
|
|
147
|
+
lines = [f"tool: {tool_name}", "arguments:"]
|
|
148
|
+
identifiers = [tool_name]
|
|
149
|
+
leaves = list(_flatten(arguments, "" if isinstance(arguments, Mapping) else "input", 0))
|
|
150
|
+
if isinstance(arguments, Mapping) and not arguments:
|
|
151
|
+
leaves = []
|
|
152
|
+
if not leaves:
|
|
153
|
+
lines.append("(none)")
|
|
154
|
+
for path, leaf in leaves:
|
|
155
|
+
rendered = _render_scalar(leaf)
|
|
156
|
+
lines.append(f"{path}: {rendered}")
|
|
157
|
+
identifiers.append(path)
|
|
158
|
+
if (
|
|
159
|
+
isinstance(leaf, str)
|
|
160
|
+
and len(rendered) <= _MAX_IDENTIFIER_VALUE_LENGTH
|
|
161
|
+
and _IDENTIFIER_VALUE.match(rendered)
|
|
162
|
+
):
|
|
163
|
+
identifiers.append(rendered)
|
|
164
|
+
normalized: list[str] = []
|
|
165
|
+
for identifier in identifiers:
|
|
166
|
+
words = _humanize(identifier)
|
|
167
|
+
if words and words != identifier.lower() and words not in normalized:
|
|
168
|
+
normalized.append(words)
|
|
169
|
+
if normalized:
|
|
170
|
+
lines.append("normalized: " + " | ".join(normalized))
|
|
171
|
+
return "\n".join(lines)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class ToolCallGovernor:
|
|
175
|
+
"""
|
|
176
|
+
Evaluate tool calls against an ACGS constitution and return a ``GovernanceDecision``.
|
|
177
|
+
|
|
178
|
+
Verdict mapping, applied to the blocking violations of the validation result:
|
|
179
|
+
|
|
180
|
+
- no violations: ``ALLOW`` (matched warn-only rules are reported in ``warning_rule_ids``);
|
|
181
|
+
- every violation comes from a rule whose workflow action is ``require_human_review`` or
|
|
182
|
+
``escalate_to_senior``: ``REVIEW``;
|
|
183
|
+
- anything else (``block``, ``block_and_notify``, ``halt_and_alert``, a rule ID that is not in
|
|
184
|
+
the constitution, an unknown action, or an invalid result without violations): ``DENY``.
|
|
185
|
+
|
|
186
|
+
A blocking rule is never downgraded to ``REVIEW`` because a review rule matched as well. In
|
|
187
|
+
that case the reason names only the blocking rules after ``Blocked by`` and lists the matched
|
|
188
|
+
review rules separately; ``rule_ids`` still contains every matched rule in match order.
|
|
189
|
+
Any exception raised while formatting or validating also yields ``DENY``.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
def __init__(
|
|
193
|
+
self,
|
|
194
|
+
constitution: Constitution | None = None,
|
|
195
|
+
*,
|
|
196
|
+
agent_id: str,
|
|
197
|
+
tool_call_formatter: ToolCallFormatter | None = None,
|
|
198
|
+
) -> None:
|
|
199
|
+
"""
|
|
200
|
+
Create a governor.
|
|
201
|
+
|
|
202
|
+
:param constitution: The constitution to enforce. Defaults to ``Constitution.default()``.
|
|
203
|
+
:param agent_id: Agent identifier passed to ``GovernanceEngine.validate``.
|
|
204
|
+
:param tool_call_formatter: Optional replacement for ``format_tool_call``.
|
|
205
|
+
"""
|
|
206
|
+
self.constitution = constitution if constitution is not None else Constitution.default()
|
|
207
|
+
self.agent_id = agent_id
|
|
208
|
+
self.tool_call_formatter = tool_call_formatter
|
|
209
|
+
self._engine = GovernanceEngine(self.constitution, strict=False)
|
|
210
|
+
self._rules: dict[str, Rule] = {rule.id: rule for rule in self.constitution.rules}
|
|
211
|
+
|
|
212
|
+
def evaluate(self, tool_name: str, arguments: Any) -> GovernanceDecision:
|
|
213
|
+
"""
|
|
214
|
+
Evaluate one tool call. Never raises.
|
|
215
|
+
|
|
216
|
+
:param tool_name: Name of the tool the model wants to call.
|
|
217
|
+
:param arguments: The tool arguments.
|
|
218
|
+
:returns: The governance decision.
|
|
219
|
+
"""
|
|
220
|
+
try:
|
|
221
|
+
formatter = self.tool_call_formatter or format_tool_call
|
|
222
|
+
action = formatter(tool_name, arguments)
|
|
223
|
+
if not isinstance(action, str) or not action.strip():
|
|
224
|
+
msg = "The tool call formatter must return a non-empty string."
|
|
225
|
+
raise TypeError(msg)
|
|
226
|
+
result = self._engine.validate(action, agent_id=self.agent_id, strict=False)
|
|
227
|
+
decision = self._decide(tool_name, result)
|
|
228
|
+
except ConstitutionalViolationError as error:
|
|
229
|
+
rule_id = error.rule_id or "unknown"
|
|
230
|
+
decision = GovernanceDecision(
|
|
231
|
+
verdict=Verdict.DENY,
|
|
232
|
+
tool_name=tool_name,
|
|
233
|
+
reason=f"ACGS rule {rule_id} halted the call.",
|
|
234
|
+
rule_ids=(rule_id,),
|
|
235
|
+
)
|
|
236
|
+
except Exception as error:
|
|
237
|
+
logger.warning(
|
|
238
|
+
"ACGS governance failed for tool '%s'; denying the call (fail-closed).", tool_name, exc_info=True
|
|
239
|
+
)
|
|
240
|
+
decision = GovernanceDecision(
|
|
241
|
+
verdict=Verdict.DENY,
|
|
242
|
+
tool_name=tool_name,
|
|
243
|
+
reason="ACGS governance could not evaluate this tool call, so it was denied.",
|
|
244
|
+
error=f"{type(error).__name__}: {error}",
|
|
245
|
+
)
|
|
246
|
+
self._log(decision)
|
|
247
|
+
return decision
|
|
248
|
+
|
|
249
|
+
def _workflow_action(self, rule_id: str) -> ViolationAction | None:
|
|
250
|
+
rule = self._rules.get(rule_id)
|
|
251
|
+
if rule is None:
|
|
252
|
+
return None
|
|
253
|
+
if rule.workflow_action is not None:
|
|
254
|
+
return rule.workflow_action
|
|
255
|
+
return ViolationAction.BLOCK if rule.severity.blocks() else ViolationAction.WARN # pragma: no cover
|
|
256
|
+
|
|
257
|
+
def _decide(self, tool_name: str, result: ValidationResult) -> GovernanceDecision:
|
|
258
|
+
warnings = tuple(dict.fromkeys(w.rule_id for w in result.warnings))
|
|
259
|
+
rule_ids = tuple(dict.fromkeys(v.rule_id for v in result.violations))
|
|
260
|
+
if not rule_ids:
|
|
261
|
+
if result.valid:
|
|
262
|
+
return GovernanceDecision(
|
|
263
|
+
verdict=Verdict.ALLOW,
|
|
264
|
+
tool_name=tool_name,
|
|
265
|
+
reason="No blocking ACGS rule matched.",
|
|
266
|
+
warning_rule_ids=warnings,
|
|
267
|
+
)
|
|
268
|
+
return GovernanceDecision(
|
|
269
|
+
verdict=Verdict.DENY,
|
|
270
|
+
tool_name=tool_name,
|
|
271
|
+
reason="ACGS reported the call as invalid without naming a rule.",
|
|
272
|
+
warning_rule_ids=warnings,
|
|
273
|
+
)
|
|
274
|
+
review_ids = tuple(rule_id for rule_id in rule_ids if self._workflow_action(rule_id) in _REVIEW_ACTIONS)
|
|
275
|
+
blocking_ids = tuple(rule_id for rule_id in rule_ids if rule_id not in review_ids)
|
|
276
|
+
if not blocking_ids:
|
|
277
|
+
return GovernanceDecision(
|
|
278
|
+
verdict=Verdict.REVIEW,
|
|
279
|
+
tool_name=tool_name,
|
|
280
|
+
reason=f"Human review required by {self._describe(review_ids)}.",
|
|
281
|
+
rule_ids=rule_ids,
|
|
282
|
+
warning_rule_ids=warnings,
|
|
283
|
+
)
|
|
284
|
+
reason = f"Blocked by {self._describe(blocking_ids)}."
|
|
285
|
+
if review_ids:
|
|
286
|
+
reason += f" Review rules that also matched: {self._describe(review_ids)}."
|
|
287
|
+
return GovernanceDecision(
|
|
288
|
+
verdict=Verdict.DENY,
|
|
289
|
+
tool_name=tool_name,
|
|
290
|
+
reason=reason,
|
|
291
|
+
rule_ids=rule_ids,
|
|
292
|
+
warning_rule_ids=warnings,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def _describe(self, rule_ids: Sequence[str]) -> str:
|
|
296
|
+
"""Join ``ACGS rule <id> (<text>)`` descriptions for ``rule_ids``; unknown IDs have no text."""
|
|
297
|
+
parts = []
|
|
298
|
+
for rule_id in rule_ids:
|
|
299
|
+
rule = self._rules.get(rule_id)
|
|
300
|
+
parts.append(f"ACGS rule {rule_id}" if rule is None else f"ACGS rule {rule_id} ({rule.text})")
|
|
301
|
+
return "; ".join(parts)
|
|
302
|
+
|
|
303
|
+
@staticmethod
|
|
304
|
+
def _log(decision: GovernanceDecision) -> None:
|
|
305
|
+
if decision.verdict is Verdict.ALLOW:
|
|
306
|
+
logger.debug("ACGS allowed tool '%s'.", decision.tool_name)
|
|
307
|
+
elif decision.verdict is Verdict.REVIEW:
|
|
308
|
+
logger.info("ACGS requires review for tool '%s': %s", decision.tool_name, decision.rule_ids)
|
|
309
|
+
else:
|
|
310
|
+
logger.info("ACGS denied tool '%s': %s", decision.tool_name, decision.rule_ids or decision.error)
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ACGS Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""ACGS governance for Microsoft Agent Framework function tools: function middleware plus a chat-level tool check."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from acgs_lite import Constitution
|
|
13
|
+
from agent_framework import (
|
|
14
|
+
ChatContext,
|
|
15
|
+
ChatMiddleware,
|
|
16
|
+
Content,
|
|
17
|
+
FunctionInvocationContext,
|
|
18
|
+
FunctionMiddleware,
|
|
19
|
+
FunctionTool,
|
|
20
|
+
MCPStdioTool,
|
|
21
|
+
MCPStreamableHTTPTool,
|
|
22
|
+
MCPWebsocketTool,
|
|
23
|
+
MiddlewareFailure,
|
|
24
|
+
normalize_tools,
|
|
25
|
+
)
|
|
26
|
+
from pydantic import BaseModel
|
|
27
|
+
from pydantic_core import to_jsonable_python
|
|
28
|
+
|
|
29
|
+
from agent_framework_acgs._governance import GovernanceDecision, ToolCallFormatter, ToolCallGovernor, Verdict
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
DECISION_METADATA_KEY = "acgs_decision"
|
|
34
|
+
"""Key of the ``GovernanceDecision`` the function middleware stores in ``FunctionInvocationContext.metadata``."""
|
|
35
|
+
|
|
36
|
+
APPROVAL_PROPERTIES_KEY = "acgs"
|
|
37
|
+
"""Key of the ACGS details in the ``additional_properties`` of an ACGS approval request."""
|
|
38
|
+
|
|
39
|
+
# Local MCP tools are expanded into function tools whose calls go through function middleware.
|
|
40
|
+
_MCP_TOOLS = (MCPStdioTool, MCPStreamableHTTPTool, MCPWebsocketTool)
|
|
41
|
+
_EVALUATION_FAILED = "ACGS governance could not evaluate this tool call, so it was denied."
|
|
42
|
+
_APPROVAL_REQUEST_FAILED = "The approval request failed, so it was denied."
|
|
43
|
+
_CALLER_RUNS_ALL = (
|
|
44
|
+
"all offered tools (function invocation is off or missing on the chat client, so the caller runs them)"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ACGSConfigurationError(MiddlewareFailure):
|
|
49
|
+
"""Raised during a run when ACGS cannot enforce its rules with the current configuration.
|
|
50
|
+
|
|
51
|
+
It subclasses ``MiddlewareFailure``, so the framework stops the run and raises it to the caller
|
|
52
|
+
instead of turning it into a tool result.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class UngovernedToolsError(ACGSConfigurationError):
|
|
57
|
+
"""Raised when a run offers tools whose calls ACGS cannot check (see ``ACGSGuard.ungoverned_tools``)."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ACGSToolCallDenied(MiddlewareFailure):
|
|
61
|
+
"""Raised for a denied call when the guard uses ``on_deny="raise"``. It ends the run."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, decision: GovernanceDecision) -> None:
|
|
64
|
+
"""Create the error.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
decision: The decision that denied the call.
|
|
68
|
+
"""
|
|
69
|
+
super().__init__(decision.reason)
|
|
70
|
+
self.decision = decision
|
|
71
|
+
"""The ACGS decision for the call."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _arguments(arguments: BaseModel | Mapping[str, Any]) -> dict[str, Any]:
|
|
75
|
+
if isinstance(arguments, BaseModel):
|
|
76
|
+
return arguments.model_dump(mode="json")
|
|
77
|
+
return dict(arguments)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _is_approved(approval_response: object) -> bool:
|
|
81
|
+
return (
|
|
82
|
+
isinstance(approval_response, Content)
|
|
83
|
+
and approval_response.type == "function_approval_response"
|
|
84
|
+
and approval_response.approved is True
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _describe_ungoverned(tool: object) -> str | None:
|
|
89
|
+
if isinstance(tool, FunctionTool):
|
|
90
|
+
return f"declaration-only function tool '{tool.name}'" if tool.declaration_only else None
|
|
91
|
+
if isinstance(tool, _MCP_TOOLS):
|
|
92
|
+
return None
|
|
93
|
+
if isinstance(tool, Mapping):
|
|
94
|
+
kind = tool.get("type") or tool.get("name") or "unknown"
|
|
95
|
+
return f"hosted tool '{kind}'"
|
|
96
|
+
return f"tool object of type {type(tool).__name__}"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class ACGSFunctionMiddleware(FunctionMiddleware):
|
|
100
|
+
"""Function middleware that checks each function call with an ``ACGSGuard`` before the function runs.
|
|
101
|
+
|
|
102
|
+
Create it through ``ACGSGuard`` (``guard.function_middleware`` or ``guard.middleware``).
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, guard: ACGSGuard) -> None:
|
|
106
|
+
"""Create the middleware.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
guard: The guard whose rules and options apply.
|
|
110
|
+
"""
|
|
111
|
+
self.guard = guard
|
|
112
|
+
|
|
113
|
+
async def process(
|
|
114
|
+
self,
|
|
115
|
+
context: FunctionInvocationContext,
|
|
116
|
+
call_next: Callable[[], Awaitable[None]],
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Run the function only if ACGS allows the call, or a human approved a call that needs review.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
context: The function invocation context.
|
|
122
|
+
call_next: Runs the rest of the pipeline and the function.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
UngovernedToolsError: If the run offers tools ACGS cannot check and ``allow_ungoverned`` is off.
|
|
126
|
+
ACGSToolCallDenied: If the call is denied and ``on_deny="raise"``.
|
|
127
|
+
"""
|
|
128
|
+
guard = self.guard
|
|
129
|
+
guard.check_tools(context.tools)
|
|
130
|
+
name = context.function.name
|
|
131
|
+
try:
|
|
132
|
+
decision = guard.evaluate(name, _arguments(context.arguments))
|
|
133
|
+
except Exception as error:
|
|
134
|
+
decision = GovernanceDecision(
|
|
135
|
+
verdict=Verdict.DENY,
|
|
136
|
+
tool_name=name,
|
|
137
|
+
reason=_EVALUATION_FAILED,
|
|
138
|
+
error=f"{type(error).__name__}: {error}",
|
|
139
|
+
)
|
|
140
|
+
context.metadata[DECISION_METADATA_KEY] = decision
|
|
141
|
+
if decision.verdict is Verdict.ALLOW:
|
|
142
|
+
await call_next()
|
|
143
|
+
return
|
|
144
|
+
if decision.verdict is Verdict.REVIEW and guard.on_review == "approve":
|
|
145
|
+
if _is_approved(context.metadata.get("approval_response")):
|
|
146
|
+
await call_next()
|
|
147
|
+
return
|
|
148
|
+
try:
|
|
149
|
+
context.result = self._approval_request(context, decision)
|
|
150
|
+
except Exception as error:
|
|
151
|
+
decision = GovernanceDecision(
|
|
152
|
+
verdict=Verdict.DENY,
|
|
153
|
+
tool_name=name,
|
|
154
|
+
reason=f"{decision.reason} {_APPROVAL_REQUEST_FAILED}",
|
|
155
|
+
rule_ids=decision.rule_ids,
|
|
156
|
+
warning_rule_ids=decision.warning_rule_ids,
|
|
157
|
+
error=f"{type(error).__name__}: {error}",
|
|
158
|
+
)
|
|
159
|
+
context.metadata[DECISION_METADATA_KEY] = decision
|
|
160
|
+
else:
|
|
161
|
+
return
|
|
162
|
+
if guard.on_deny == "raise":
|
|
163
|
+
raise ACGSToolCallDenied(decision)
|
|
164
|
+
context.result = f"Tool call '{name}' was not executed. {decision.reason}"
|
|
165
|
+
|
|
166
|
+
@staticmethod
|
|
167
|
+
def _approval_request(context: FunctionInvocationContext, decision: GovernanceDecision) -> Content:
|
|
168
|
+
call_id = context.metadata["call_id"]
|
|
169
|
+
occurrence_id = context.metadata.get("function_call_occurrence_id") or call_id
|
|
170
|
+
function_call = Content.from_function_call(
|
|
171
|
+
call_id=call_id,
|
|
172
|
+
name=context.function.name,
|
|
173
|
+
arguments=to_jsonable_python(_arguments(context.arguments)),
|
|
174
|
+
id=occurrence_id,
|
|
175
|
+
)
|
|
176
|
+
return Content.from_function_approval_request(
|
|
177
|
+
id=occurrence_id,
|
|
178
|
+
function_call=function_call,
|
|
179
|
+
additional_properties={
|
|
180
|
+
"reason": decision.reason,
|
|
181
|
+
APPROVAL_PROPERTIES_KEY: {
|
|
182
|
+
"verdict": decision.verdict.value,
|
|
183
|
+
"rule_ids": list(decision.rule_ids),
|
|
184
|
+
"warning_rule_ids": list(decision.warning_rule_ids),
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class ACGSToolCheck(ChatMiddleware):
|
|
191
|
+
"""Chat middleware that stops a run before the model is called if it offers tools ACGS cannot check.
|
|
192
|
+
|
|
193
|
+
Create it through ``ACGSGuard`` (``guard.tool_check`` or ``guard.middleware``).
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def __init__(self, guard: ACGSGuard) -> None:
|
|
197
|
+
"""Create the middleware.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
guard: The guard whose options apply.
|
|
201
|
+
"""
|
|
202
|
+
self.guard = guard
|
|
203
|
+
|
|
204
|
+
async def process(self, context: ChatContext, call_next: Callable[[], Awaitable[None]]) -> None:
|
|
205
|
+
"""Check the offered tools and the chat client's function invocation settings, then call the model.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
context: The chat context.
|
|
209
|
+
call_next: Calls the model.
|
|
210
|
+
|
|
211
|
+
Raises:
|
|
212
|
+
ACGSConfigurationError: If ``on_review="approve"`` and the client does not bind approval responses
|
|
213
|
+
to recorded requests.
|
|
214
|
+
UngovernedToolsError: If the run offers tools ACGS cannot check and ``allow_ungoverned`` is off.
|
|
215
|
+
"""
|
|
216
|
+
guard = self.guard
|
|
217
|
+
config: Mapping[str, Any] = getattr(context.client, "function_invocation_configuration", None) or {}
|
|
218
|
+
if guard.on_review == "approve" and config.get("disable_approval_response_binding"):
|
|
219
|
+
msg = (
|
|
220
|
+
"ACGS review needs approval responses bound to recorded requests, but the chat client sets "
|
|
221
|
+
"disable_approval_response_binding. Turn it off or use on_review='deny'."
|
|
222
|
+
)
|
|
223
|
+
raise ACGSConfigurationError(msg)
|
|
224
|
+
tools = normalize_tools(context.options.get("tools") if context.options else None)
|
|
225
|
+
if tools and not config.get("enabled", False):
|
|
226
|
+
guard.report_ungoverned([_CALLER_RUNS_ALL])
|
|
227
|
+
additional = [
|
|
228
|
+
f"additional tool '{tool.name}' (the caller runs it)" for tool in config.get("additional_tools") or ()
|
|
229
|
+
]
|
|
230
|
+
if additional:
|
|
231
|
+
guard.report_ungoverned(additional)
|
|
232
|
+
guard.check_tools(tools)
|
|
233
|
+
await call_next()
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class ACGSGuard:
|
|
237
|
+
"""Check Microsoft Agent Framework function calls against an ACGS constitution before the function runs.
|
|
238
|
+
|
|
239
|
+
Add ``guard.middleware`` to an agent (or a chat client, or one run). It contains:
|
|
240
|
+
|
|
241
|
+
- ``function_middleware`` (``ACGSFunctionMiddleware``), which checks every call of a function tool,
|
|
242
|
+
including local MCP tools. Allowed calls run. Blocked calls do not run: the reason becomes the
|
|
243
|
+
call's result, which the model reads, or with ``on_deny="raise"`` the run ends with
|
|
244
|
+
``ACGSToolCallDenied``. Calls that only match review rules pause the run with a native
|
|
245
|
+
``function_approval_request`` in ``response.user_input_requests``. When the approval is sent
|
|
246
|
+
back in the same session, the framework replays the call and the guard checks it again.
|
|
247
|
+
- ``tool_check`` (``ACGSToolCheck``), which stops the run before the model is called when it
|
|
248
|
+
offers tools that the function middleware never sees: hosted tools, declaration-only function
|
|
249
|
+
tools, the chat client's ``additional_tools``, or any tool when the client does not run the
|
|
250
|
+
tool loop itself.
|
|
251
|
+
|
|
252
|
+
A blocking rule always wins over review rules, and any error while evaluating a call denies it.
|
|
253
|
+
|
|
254
|
+
Example:
|
|
255
|
+
>>> from agent_framework_acgs import ACGSGuard
|
|
256
|
+
>>> guard = ACGSGuard()
|
|
257
|
+
>>> guard.evaluate("send_email", {"to": "a@example.com", "body": "The password is hunter2"}).verdict
|
|
258
|
+
<Verdict.DENY: 'deny'>
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def __init__( # noqa: PLR0913
|
|
262
|
+
self,
|
|
263
|
+
*,
|
|
264
|
+
constitution: Constitution | None = None,
|
|
265
|
+
agent_id: str = "agent-framework",
|
|
266
|
+
on_review: Literal["approve", "deny"] = "approve",
|
|
267
|
+
on_deny: Literal["reject", "raise"] = "reject",
|
|
268
|
+
allow_ungoverned: bool = False,
|
|
269
|
+
tool_call_formatter: ToolCallFormatter | None = None,
|
|
270
|
+
) -> None:
|
|
271
|
+
"""Create the guard.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
constitution: The ACGS constitution to enforce. Defaults to
|
|
275
|
+
``acgs_lite.Constitution.default()``.
|
|
276
|
+
agent_id: Agent identifier recorded by ACGS for each validation.
|
|
277
|
+
on_review: What to do when only review rules match. ``"approve"`` asks for approval through
|
|
278
|
+
the framework's tool approval flow. ``"deny"`` denies the call.
|
|
279
|
+
on_deny: What to do with a denied call. ``"reject"`` skips the function and sends the reason to
|
|
280
|
+
the model as the call's result. ``"raise"`` ends the run with ``ACGSToolCallDenied``.
|
|
281
|
+
allow_ungoverned: Log a warning instead of stopping the run when it offers tools ACGS cannot check.
|
|
282
|
+
tool_call_formatter: Optional function ``(tool_name, args) -> str`` that replaces
|
|
283
|
+
``format_tool_call``.
|
|
284
|
+
|
|
285
|
+
Raises:
|
|
286
|
+
ValueError: If ``on_review`` or ``on_deny`` is invalid.
|
|
287
|
+
"""
|
|
288
|
+
if on_review not in ("approve", "deny"):
|
|
289
|
+
msg = f"on_review must be 'approve' or 'deny', got {on_review!r}"
|
|
290
|
+
raise ValueError(msg)
|
|
291
|
+
if on_deny not in ("reject", "raise"):
|
|
292
|
+
msg = f"on_deny must be 'reject' or 'raise', got {on_deny!r}"
|
|
293
|
+
raise ValueError(msg)
|
|
294
|
+
self._governor = ToolCallGovernor(constitution, agent_id=agent_id, tool_call_formatter=tool_call_formatter)
|
|
295
|
+
self.constitution: Constitution = self._governor.constitution
|
|
296
|
+
self.agent_id = agent_id
|
|
297
|
+
self.on_review = on_review
|
|
298
|
+
self.on_deny = on_deny
|
|
299
|
+
self.allow_ungoverned = allow_ungoverned
|
|
300
|
+
self.function_middleware = ACGSFunctionMiddleware(self)
|
|
301
|
+
"""The function middleware."""
|
|
302
|
+
self.tool_check = ACGSToolCheck(self)
|
|
303
|
+
"""The chat middleware that refuses tools ACGS cannot check."""
|
|
304
|
+
|
|
305
|
+
def __repr__(self) -> str:
|
|
306
|
+
"""Show the options, not the constitution."""
|
|
307
|
+
return (
|
|
308
|
+
f"ACGSGuard(agent_id={self.agent_id!r}, on_review={self.on_review!r}, on_deny={self.on_deny!r}, "
|
|
309
|
+
f"allow_ungoverned={self.allow_ungoverned!r})"
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def middleware(self) -> list[ACGSToolCheck | ACGSFunctionMiddleware]:
|
|
314
|
+
"""Both middleware, as a new list to pass as ``middleware=``."""
|
|
315
|
+
return [self.tool_check, self.function_middleware]
|
|
316
|
+
|
|
317
|
+
def evaluate(self, tool_name: str, arguments: Any) -> GovernanceDecision:
|
|
318
|
+
"""Evaluate a tool call without running an agent. Never raises.
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
tool_name: Name of the tool.
|
|
322
|
+
arguments: The tool arguments.
|
|
323
|
+
|
|
324
|
+
Returns:
|
|
325
|
+
The governance decision.
|
|
326
|
+
"""
|
|
327
|
+
return self._governor.evaluate(tool_name, arguments)
|
|
328
|
+
|
|
329
|
+
@staticmethod
|
|
330
|
+
def ungoverned_tools(tools: Any) -> list[str]:
|
|
331
|
+
"""Describe the tools whose calls the function middleware never sees.
|
|
332
|
+
|
|
333
|
+
Function tools with an implementation and local MCP tools are governed. Hosted tools
|
|
334
|
+
(mappings), other tool objects and declaration-only function tools are not.
|
|
335
|
+
|
|
336
|
+
Args:
|
|
337
|
+
tools: A tool, a callable, or a sequence of them, as accepted by ``tools=``.
|
|
338
|
+
|
|
339
|
+
Returns:
|
|
340
|
+
One description per ungoverned tool, empty if every tool is governed.
|
|
341
|
+
"""
|
|
342
|
+
return [d for d in map(_describe_ungoverned, normalize_tools(tools)) if d is not None]
|
|
343
|
+
|
|
344
|
+
def check_tools(self, tools: Sequence[Any] | None) -> None:
|
|
345
|
+
"""Report ungoverned tools (see ``report_ungoverned``).
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
tools: The tools offered to the model.
|
|
349
|
+
"""
|
|
350
|
+
ungoverned = self.ungoverned_tools(tools)
|
|
351
|
+
if ungoverned:
|
|
352
|
+
self.report_ungoverned(ungoverned)
|
|
353
|
+
|
|
354
|
+
def report_ungoverned(self, descriptions: Sequence[str]) -> None:
|
|
355
|
+
"""Raise ``UngovernedToolsError``, or log a warning when ``allow_ungoverned`` is set.
|
|
356
|
+
|
|
357
|
+
Args:
|
|
358
|
+
descriptions: What ACGS cannot check.
|
|
359
|
+
|
|
360
|
+
Raises:
|
|
361
|
+
UngovernedToolsError: Unless ``allow_ungoverned`` is set.
|
|
362
|
+
"""
|
|
363
|
+
listed = "; ".join(descriptions)
|
|
364
|
+
if self.allow_ungoverned:
|
|
365
|
+
logger.warning("ACGS does not check calls of: %s (allow_ungoverned is set).", listed)
|
|
366
|
+
return
|
|
367
|
+
msg = (
|
|
368
|
+
f"ACGS cannot check calls of: {listed}. Remove them, or pass allow_ungoverned=True to run them "
|
|
369
|
+
"without ACGS checks."
|
|
370
|
+
)
|
|
371
|
+
raise UngovernedToolsError(msg)
|
|
File without changes
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agent-framework-acgs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ACGS rule-based tool-call governance for Microsoft Agent Framework function tools, via function middleware and tool approvals
|
|
5
|
+
Project-URL: Homepage, https://github.com/acgs-ai/agent-framework-acgs
|
|
6
|
+
Project-URL: Documentation, https://github.com/acgs-ai/agent-framework-acgs#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/acgs-ai/agent-framework-acgs
|
|
8
|
+
Project-URL: Issues, https://github.com/acgs-ai/agent-framework-acgs/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/acgs-ai/agent-framework-acgs/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Martin Lyu
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: acgs,agent-framework,agents,ai,governance,human-in-the-loop,microsoft-agent-framework,middleware,tool-calls
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: acgs-lite<4,>=3.0.1
|
|
27
|
+
Requires-Dist: agent-framework-core<2,>=1.20.0
|
|
28
|
+
Provides-Extra: mcp
|
|
29
|
+
Requires-Dist: mcp<3,>=1.24.0; extra == 'mcp'
|
|
30
|
+
Requires-Dist: tenacity<10,>=9.1.4; extra == 'mcp'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# agent-framework-acgs
|
|
34
|
+
|
|
35
|
+
[](https://github.com/acgs-ai/agent-framework-acgs/actions/workflows/ci.yml)
|
|
36
|
+
[](https://pypi.org/project/agent-framework-acgs/)
|
|
37
|
+
[](https://pypi.org/project/agent-framework-acgs/)
|
|
38
|
+
|
|
39
|
+
`agent-framework-acgs` checks [Microsoft Agent Framework](https://github.com/microsoft/agent-framework) function
|
|
40
|
+
calls against [ACGS](https://pypi.org/project/acgs-lite/) constitution rules before the function runs. It uses two
|
|
41
|
+
documented framework mechanisms:
|
|
42
|
+
|
|
43
|
+
- [function middleware](https://learn.microsoft.com/en-us/agent-framework/agents/middleware/), which runs right
|
|
44
|
+
before each function call, including a call that was approved;
|
|
45
|
+
- [tool approval](https://learn.microsoft.com/en-us/agent-framework/agents/tools/tool-approval), so calls that need
|
|
46
|
+
review pause the run as `function_approval_request` items that you approve or reject in the same session.
|
|
47
|
+
|
|
48
|
+
What happens to a call:
|
|
49
|
+
|
|
50
|
+
- Calls that match no blocking rule run unchanged.
|
|
51
|
+
- Calls that match a blocking rule do not run. The model gets the reason as the function result and can continue,
|
|
52
|
+
or the run ends with `ACGSToolCallDenied` if you pass `on_deny="raise"`.
|
|
53
|
+
- Calls that only match review rules pause the run for approval and run only once approved. They can also be
|
|
54
|
+
rejected.
|
|
55
|
+
- A blocking rule always wins. Nobody is asked to approve a blocked call, and an approved call is checked again
|
|
56
|
+
and not run if it is blocked.
|
|
57
|
+
- Any error while evaluating a call denies it (fail-closed).
|
|
58
|
+
- A run that offers tools the middleware cannot check (hosted tools, declaration-only tools, tools the caller
|
|
59
|
+
runs) fails with `UngovernedToolsError` before the model is called.
|
|
60
|
+
|
|
61
|
+
The package is a thin adapter over the public `acgs-lite` API.
|
|
62
|
+
|
|
63
|
+
> [!NOTE]
|
|
64
|
+
> This is a community package. It is not part of Microsoft Agent Framework and is not maintained, reviewed or
|
|
65
|
+
> endorsed by Microsoft.
|
|
66
|
+
|
|
67
|
+
## Installation
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install agent-framework-acgs
|
|
71
|
+
pip install "agent-framework-acgs[mcp]" # for local MCP tools
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Requires Python 3.10 or later, `agent-framework-core>=1.20.0,<2` and `acgs-lite>=3.0.1,<4`. The `mcp` extra adds
|
|
75
|
+
`mcp` and `tenacity`, which Agent Framework's MCP tools need.
|
|
76
|
+
|
|
77
|
+
## Usage
|
|
78
|
+
|
|
79
|
+
`guard.middleware` is a list with a chat middleware (`guard.tool_check`, which checks the tools a run offers) and a
|
|
80
|
+
function middleware (`guard.function_middleware`, which checks each call). Pass it wherever Agent Framework takes
|
|
81
|
+
middleware: to the agent, to one run, or to the chat client.
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from agent_framework import Agent
|
|
85
|
+
|
|
86
|
+
from agent_framework_acgs import ACGSGuard
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def send_email(to: str, body: str) -> str:
|
|
90
|
+
"""Send an email."""
|
|
91
|
+
return f"sent to {to}"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
guard = ACGSGuard()
|
|
95
|
+
# client is any Agent Framework chat client, for example OpenAIChatClient() from agent-framework-openai.
|
|
96
|
+
agent = Agent(client=client, tools=[send_email], middleware=guard.middleware)
|
|
97
|
+
|
|
98
|
+
# For one run only:
|
|
99
|
+
# await agent.run("...", middleware=guard.middleware)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Quickstart
|
|
103
|
+
|
|
104
|
+
`examples/quickstart.py` runs offline. A small scripted chat client built on the framework's own
|
|
105
|
+
`FunctionInvocationLayer` and `ChatMiddlewareLayer` stands in for a model:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
"""Block, allow and review tool calls with agent-framework-acgs. Runs offline: python examples/quickstart.py"""
|
|
109
|
+
|
|
110
|
+
import asyncio
|
|
111
|
+
import json
|
|
112
|
+
from collections.abc import Awaitable, Mapping, Sequence
|
|
113
|
+
from typing import Any
|
|
114
|
+
|
|
115
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
116
|
+
from agent_framework import (
|
|
117
|
+
Agent,
|
|
118
|
+
AgentResponse,
|
|
119
|
+
BaseChatClient,
|
|
120
|
+
ChatMiddlewareLayer,
|
|
121
|
+
ChatResponse,
|
|
122
|
+
ChatResponseUpdate,
|
|
123
|
+
Content,
|
|
124
|
+
FunctionInvocationLayer,
|
|
125
|
+
Message,
|
|
126
|
+
ResponseStream,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
from agent_framework_acgs import ACGSGuard
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ScriptedModel(FunctionInvocationLayer[Any], ChatMiddlewareLayer[Any], BaseChatClient[Any]):
|
|
133
|
+
"""Stands in for a real chat client so the example runs offline. Each turn is a list of tool calls."""
|
|
134
|
+
|
|
135
|
+
def __init__(self, *turns: list[tuple[str, str, dict[str, Any]]]) -> None:
|
|
136
|
+
super().__init__()
|
|
137
|
+
self.turns = list(turns)
|
|
138
|
+
|
|
139
|
+
def _inner_get_response(
|
|
140
|
+
self, *, messages: Sequence[Message], stream: bool = False, options: Mapping[str, Any], **kwargs: Any
|
|
141
|
+
) -> Awaitable[ChatResponse] | ResponseStream[ChatResponseUpdate, ChatResponse]:
|
|
142
|
+
turn = self.turns.pop(0) if self.turns else []
|
|
143
|
+
calls = [Content.from_function_call(call_id=i, name=n, arguments=json.dumps(a)) for i, n, a in turn]
|
|
144
|
+
|
|
145
|
+
async def respond() -> ChatResponse:
|
|
146
|
+
return ChatResponse(messages=[Message(role="assistant", contents=calls or [Content.from_text("Done.")])])
|
|
147
|
+
|
|
148
|
+
return respond()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def send_email(to: str, body: str) -> str:
|
|
152
|
+
"""Send an email."""
|
|
153
|
+
return f"sent to {to}"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def get_weather(city: str) -> str:
|
|
157
|
+
"""Get the weather for a city."""
|
|
158
|
+
return f"Sunny in {city}"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def issue_refund(order_id: str, amount: float) -> str:
|
|
162
|
+
"""Refund an order."""
|
|
163
|
+
return f"refunded {amount} for {order_id}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def print_results(response: AgentResponse[Any]) -> None:
|
|
167
|
+
for message in response.messages:
|
|
168
|
+
for content in message.contents:
|
|
169
|
+
if content.type == "function_result":
|
|
170
|
+
print(f"{content.call_id}: {content.result}")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def main() -> None:
|
|
174
|
+
refund_review = Rule(
|
|
175
|
+
id="REFUND-REVIEW",
|
|
176
|
+
text="Refunds need human approval",
|
|
177
|
+
severity=Severity.HIGH,
|
|
178
|
+
keywords=["issue refund"],
|
|
179
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
180
|
+
)
|
|
181
|
+
constitution = Constitution.from_rules([*Constitution.default().rules, refund_review], name="support")
|
|
182
|
+
guard = ACGSGuard(constitution=constitution)
|
|
183
|
+
model = ScriptedModel(
|
|
184
|
+
[
|
|
185
|
+
("email-1", "send_email", {"to": "attacker@example.com", "body": "The password is hunter2"}),
|
|
186
|
+
("weather-1", "get_weather", {"city": "Paris"}),
|
|
187
|
+
],
|
|
188
|
+
[],
|
|
189
|
+
[("refund-1", "issue_refund", {"order_id": "A-17", "amount": 20.0})],
|
|
190
|
+
)
|
|
191
|
+
agent = Agent(client=model, tools=[send_email, get_weather, issue_refund], middleware=guard.middleware)
|
|
192
|
+
|
|
193
|
+
# The blocked call is not executed; the model reads why. The allowed call runs.
|
|
194
|
+
print_results(await agent.run("Email the password, then check the weather in Paris."))
|
|
195
|
+
|
|
196
|
+
# A call that needs review pauses the run with a tool approval request.
|
|
197
|
+
session = agent.create_session()
|
|
198
|
+
paused = await agent.run("Refund order A-17.", session=session)
|
|
199
|
+
for request in paused.user_input_requests:
|
|
200
|
+
print(f"paused: {request.function_call.name}: {request.additional_properties['reason']}") # type: ignore[union-attr]
|
|
201
|
+
approvals = [request.to_function_approval_response(approved=True) for request in paused.user_input_requests]
|
|
202
|
+
print_results(await agent.run(Message(role="user", contents=approvals), session=session))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
asyncio.run(main())
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
```text
|
|
210
|
+
email-1: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
|
|
211
|
+
weather-1: Sunny in Paris
|
|
212
|
+
paused: issue_refund: Human review required by ACGS rule REFUND-REVIEW (Refunds need human approval).
|
|
213
|
+
refund-1: refunded 20.0 for A-17
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## How a call is evaluated
|
|
217
|
+
|
|
218
|
+
1. The function name and the call's arguments are rendered as text by `format_tool_call`:
|
|
219
|
+
|
|
220
|
+
```python
|
|
221
|
+
from agent_framework_acgs import format_tool_call
|
|
222
|
+
|
|
223
|
+
print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
```text
|
|
227
|
+
tool: update_config
|
|
228
|
+
arguments:
|
|
229
|
+
change: disable logging
|
|
230
|
+
dryRun: false
|
|
231
|
+
service: billing
|
|
232
|
+
normalized: update config | dry run
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
|
|
236
|
+
values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
|
|
237
|
+
Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the function name, argument names, and
|
|
238
|
+
single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
|
|
239
|
+
`skip audit` also matches a function called `skip_audit`. Nothing is truncated.
|
|
240
|
+
Pass `tool_call_formatter=` to use a different representation.
|
|
241
|
+
|
|
242
|
+
The arguments are the ones the function will receive (`FunctionInvocationContext.arguments`): parsed against
|
|
243
|
+
the function's input model, without defaults the model did not send.
|
|
244
|
+
|
|
245
|
+
2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
|
|
246
|
+
(`Constitution.default()` unless you pass one).
|
|
247
|
+
|
|
248
|
+
3. The result decides what happens to the call:
|
|
249
|
+
|
|
250
|
+
| ACGS outcome | Result |
|
|
251
|
+
|---|---|
|
|
252
|
+
| No blocking rule matched (warn-only rules may match) | The function runs |
|
|
253
|
+
| Only `require_human_review` / `escalate_to_senior` rules matched | Review (see below) |
|
|
254
|
+
| Any `block`, `block_and_notify` or `halt_and_alert` rule matched | Denied |
|
|
255
|
+
| A rule ID not found in the constitution, or an invalid result without a rule | Denied |
|
|
256
|
+
| Any exception while reading or evaluating the call | Denied (fail-closed) |
|
|
257
|
+
|
|
258
|
+
A matched blocking rule is never downgraded to review because a review rule matched as well.
|
|
259
|
+
The denial reason then lists only the blocking rules after "Blocked by" and names the matched review
|
|
260
|
+
rules separately.
|
|
261
|
+
|
|
262
|
+
A denied call is not executed. The middleware sets `context.result` to
|
|
263
|
+
`"Tool call '<name>' was not executed. <reason>"` and does not call the rest of the pipeline, so the model gets the
|
|
264
|
+
reason as the function result. The reason names the matched rules but never repeats argument values. With
|
|
265
|
+
`on_deny="raise"`, the middleware raises `ACGSToolCallDenied` (a `MiddlewareFailure`, which Agent Framework
|
|
266
|
+
passes to the caller); its `decision` attribute holds the decision.
|
|
267
|
+
|
|
268
|
+
Every decision is stored in `context.metadata["acgs_decision"]` (`DECISION_METADATA_KEY`) for middleware placed
|
|
269
|
+
before the guard. `ACGSGuard.evaluate(tool_name, args)` returns the `GovernanceDecision` without running
|
|
270
|
+
anything.
|
|
271
|
+
|
|
272
|
+
## Review
|
|
273
|
+
|
|
274
|
+
A call that needs review pauses the run. The middleware sets the call's result to a `function_approval_request`,
|
|
275
|
+
which the framework passes through to drive its approval flow (as described for `result` in the
|
|
276
|
+
`FunctionInvocationContext` docstring). The request appears in `response.user_input_requests`; answer it in the
|
|
277
|
+
same session:
|
|
278
|
+
|
|
279
|
+
```python
|
|
280
|
+
from agent_framework import Agent, AgentResponse, Message
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
async def run_with_review(agent: Agent, prompt: str) -> AgentResponse:
|
|
284
|
+
session = agent.create_session()
|
|
285
|
+
response = await agent.run(prompt, session=session)
|
|
286
|
+
while response.user_input_requests:
|
|
287
|
+
answers = []
|
|
288
|
+
for request in response.user_input_requests:
|
|
289
|
+
print(request.function_call.name, request.additional_properties.get("reason"))
|
|
290
|
+
answers.append(request.to_function_approval_response(approved=True)) # or approved=False
|
|
291
|
+
response = await agent.run(Message(role="user", contents=answers), session=session)
|
|
292
|
+
return response
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
When the approved call is replayed, the middleware evaluates it again. It runs only if it still needs review and
|
|
296
|
+
the framework passed an approval for it; if it is blocked by then, it is denied.
|
|
297
|
+
|
|
298
|
+
Things to know:
|
|
299
|
+
|
|
300
|
+
- Review needs an `AgentSession`. The framework binds approval responses to the requests it recorded in the session,
|
|
301
|
+
so an approval without the session, a forged approval, or a replayed approval does not run a call, and an
|
|
302
|
+
approval with edited arguments does not run the edited call. `guard.tool_check` raises `ACGSConfigurationError` if the chat client sets
|
|
303
|
+
`disable_approval_response_binding` (use `on_review="deny"` there).
|
|
304
|
+
- Each request carries `additional_properties["reason"]` and `additional_properties["acgs"]`
|
|
305
|
+
(`APPROVAL_PROPERTIES_KEY`) with `verdict`, `rule_ids` and `warning_rule_ids`.
|
|
306
|
+
- A rejected call does not run; the model gets the framework's rejection message.
|
|
307
|
+
- Streamed runs work the same; the requests are on the final response. Sessions saved with `session.to_dict()` and
|
|
308
|
+
restored with `AgentSession.from_dict(...)` can be resumed.
|
|
309
|
+
- For a function with `approval_mode="always_require"`, the framework asks first and one approval covers both;
|
|
310
|
+
a blocked call is denied after approval.
|
|
311
|
+
- Standing approval rules of `ToolApprovalMiddleware` (`create_always_approve_tool_response`) also answer ACGS
|
|
312
|
+
review requests: later review calls of that tool in the session run without asking. Blocked calls are still
|
|
313
|
+
denied.
|
|
314
|
+
- An agent used as a tool (`Agent.as_tool`) cannot ask for approval through the outer run. A call inside it that
|
|
315
|
+
needs review does not run, and the outer model gets an error result. Use `on_review="deny"` for such agents.
|
|
316
|
+
- Use `on_review="deny"` for runs nobody can approve.
|
|
317
|
+
|
|
318
|
+
## What is covered
|
|
319
|
+
|
|
320
|
+
| Tool | Checked | How |
|
|
321
|
+
|---|---|---|
|
|
322
|
+
| Function tools (plain functions, `@tool`, `FunctionTool(...)`) | Yes | Function middleware |
|
|
323
|
+
| Local MCP tools (`MCPStdioTool`, `MCPStreamableHTTPTool`, `MCPWebsocketTool`) | Yes | The framework calls them as function tools |
|
|
324
|
+
| `Agent.as_tool(...)` | The call to the agent tool, yes | Pass the guard to the inner agent too to check its calls |
|
|
325
|
+
| Tools added during a run (`FunctionInvocationContext.add_tools`) | Function tools, yes | Others are refused before the next model call |
|
|
326
|
+
| Hosted tools (provider tools given as dicts or provider objects, such as hosted web search, code interpreter or hosted MCP) | No | The provider runs them; refused |
|
|
327
|
+
| Declaration-only function tools (no implementation) | No | The caller runs them; refused |
|
|
328
|
+
| `function_invocation_configuration["additional_tools"]` | No | The caller runs them; refused |
|
|
329
|
+
| Any tool when function invocation is off (`enabled=False`) or the client has no `FunctionInvocationLayer` | No | The caller runs them; refused |
|
|
330
|
+
|
|
331
|
+
Refused means `guard.tool_check` raises `UngovernedToolsError` before the model is called. Pass
|
|
332
|
+
`allow_ungoverned=True` to run such tools with a logged warning instead; their calls are not checked.
|
|
333
|
+
|
|
334
|
+
`guard.tool_check` is a chat middleware, so it runs only on chat clients built with `ChatMiddlewareLayer`. On a
|
|
335
|
+
client without it, the function middleware still checks every call and raises `UngovernedToolsError` when a
|
|
336
|
+
function is called in a run that offers ungoverned tools, but by then the model has already seen those tools.
|
|
337
|
+
|
|
338
|
+
## Middleware order
|
|
339
|
+
|
|
340
|
+
Function middleware runs in the order client, agent, run, and in list order within each. Middleware placed after
|
|
341
|
+
the guard runs after the check, so a middleware there that changes `context.arguments` changes them unchecked.
|
|
342
|
+
Put `guard.middleware` last, at the innermost level you use.
|
|
343
|
+
|
|
344
|
+
## Custom constitutions
|
|
345
|
+
|
|
346
|
+
```python
|
|
347
|
+
from acgs_lite import Constitution, Rule, Severity, ViolationAction
|
|
348
|
+
|
|
349
|
+
from agent_framework_acgs import ACGSGuard
|
|
350
|
+
|
|
351
|
+
constitution = Constitution.from_rules(
|
|
352
|
+
[
|
|
353
|
+
Rule(
|
|
354
|
+
id="NO-DESTRUCTIVE-SQL",
|
|
355
|
+
text="No destructive SQL",
|
|
356
|
+
severity=Severity.CRITICAL,
|
|
357
|
+
keywords=["drop table", "truncate table"],
|
|
358
|
+
),
|
|
359
|
+
Rule(
|
|
360
|
+
id="REFUND-REVIEW",
|
|
361
|
+
text="Refunds need approval",
|
|
362
|
+
severity=Severity.HIGH,
|
|
363
|
+
keywords=["refund"],
|
|
364
|
+
workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
|
|
365
|
+
),
|
|
366
|
+
],
|
|
367
|
+
name="payments",
|
|
368
|
+
)
|
|
369
|
+
guard = ACGSGuard(constitution=constitution, agent_id="payments-app")
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
`Constitution.from_yaml("rules.yaml")` works as well. To enforce two constitutions, add two guards; a call runs
|
|
373
|
+
only if both allow it.
|
|
374
|
+
|
|
375
|
+
## Options
|
|
376
|
+
|
|
377
|
+
| Argument | Default | Meaning |
|
|
378
|
+
|---|---|---|
|
|
379
|
+
| `constitution` | `Constitution.default()` | Rules to enforce |
|
|
380
|
+
| `agent_id` | `"agent-framework"` | Agent identifier recorded by ACGS |
|
|
381
|
+
| `on_review` | `"approve"` | `"approve"` (pause for approval) or `"deny"` |
|
|
382
|
+
| `on_deny` | `"reject"` | `"reject"` (function result with the reason) or `"raise"` (`ACGSToolCallDenied`) |
|
|
383
|
+
| `allow_ungoverned` | `False` | Run tools the middleware cannot check, with a logged warning, instead of raising |
|
|
384
|
+
| `tool_call_formatter` | `format_tool_call` | `(tool_name, args) -> str` used as the evaluated text |
|
|
385
|
+
|
|
386
|
+
## Limitations
|
|
387
|
+
|
|
388
|
+
- Only tools listed as checked in [What is covered](#what-is-covered). User input, model output, and function
|
|
389
|
+
results are not checked; other Agent Framework middleware can handle those.
|
|
390
|
+
- With `on_deny="raise"`, other calls from the same model turn may already have run: with concurrent invocation
|
|
391
|
+
(the default), allowed calls can run alongside the denied one; with `allow_concurrent_invocation=False`, earlier
|
|
392
|
+
calls ran and later ones do not start.
|
|
393
|
+
- Defaults the model did not send are not evaluated, and arguments the function does not declare are dropped by
|
|
394
|
+
the framework before the check (they are not passed to the function either).
|
|
395
|
+
- Middleware placed after the guard can change the arguments after the check (see
|
|
396
|
+
[Middleware order](#middleware-order)).
|
|
397
|
+
- Tested with `Agent.run` streamed and not, parallel calls in one model turn, approval, rejection and resume
|
|
398
|
+
(including a serialized session), forged, edited, replayed and session-less approvals, `approval_mode`,
|
|
399
|
+
`ToolApprovalMiddleware`, client-, agent- and run-level middleware, `Agent.as_tool`, `add_tools`, and a local
|
|
400
|
+
stdio MCP server, against agent-framework-core 1.20.0 and the latest release. Workflows, hosted agent services
|
|
401
|
+
and declarative agents are not tested.
|
|
402
|
+
- `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
|
|
403
|
+
and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
|
|
404
|
+
patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
|
|
405
|
+
tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
|
|
406
|
+
- Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
|
|
407
|
+
("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
|
|
408
|
+
(`api-key` does not match the keyword `api_key`).
|
|
409
|
+
- Because argument names are part of the evaluated text, a function with a parameter named `password` is denied
|
|
410
|
+
under the default constitution whenever it is called.
|
|
411
|
+
- Agent Framework releases often. The adapter allows `agent-framework-core<2` and is tested against the oldest
|
|
412
|
+
supported and the latest release. agent-framework-core 1.20.0 is the minimum because earlier releases run an
|
|
413
|
+
approved call even when the approval came without a session.
|
|
414
|
+
|
|
415
|
+
## Development
|
|
416
|
+
|
|
417
|
+
```bash
|
|
418
|
+
uv sync --group dev # or use hatch: hatch run prepare
|
|
419
|
+
hatch run format # ruff format + ruff check --fix
|
|
420
|
+
hatch run lint # ruff check + ruff format --check
|
|
421
|
+
hatch run typecheck # mypy --strict
|
|
422
|
+
hatch run cov # pytest with a 100% branch-coverage gate, network disabled
|
|
423
|
+
hatch run min:cov # the same tests against agent-framework-core 1.20.0, acgs-lite 3.0.1 and mcp 1.24.0
|
|
424
|
+
pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
|
|
428
|
+
and the changelog.
|
|
429
|
+
|
|
430
|
+
## License
|
|
431
|
+
|
|
432
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
agent_framework_acgs/__init__.py,sha256=0WQPh-8rvf4SUy3fBP6mNtBc60MIkYFY-8-RHNJOs-E,858
|
|
2
|
+
agent_framework_acgs/_governance.py,sha256=PWI_T24mQhyFW3xfCVh0pe8FWxXdWGf6cm7ehv7_Il8,13033
|
|
3
|
+
agent_framework_acgs/middleware.py,sha256=_lNGZzdYEqHdLr1PVlUPmkZvkIxgmsz-BFbUpaflbyQ,15350
|
|
4
|
+
agent_framework_acgs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
agent_framework_acgs-0.1.0.dist-info/METADATA,sha256=WGbzk0Ptyc6uMVklxs5HnPPS7cTL9Bdi0RobJCzYtzU,21025
|
|
6
|
+
agent_framework_acgs-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
7
|
+
agent_framework_acgs-0.1.0.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
|
|
8
|
+
agent_framework_acgs-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.
|