intent-envelope 0.2.0__tar.gz → 0.2.1__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.
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/PKG-INFO +57 -1
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/README.md +54 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/pyproject.toml +5 -1
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/__init__.py +12 -1
- intent_envelope-0.2.1/src/intent_envelope/adapters/__init__.py +20 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/_core.py +103 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/autogen.py +52 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/claude_agent_sdk.py +62 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/crewai.py +73 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/langgraph.py +42 -0
- intent_envelope-0.2.1/src/intent_envelope/adapters/openai_agents.py +60 -0
- intent_envelope-0.2.1/src/intent_envelope/amend.py +328 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/enforce.py +10 -1
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/evaluate.py +187 -0
- intent_envelope-0.2.1/src/intent_envelope/schema/intent-envelope-0.2.json +349 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/validate.py +12 -5
- intent_envelope-0.2.1/tests/adapters_common.py +16 -0
- intent_envelope-0.2.1/tests/test_adapter_autogen.py +46 -0
- intent_envelope-0.2.1/tests/test_adapter_claude_agent_sdk.py +53 -0
- intent_envelope-0.2.1/tests/test_adapter_core.py +53 -0
- intent_envelope-0.2.1/tests/test_adapter_crewai.py +48 -0
- intent_envelope-0.2.1/tests/test_adapter_langgraph.py +84 -0
- intent_envelope-0.2.1/tests/test_adapter_openai_agents.py +54 -0
- intent_envelope-0.2.1/tests/test_packs.py +27 -0
- intent_envelope-0.2.1/tests/test_v02.py +142 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/.gitignore +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/cli.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/src/intent_envelope/schema/intent-envelope-0.1.json +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tests/test_conformance.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tests/test_decisions.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tests/test_enforcement.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tests/test_expires_format.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tests/test_packaging.py +0 -0
- {intent_envelope-0.2.0 → intent_envelope-0.2.1}/tools/consumer_smoke.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: intent-envelope
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Declare what an AI agent is for, and enforce it in code at every tool call.
|
|
5
5
|
Project-URL: Homepage, https://securedai.org/agent-intent
|
|
6
6
|
Project-URL: Documentation, https://securedai.org/architecture
|
|
@@ -15,6 +15,8 @@ Classifier: Topic :: Security
|
|
|
15
15
|
Requires-Python: >=3.9
|
|
16
16
|
Requires-Dist: jsonschema>=4.18
|
|
17
17
|
Requires-Dist: rfc3339-validator>=0.1.4
|
|
18
|
+
Provides-Extra: signing
|
|
19
|
+
Requires-Dist: cryptography>=42; extra == 'signing'
|
|
18
20
|
Description-Content-Type: text/markdown
|
|
19
21
|
|
|
20
22
|
# Intent Envelope
|
|
@@ -75,6 +77,60 @@ pip install intent-envelope
|
|
|
75
77
|
intent-envelope validate examples/crm-enrichment-agent.json
|
|
76
78
|
```
|
|
77
79
|
|
|
80
|
+
## In an agent framework
|
|
81
|
+
|
|
82
|
+
The Python package has an adapter for each of five frameworks. Each one decides every
|
|
83
|
+
call with an `EnforcementPoint` at the place the framework runs a tool, with the
|
|
84
|
+
arguments the tool will actually run with, and tells the agent why a refused call did not
|
|
85
|
+
run. None of the frameworks is a dependency: an adapter imports its framework only when
|
|
86
|
+
you use it.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from intent_envelope import EnforcementPoint
|
|
90
|
+
ep = EnforcementPoint(envelope)
|
|
91
|
+
|
|
92
|
+
# LangGraph: every tool a ToolNode holds, sync or async
|
|
93
|
+
from intent_envelope.adapters.langgraph import guard_tool_node
|
|
94
|
+
node = ToolNode(tools, **guard_tool_node(ep))
|
|
95
|
+
|
|
96
|
+
# CrewAI: at the tool itself, after any hook that might rewrite its input
|
|
97
|
+
from intent_envelope.adapters.crewai import guard_tools
|
|
98
|
+
agent = Agent(role="Refunds", goal="...", backstory="...", tools=guard_tools(ep, tools))
|
|
99
|
+
|
|
100
|
+
# AutoGen (autogen-agentchat 0.4 and later): same name, description and schema
|
|
101
|
+
from intent_envelope.adapters.autogen import guard_tools
|
|
102
|
+
agent = AssistantAgent("refunds", model_client=client, tools=guard_tools(ep, tools))
|
|
103
|
+
|
|
104
|
+
# OpenAI Agents SDK: a tool input guardrail on every function tool
|
|
105
|
+
from intent_envelope.adapters.openai_agents import guard_tools
|
|
106
|
+
agent = Agent(name="refunds", tools=guard_tools(ep, tools))
|
|
107
|
+
|
|
108
|
+
# Claude Agent SDK: a PreToolUse hook covering built-in and MCP tools
|
|
109
|
+
from intent_envelope.adapters.claude_agent_sdk import hooks
|
|
110
|
+
options = ClaudeAgentOptions(hooks=hooks(ep))
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
What they hold to:
|
|
114
|
+
|
|
115
|
+
- **A refused call never runs.** LangGraph gets an error `ToolMessage`, CrewAI and the
|
|
116
|
+
OpenAI Agents SDK return the reason as the tool's result, AutoGen raises, and the
|
|
117
|
+
Claude Agent SDK denies the call with the reason.
|
|
118
|
+
- **An escalation is refused unless you can get an answer.** Pass `approve=`, a function
|
|
119
|
+
given the decision that returns `True` only once the named person approved (it may be
|
|
120
|
+
async). Anything else, including an exception, refuses.
|
|
121
|
+
- **Parallel calls cannot overrun a limit.** LangGraph runs a node's calls in a thread
|
|
122
|
+
pool, so deciding a call and counting it against `max_tool_calls` is one locked step.
|
|
123
|
+
- **What cannot be guarded is refused, not passed through.** The OpenAI SDK's hosted
|
|
124
|
+
tools run on OpenAI's side, so `guard_tools` refuses them.
|
|
125
|
+
- **The Claude hook does not grant anything.** An allowed call gets no decision, so the
|
|
126
|
+
SDK's own permission checks still apply, and an error in the check denies.
|
|
127
|
+
|
|
128
|
+
Two things to know. Tool names are the framework's: in the Claude Agent SDK an MCP tool
|
|
129
|
+
is `mcp__<server>__<tool>`. And a hook that rewrites a tool's input after the check
|
|
130
|
+
(another Claude `PreToolUse` hook returning `updatedInput`) means the call that runs is
|
|
131
|
+
not the call that was checked, so do not pair the two. CI runs each adapter against the
|
|
132
|
+
latest release of its framework.
|
|
133
|
+
|
|
78
134
|
## The examples
|
|
79
135
|
|
|
80
136
|
Each one is drawn from an engagement published at https://securedai.org/case-studies,
|
|
@@ -56,6 +56,60 @@ pip install intent-envelope
|
|
|
56
56
|
intent-envelope validate examples/crm-enrichment-agent.json
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
+
## In an agent framework
|
|
60
|
+
|
|
61
|
+
The Python package has an adapter for each of five frameworks. Each one decides every
|
|
62
|
+
call with an `EnforcementPoint` at the place the framework runs a tool, with the
|
|
63
|
+
arguments the tool will actually run with, and tells the agent why a refused call did not
|
|
64
|
+
run. None of the frameworks is a dependency: an adapter imports its framework only when
|
|
65
|
+
you use it.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from intent_envelope import EnforcementPoint
|
|
69
|
+
ep = EnforcementPoint(envelope)
|
|
70
|
+
|
|
71
|
+
# LangGraph: every tool a ToolNode holds, sync or async
|
|
72
|
+
from intent_envelope.adapters.langgraph import guard_tool_node
|
|
73
|
+
node = ToolNode(tools, **guard_tool_node(ep))
|
|
74
|
+
|
|
75
|
+
# CrewAI: at the tool itself, after any hook that might rewrite its input
|
|
76
|
+
from intent_envelope.adapters.crewai import guard_tools
|
|
77
|
+
agent = Agent(role="Refunds", goal="...", backstory="...", tools=guard_tools(ep, tools))
|
|
78
|
+
|
|
79
|
+
# AutoGen (autogen-agentchat 0.4 and later): same name, description and schema
|
|
80
|
+
from intent_envelope.adapters.autogen import guard_tools
|
|
81
|
+
agent = AssistantAgent("refunds", model_client=client, tools=guard_tools(ep, tools))
|
|
82
|
+
|
|
83
|
+
# OpenAI Agents SDK: a tool input guardrail on every function tool
|
|
84
|
+
from intent_envelope.adapters.openai_agents import guard_tools
|
|
85
|
+
agent = Agent(name="refunds", tools=guard_tools(ep, tools))
|
|
86
|
+
|
|
87
|
+
# Claude Agent SDK: a PreToolUse hook covering built-in and MCP tools
|
|
88
|
+
from intent_envelope.adapters.claude_agent_sdk import hooks
|
|
89
|
+
options = ClaudeAgentOptions(hooks=hooks(ep))
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
What they hold to:
|
|
93
|
+
|
|
94
|
+
- **A refused call never runs.** LangGraph gets an error `ToolMessage`, CrewAI and the
|
|
95
|
+
OpenAI Agents SDK return the reason as the tool's result, AutoGen raises, and the
|
|
96
|
+
Claude Agent SDK denies the call with the reason.
|
|
97
|
+
- **An escalation is refused unless you can get an answer.** Pass `approve=`, a function
|
|
98
|
+
given the decision that returns `True` only once the named person approved (it may be
|
|
99
|
+
async). Anything else, including an exception, refuses.
|
|
100
|
+
- **Parallel calls cannot overrun a limit.** LangGraph runs a node's calls in a thread
|
|
101
|
+
pool, so deciding a call and counting it against `max_tool_calls` is one locked step.
|
|
102
|
+
- **What cannot be guarded is refused, not passed through.** The OpenAI SDK's hosted
|
|
103
|
+
tools run on OpenAI's side, so `guard_tools` refuses them.
|
|
104
|
+
- **The Claude hook does not grant anything.** An allowed call gets no decision, so the
|
|
105
|
+
SDK's own permission checks still apply, and an error in the check denies.
|
|
106
|
+
|
|
107
|
+
Two things to know. Tool names are the framework's: in the Claude Agent SDK an MCP tool
|
|
108
|
+
is `mcp__<server>__<tool>`. And a hook that rewrites a tool's input after the check
|
|
109
|
+
(another Claude `PreToolUse` hook returning `updatedInput`) means the call that runs is
|
|
110
|
+
not the call that was checked, so do not pair the two. CI runs each adapter against the
|
|
111
|
+
latest release of its framework.
|
|
112
|
+
|
|
59
113
|
## The examples
|
|
60
114
|
|
|
61
115
|
Each one is drawn from an engagement published at https://securedai.org/case-studies,
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "intent-envelope"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.1"
|
|
8
8
|
description = "Declare what an AI agent is for, and enforce it in code at every tool call."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -22,6 +22,10 @@ classifiers = [
|
|
|
22
22
|
# accepts any string, so this pin is load bearing rather than cosmetic.
|
|
23
23
|
dependencies = ["jsonschema>=4.18", "rfc3339-validator>=0.1.4"]
|
|
24
24
|
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
# Verifying a signed amendment (Intent Envelope 0.2). Everything else works without it.
|
|
27
|
+
signing = ["cryptography>=42"]
|
|
28
|
+
|
|
25
29
|
[project.scripts]
|
|
26
30
|
intent-envelope = "intent_envelope.cli:main"
|
|
27
31
|
|
|
@@ -21,9 +21,11 @@ from .evaluate import (
|
|
|
21
21
|
default_data_matcher,
|
|
22
22
|
evaluate,
|
|
23
23
|
)
|
|
24
|
+
from .amend import Admission, AmendmentCheck, admit_component, canonical, check_amendment, sign_amendment, widening
|
|
25
|
+
from .evaluate import host_matches
|
|
24
26
|
from .validate import ValidationError, load_schema, validate
|
|
25
27
|
|
|
26
|
-
__version__ = "0.2.
|
|
28
|
+
__version__ = "0.2.1"
|
|
27
29
|
__all__ = [
|
|
28
30
|
# envelopes
|
|
29
31
|
"validate",
|
|
@@ -43,5 +45,14 @@ __all__ = [
|
|
|
43
45
|
"default_facts",
|
|
44
46
|
"Refused",
|
|
45
47
|
"Escalated",
|
|
48
|
+
# 0.2
|
|
49
|
+
"host_matches",
|
|
50
|
+
"check_amendment",
|
|
51
|
+
"sign_amendment",
|
|
52
|
+
"widening",
|
|
53
|
+
"canonical",
|
|
54
|
+
"admit_component",
|
|
55
|
+
"AmendmentCheck",
|
|
56
|
+
"Admission",
|
|
46
57
|
"__version__",
|
|
47
58
|
]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Enforce an envelope inside an agent framework, at the point it runs a tool.
|
|
2
|
+
|
|
3
|
+
One module per framework, each importing that framework only when used, so installing
|
|
4
|
+
intent-envelope pulls in none of them:
|
|
5
|
+
|
|
6
|
+
intent_envelope.adapters.langgraph ToolNode(tools, **guard_tool_node(ep))
|
|
7
|
+
intent_envelope.adapters.crewai Agent(tools=guard_tools(ep, tools))
|
|
8
|
+
intent_envelope.adapters.autogen AssistantAgent(tools=guard_tools(ep, tools))
|
|
9
|
+
intent_envelope.adapters.openai_agents Agent(tools=guard_tools(ep, tools))
|
|
10
|
+
intent_envelope.adapters.claude_agent_sdk ClaudeAgentOptions(hooks=hooks(ep))
|
|
11
|
+
|
|
12
|
+
Each one decides the call with the EnforcementPoint you pass, before the tool runs, with
|
|
13
|
+
the arguments the tool will actually run with. A refused call never runs, and the agent
|
|
14
|
+
is told why in the framework's own way. The EnforcementPoint keeps the run's counts and
|
|
15
|
+
every decision, as it does without a framework.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from ._core import Verdict, adecide, decide
|
|
19
|
+
|
|
20
|
+
__all__ = ["Verdict", "decide", "adecide"]
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""What every adapter shares: decide a call, and say what the agent is told.
|
|
2
|
+
|
|
3
|
+
An adapter is only the place a framework lets something run before a tool does. The
|
|
4
|
+
decision is the EnforcementPoint's, and is the same whichever framework asked.
|
|
5
|
+
|
|
6
|
+
Escalation: a framework has no person to ask, so by default an escalated call is
|
|
7
|
+
refused and the agent is told who it needed. Pass `approve`, a function given the
|
|
8
|
+
Decision that returns True only once the named person has approved, to wait for one.
|
|
9
|
+
It may be async. Anything but True, or an exception, refuses.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import inspect
|
|
15
|
+
import threading
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, Awaitable, Callable, Dict, Optional, Union
|
|
18
|
+
|
|
19
|
+
from ..enforce import EnforcementPoint
|
|
20
|
+
from ..evaluate import ALLOW, ESCALATE, Decision
|
|
21
|
+
|
|
22
|
+
Approver = Callable[[Decision], Union[bool, Awaitable[bool]]]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Verdict:
|
|
27
|
+
allowed: bool
|
|
28
|
+
decision: Decision
|
|
29
|
+
#: What the agent is told when the call is refused. Empty when it is allowed.
|
|
30
|
+
message: str = ""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _refusal(d: Decision) -> str:
|
|
34
|
+
if d.result == ESCALATE:
|
|
35
|
+
return (f"Not run: this call needs approval from {d.escalate_to} under the intent "
|
|
36
|
+
f"envelope ({d.detail}), and none was given.")
|
|
37
|
+
return f"Not run: the intent envelope refused this call ({d.rule}: {d.detail})."
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_LOCKS_GUARD = threading.Lock()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _lock(ep: EnforcementPoint) -> threading.Lock:
|
|
44
|
+
# Frameworks run tool calls in parallel (LangGraph's ToolNode uses a thread pool).
|
|
45
|
+
# Deciding a call and counting it against max_tool_calls has to be one step, or
|
|
46
|
+
# two calls that each see 9 of 10 both run.
|
|
47
|
+
with _LOCKS_GUARD:
|
|
48
|
+
lock = getattr(ep, "_adapter_lock", None)
|
|
49
|
+
if lock is None:
|
|
50
|
+
lock = threading.Lock()
|
|
51
|
+
ep._adapter_lock = lock # type: ignore[attr-defined]
|
|
52
|
+
return lock
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _count(ep: EnforcementPoint, d: Decision) -> None:
|
|
56
|
+
# An approved escalation is a call that runs, so it spends the run's budget exactly
|
|
57
|
+
# as an allow does in EnforcementPoint.check.
|
|
58
|
+
ep.state.tool_calls_made += 1
|
|
59
|
+
ep.state.spend_usd += d.call.estimated_cost_usd
|
|
60
|
+
ep.state.recipients_contacted += len(d.call.recipients)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def decide(ep: EnforcementPoint, tool: str, arguments: Optional[Dict[str, Any]],
|
|
64
|
+
approve: Optional[Approver] = None) -> Verdict:
|
|
65
|
+
"""For frameworks that call tools synchronously."""
|
|
66
|
+
with _lock(ep):
|
|
67
|
+
d = ep.check(tool, dict(arguments or {}))
|
|
68
|
+
if d.result == ALLOW:
|
|
69
|
+
return Verdict(True, d)
|
|
70
|
+
if d.result == ESCALATE and approve is not None:
|
|
71
|
+
try:
|
|
72
|
+
ok = approve(d)
|
|
73
|
+
if inspect.isawaitable(ok):
|
|
74
|
+
getattr(ok, "close", lambda: None)() # never awaited, so close it
|
|
75
|
+
raise TypeError("approve returned an awaitable where a synchronous answer was needed")
|
|
76
|
+
except Exception:
|
|
77
|
+
ok = False
|
|
78
|
+
if ok is True:
|
|
79
|
+
with _lock(ep):
|
|
80
|
+
_count(ep, d)
|
|
81
|
+
return Verdict(True, d)
|
|
82
|
+
return Verdict(False, d, _refusal(d))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def adecide(ep: EnforcementPoint, tool: str, arguments: Optional[Dict[str, Any]],
|
|
86
|
+
approve: Optional[Approver] = None) -> Verdict:
|
|
87
|
+
"""For frameworks that call tools asynchronously. `approve` may be async."""
|
|
88
|
+
with _lock(ep):
|
|
89
|
+
d = ep.check(tool, dict(arguments or {}))
|
|
90
|
+
if d.result == ALLOW:
|
|
91
|
+
return Verdict(True, d)
|
|
92
|
+
if d.result == ESCALATE and approve is not None:
|
|
93
|
+
try:
|
|
94
|
+
ok = approve(d)
|
|
95
|
+
if inspect.isawaitable(ok):
|
|
96
|
+
ok = await ok
|
|
97
|
+
except Exception:
|
|
98
|
+
ok = False
|
|
99
|
+
if ok is True:
|
|
100
|
+
with _lock(ep):
|
|
101
|
+
_count(ep, d)
|
|
102
|
+
return Verdict(True, d)
|
|
103
|
+
return Verdict(False, d, _refusal(d))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""AutoGen (autogen-agentchat 0.4 and later): a tool that checks before it runs.
|
|
2
|
+
|
|
3
|
+
from intent_envelope.adapters.autogen import guard_tools
|
|
4
|
+
|
|
5
|
+
agent = AssistantAgent("refunds", model_client=client, tools=guard_tools(ep, [refund_tool]))
|
|
6
|
+
|
|
7
|
+
Each tool is wrapped in one that has the same name, description and argument schema, so
|
|
8
|
+
the model sees no difference. A refused call raises, which AutoGen returns to the model
|
|
9
|
+
as an error result, and the wrapped tool never runs.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Any, List, Optional
|
|
15
|
+
|
|
16
|
+
from ..enforce import EnforcementPoint
|
|
17
|
+
from ._core import Approver, adecide
|
|
18
|
+
|
|
19
|
+
__all__ = ["guard_tools", "Refused"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Refused(PermissionError):
|
|
23
|
+
"""A call the envelope refused. The message is what the model is told."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def guard_tools(ep: EnforcementPoint, tools: List[Any], approve: Optional[Approver] = None) -> List[Any]:
|
|
27
|
+
from autogen_core.tools import BaseTool, FunctionTool
|
|
28
|
+
|
|
29
|
+
class GuardedTool(BaseTool): # type: ignore[misc, valid-type]
|
|
30
|
+
def __init__(self, inner: Any):
|
|
31
|
+
super().__init__(inner.args_type(), inner.return_type(), inner.name, inner.description,
|
|
32
|
+
strict=getattr(inner, "_strict", False))
|
|
33
|
+
self._inner = inner
|
|
34
|
+
|
|
35
|
+
async def run(self, args: Any, cancellation_token: Any) -> Any:
|
|
36
|
+
arguments = args.model_dump() if hasattr(args, "model_dump") else dict(args)
|
|
37
|
+
v = await adecide(ep, self.name, arguments, approve)
|
|
38
|
+
if not v.allowed:
|
|
39
|
+
raise Refused(v.message)
|
|
40
|
+
return await self._inner.run(args, cancellation_token)
|
|
41
|
+
|
|
42
|
+
def return_value_as_string(self, value: Any) -> str:
|
|
43
|
+
return self._inner.return_value_as_string(value)
|
|
44
|
+
|
|
45
|
+
out = []
|
|
46
|
+
for t in tools:
|
|
47
|
+
if callable(t) and not isinstance(t, BaseTool):
|
|
48
|
+
t = FunctionTool(t, description=(t.__doc__ or t.__name__).strip())
|
|
49
|
+
if not isinstance(t, BaseTool):
|
|
50
|
+
raise TypeError(f"{t!r} is not an AutoGen tool, so it cannot be guarded")
|
|
51
|
+
out.append(GuardedTool(t))
|
|
52
|
+
return out
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Claude Agent SDK: a PreToolUse hook that refuses what the envelope refuses.
|
|
2
|
+
|
|
3
|
+
from claude_agent_sdk import ClaudeAgentOptions
|
|
4
|
+
from intent_envelope.adapters.claude_agent_sdk import hooks
|
|
5
|
+
|
|
6
|
+
options = ClaudeAgentOptions(hooks=hooks(ep), allowed_tools=[...])
|
|
7
|
+
|
|
8
|
+
The hook runs before every tool call, built-in and MCP alike. Tool names are the SDK's:
|
|
9
|
+
`Bash`, `Write`, `WebFetch`, and `mcp__<server>__<tool>` for MCP tools, so write the
|
|
10
|
+
envelope's tools.allow in those names.
|
|
11
|
+
|
|
12
|
+
A refused call is denied with the reason, which Claude sees. An allowed call is passed on
|
|
13
|
+
with no decision, not with "allow": the envelope says what is permitted, and it should
|
|
14
|
+
not switch off the SDK's own permission checks for a call they would stop. An error
|
|
15
|
+
inside the check denies the call, and where the SDK supports it the hook is registered
|
|
16
|
+
with on_failure "block", so a hook that fails or times out does not let the call run.
|
|
17
|
+
|
|
18
|
+
Another PreToolUse hook can rewrite a tool's input (updatedInput). Do not pair this one
|
|
19
|
+
with a hook that does, or the call that runs may not be the call that was checked.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from typing import Any, Dict, List, Optional
|
|
25
|
+
|
|
26
|
+
from ..enforce import EnforcementPoint
|
|
27
|
+
from ._core import Approver, adecide
|
|
28
|
+
|
|
29
|
+
__all__ = ["hooks", "pre_tool_use"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def pre_tool_use(ep: EnforcementPoint, approve: Optional[Approver] = None) -> Any:
|
|
33
|
+
async def check(input_data: Dict[str, Any], tool_use_id: Optional[str], context: Any) -> Dict[str, Any]:
|
|
34
|
+
tool = input_data.get("tool_name")
|
|
35
|
+
if not isinstance(tool, str) or not tool:
|
|
36
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
37
|
+
"permissionDecisionReason": "Not run: no tool name to check against the intent envelope."}}
|
|
38
|
+
try:
|
|
39
|
+
v = await adecide(ep, tool, input_data.get("tool_input") or {}, approve)
|
|
40
|
+
except Exception as e: # a hook that throws must not let the call through
|
|
41
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
42
|
+
"permissionDecisionReason": f"Not run: the intent envelope check failed: {e}"}}
|
|
43
|
+
if v.allowed:
|
|
44
|
+
return {}
|
|
45
|
+
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
46
|
+
"permissionDecisionReason": v.message}}
|
|
47
|
+
|
|
48
|
+
return check
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def hooks(ep: EnforcementPoint, approve: Optional[Approver] = None) -> Dict[str, List[Any]]:
|
|
52
|
+
"""The `hooks` argument for ClaudeAgentOptions."""
|
|
53
|
+
from claude_agent_sdk import HookMatcher
|
|
54
|
+
|
|
55
|
+
check = pre_tool_use(ep, approve)
|
|
56
|
+
try:
|
|
57
|
+
matcher = HookMatcher(matcher=None, hooks=[check], on_failure="block")
|
|
58
|
+
except TypeError:
|
|
59
|
+
# Older SDKs have no on_failure. The hook catches its own errors and denies, so
|
|
60
|
+
# the only thing lost is blocking on a hook timeout.
|
|
61
|
+
matcher = HookMatcher(matcher=None, hooks=[check])
|
|
62
|
+
return {"PreToolUse": [matcher]}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""CrewAI: decide every call a tool makes, at the tool.
|
|
2
|
+
|
|
3
|
+
from intent_envelope.adapters.crewai import guard_tools
|
|
4
|
+
|
|
5
|
+
agent = Agent(role=..., tools=guard_tools(ep, [RefundTool(), lookup]))
|
|
6
|
+
|
|
7
|
+
Wraps each tool's own run method rather than registering a before_tool_call hook.
|
|
8
|
+
CrewAI lets a before hook change the tool's input in place, so a hook that runs after
|
|
9
|
+
this one could change a call that was already approved. At the tool, the check sees the
|
|
10
|
+
arguments it is about to run with, defaults filled in, whatever ran before it. A refused
|
|
11
|
+
call returns the reason to the agent as the tool's output, and the tool does not run.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import inspect
|
|
17
|
+
from typing import Any, List, Optional
|
|
18
|
+
|
|
19
|
+
from ..enforce import EnforcementPoint
|
|
20
|
+
from ._core import Approver, adecide, decide
|
|
21
|
+
|
|
22
|
+
__all__ = ["guard_tools"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _wrap(fn: Any, name: str, ep: EnforcementPoint, approve: Optional[Approver]) -> Any:
|
|
26
|
+
sig = inspect.signature(fn)
|
|
27
|
+
|
|
28
|
+
def arguments(args: tuple, kwargs: dict) -> dict:
|
|
29
|
+
# Name positional arguments and fill defaults, so the envelope sees exactly what runs.
|
|
30
|
+
try:
|
|
31
|
+
bound = sig.bind(*args, **kwargs)
|
|
32
|
+
bound.apply_defaults()
|
|
33
|
+
return {k: v for k, v in bound.arguments.items() if k != "self"}
|
|
34
|
+
except TypeError:
|
|
35
|
+
return dict(kwargs)
|
|
36
|
+
|
|
37
|
+
if inspect.iscoroutinefunction(fn):
|
|
38
|
+
async def guarded_async(*args: Any, **kwargs: Any) -> Any:
|
|
39
|
+
v = await adecide(ep, name, arguments(args, kwargs), approve)
|
|
40
|
+
return await fn(*args, **kwargs) if v.allowed else v.message
|
|
41
|
+
|
|
42
|
+
return guarded_async
|
|
43
|
+
|
|
44
|
+
def guarded(*args: Any, **kwargs: Any) -> Any:
|
|
45
|
+
v = decide(ep, name, arguments(args, kwargs), approve)
|
|
46
|
+
return fn(*args, **kwargs) if v.allowed else v.message
|
|
47
|
+
|
|
48
|
+
return guarded
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _guard(tool: Any, ep: EnforcementPoint, approve: Optional[Approver]) -> Any:
|
|
52
|
+
# A tool made with @tool runs its function directly, so that is what is wrapped. A
|
|
53
|
+
# BaseTool subclass runs _run (and _arun, when it has its own). Exactly one of them
|
|
54
|
+
# is wrapped, so each call is decided once.
|
|
55
|
+
func = getattr(tool, "func", None)
|
|
56
|
+
if callable(func):
|
|
57
|
+
object.__setattr__(tool, "func", _wrap(func, tool.name, ep, approve))
|
|
58
|
+
return tool
|
|
59
|
+
object.__setattr__(tool, "_run", _wrap(tool._run, tool.name, ep, approve))
|
|
60
|
+
arun = getattr(type(tool), "_arun", None)
|
|
61
|
+
from crewai.tools import BaseTool
|
|
62
|
+
|
|
63
|
+
if arun is not None and arun is not getattr(BaseTool, "_arun", None):
|
|
64
|
+
object.__setattr__(tool, "_arun", _wrap(tool._arun, tool.name, ep, approve))
|
|
65
|
+
return tool
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def guard_tools(ep: EnforcementPoint, tools: List[Any], approve: Optional[Approver] = None) -> List[Any]:
|
|
69
|
+
"""The same tools, each checked against the envelope before it runs. Changes them in place."""
|
|
70
|
+
for t in tools:
|
|
71
|
+
if not hasattr(t, "_run") or not hasattr(t, "name"):
|
|
72
|
+
raise TypeError(f"{t!r} is not a CrewAI tool, so it cannot be guarded")
|
|
73
|
+
return [_guard(t, ep, approve) for t in tools]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""LangGraph: decide every call a ToolNode makes.
|
|
2
|
+
|
|
3
|
+
from langgraph.prebuilt import ToolNode
|
|
4
|
+
from intent_envelope.adapters.langgraph import guard_tool_node
|
|
5
|
+
|
|
6
|
+
node = ToolNode(tools, **guard_tool_node(ep))
|
|
7
|
+
|
|
8
|
+
Uses ToolNode's wrap_tool_call and awrap_tool_call, so it covers every tool the node
|
|
9
|
+
holds, sync or async, and sees the arguments the node is about to run the tool with. A
|
|
10
|
+
refused call comes back to the model as an error ToolMessage and the tool never runs.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any, Callable, Dict, Optional
|
|
16
|
+
|
|
17
|
+
from ..enforce import EnforcementPoint
|
|
18
|
+
from ._core import Approver, adecide, decide
|
|
19
|
+
|
|
20
|
+
__all__ = ["guard_tool_node"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _refused(call: Dict[str, Any], message: str) -> Any:
|
|
24
|
+
from langchain_core.messages import ToolMessage
|
|
25
|
+
|
|
26
|
+
return ToolMessage(content=message, tool_call_id=call.get("id") or "", name=call.get("name"), status="error")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def guard_tool_node(ep: EnforcementPoint, approve: Optional[Approver] = None) -> Dict[str, Callable]:
|
|
30
|
+
"""Keyword arguments for ToolNode: wrap_tool_call and awrap_tool_call."""
|
|
31
|
+
|
|
32
|
+
def wrap(request: Any, execute: Callable) -> Any:
|
|
33
|
+
call = request.tool_call
|
|
34
|
+
v = decide(ep, call["name"], call.get("args"), approve)
|
|
35
|
+
return execute(request) if v.allowed else _refused(call, v.message)
|
|
36
|
+
|
|
37
|
+
async def awrap(request: Any, execute: Callable) -> Any:
|
|
38
|
+
call = request.tool_call
|
|
39
|
+
v = await adecide(ep, call["name"], call.get("args"), approve)
|
|
40
|
+
return await execute(request) if v.allowed else _refused(call, v.message)
|
|
41
|
+
|
|
42
|
+
return {"wrap_tool_call": wrap, "awrap_tool_call": awrap}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""OpenAI Agents SDK: a tool input guardrail on every function tool.
|
|
2
|
+
|
|
3
|
+
from intent_envelope.adapters.openai_agents import guard_tools
|
|
4
|
+
|
|
5
|
+
agent = Agent(name="refunds", tools=guard_tools(ep, [issue_refund, lookup_order]))
|
|
6
|
+
|
|
7
|
+
Adds a tool input guardrail, which the SDK runs before the tool with the arguments the
|
|
8
|
+
model sent. A refused call is rejected with the reason as the tool's result, and the tool
|
|
9
|
+
never runs. Guardrails already on a tool are kept.
|
|
10
|
+
|
|
11
|
+
Hosted tools (web search, file search, code interpreter, computer use) run on OpenAI's
|
|
12
|
+
side, where nothing local can stop them, so they are refused here rather than passed
|
|
13
|
+
through unguarded. Leave them out of a guarded agent, or name them in tools.deny.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import dataclasses
|
|
19
|
+
import json
|
|
20
|
+
from typing import Any, List, Optional
|
|
21
|
+
|
|
22
|
+
from ..enforce import EnforcementPoint
|
|
23
|
+
from ._core import Approver, adecide
|
|
24
|
+
|
|
25
|
+
__all__ = ["guard_tools", "envelope_guardrail"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def envelope_guardrail(ep: EnforcementPoint, approve: Optional[Approver] = None) -> Any:
|
|
29
|
+
from agents import ToolGuardrailFunctionOutput, tool_input_guardrail
|
|
30
|
+
|
|
31
|
+
@tool_input_guardrail(name="intent_envelope")
|
|
32
|
+
async def check(data: Any) -> Any:
|
|
33
|
+
ctx = data.context
|
|
34
|
+
try:
|
|
35
|
+
arguments = json.loads(ctx.tool_arguments or "{}")
|
|
36
|
+
except ValueError:
|
|
37
|
+
return ToolGuardrailFunctionOutput.reject_content(
|
|
38
|
+
"Not run: the arguments are not JSON, so the intent envelope cannot check them.")
|
|
39
|
+
if not isinstance(arguments, dict):
|
|
40
|
+
arguments = {"input": arguments}
|
|
41
|
+
v = await adecide(ep, ctx.tool_name, arguments, approve)
|
|
42
|
+
if v.allowed:
|
|
43
|
+
return ToolGuardrailFunctionOutput.allow(output_info={"rule": v.decision.rule})
|
|
44
|
+
return ToolGuardrailFunctionOutput.reject_content(v.message, output_info=v.decision.record())
|
|
45
|
+
|
|
46
|
+
return check
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def guard_tools(ep: EnforcementPoint, tools: List[Any], approve: Optional[Approver] = None) -> List[Any]:
|
|
50
|
+
from agents import FunctionTool
|
|
51
|
+
|
|
52
|
+
guardrail = envelope_guardrail(ep, approve)
|
|
53
|
+
out = []
|
|
54
|
+
for t in tools:
|
|
55
|
+
if not isinstance(t, FunctionTool):
|
|
56
|
+
raise TypeError(
|
|
57
|
+
f"{getattr(t, 'name', t)!r} is not a function tool. Hosted tools run on OpenAI's side, "
|
|
58
|
+
"where the envelope cannot stop them, so a guarded agent cannot carry one")
|
|
59
|
+
out.append(dataclasses.replace(t, tool_input_guardrails=[*(t.tool_input_guardrails or []), guardrail]))
|
|
60
|
+
return out
|