intent-envelope 0.0.1__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/.gitignore +2 -0
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/PKG-INFO +6 -2
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/README.md +3 -0
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/pyproject.toml +6 -3
- intent_envelope-0.2.0/src/intent_envelope/__init__.py +47 -0
- intent_envelope-0.2.0/src/intent_envelope/enforce.py +210 -0
- intent_envelope-0.2.0/src/intent_envelope/evaluate.py +329 -0
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/src/intent_envelope/validate.py +8 -3
- intent_envelope-0.2.0/tests/test_decisions.py +93 -0
- intent_envelope-0.2.0/tests/test_enforcement.py +166 -0
- intent_envelope-0.2.0/tests/test_expires_format.py +80 -0
- intent_envelope-0.2.0/tests/test_packaging.py +87 -0
- intent_envelope-0.2.0/tools/consumer_smoke.py +170 -0
- intent_envelope-0.0.1/src/intent_envelope/__init__.py +0 -13
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/src/intent_envelope/cli.py +0 -0
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/src/intent_envelope/schema/intent-envelope-0.1.json +0 -0
- {intent_envelope-0.0.1 → intent_envelope-0.2.0}/tests/test_conformance.py +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: intent-envelope
|
|
3
|
-
Version: 0.0
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 0.2.0
|
|
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
|
|
7
7
|
Project-URL: Repository, https://github.com/secured-ai/intent-envelope
|
|
@@ -14,10 +14,14 @@ Classifier: Programming Language :: Python :: 3
|
|
|
14
14
|
Classifier: Topic :: Security
|
|
15
15
|
Requires-Python: >=3.9
|
|
16
16
|
Requires-Dist: jsonschema>=4.18
|
|
17
|
+
Requires-Dist: rfc3339-validator>=0.1.4
|
|
17
18
|
Description-Content-Type: text/markdown
|
|
18
19
|
|
|
19
20
|
# Intent Envelope
|
|
20
21
|
|
|
22
|
+
[](https://scorecard.dev/viewer/?uri=github.com/secured-ai/intent-envelope)
|
|
23
|
+
[](https://github.com/secured-ai/intent-envelope/actions/workflows/ci.yml)
|
|
24
|
+
|
|
21
25
|
**Your agent was not hacked. It was told what to do, just not by you.**
|
|
22
26
|
|
|
23
27
|
An agent reads documents, tickets, web pages and tool output. Any of them can contain
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# Intent Envelope
|
|
2
2
|
|
|
3
|
+
[](https://scorecard.dev/viewer/?uri=github.com/secured-ai/intent-envelope)
|
|
4
|
+
[](https://github.com/secured-ai/intent-envelope/actions/workflows/ci.yml)
|
|
5
|
+
|
|
3
6
|
**Your agent was not hacked. It was told what to do, just not by you.**
|
|
4
7
|
|
|
5
8
|
An agent reads documents, tickets, web pages and tool output. Any of them can contain
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "intent-envelope"
|
|
7
|
-
version = "0.0
|
|
8
|
-
description = "
|
|
7
|
+
version = "0.2.0"
|
|
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"
|
|
11
11
|
license = "Apache-2.0"
|
|
@@ -17,7 +17,10 @@ classifiers = [
|
|
|
17
17
|
"Topic :: Security",
|
|
18
18
|
"Programming Language :: Python :: 3",
|
|
19
19
|
]
|
|
20
|
-
|
|
20
|
+
# jsonschema only enforces "format" when a checker is installed for that format.
|
|
21
|
+
# Without rfc3339-validator, FormatChecker silently skips date-time and expires
|
|
22
|
+
# accepts any string, so this pin is load bearing rather than cosmetic.
|
|
23
|
+
dependencies = ["jsonschema>=4.18", "rfc3339-validator>=0.1.4"]
|
|
21
24
|
|
|
22
25
|
[project.scripts]
|
|
23
26
|
intent-envelope = "intent_envelope.cli:main"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Declared intent envelopes for AI agents.
|
|
2
|
+
|
|
3
|
+
An envelope states what an agent is for: the tools it may call, the data it may
|
|
4
|
+
touch, who it may contact, what it may spend, and which actions need a human.
|
|
5
|
+
It is written before the agent runs and checked in code at every tool call.
|
|
6
|
+
|
|
7
|
+
Two halves. `validate` answers whether an envelope is well formed. `evaluate` and
|
|
8
|
+
`EnforcementPoint` answer the question that matters at runtime: given this envelope,
|
|
9
|
+
may this call happen, and on whose authority was that decided.
|
|
10
|
+
|
|
11
|
+
Specification: https://securedai.org/agent-intent
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .enforce import EnforcementPoint, Escalated, Refused, ToolFacts, default_facts
|
|
15
|
+
from .evaluate import (
|
|
16
|
+
Call,
|
|
17
|
+
Decision,
|
|
18
|
+
RunState,
|
|
19
|
+
UnsupportedCondition,
|
|
20
|
+
default_condition_matcher,
|
|
21
|
+
default_data_matcher,
|
|
22
|
+
evaluate,
|
|
23
|
+
)
|
|
24
|
+
from .validate import ValidationError, load_schema, validate
|
|
25
|
+
|
|
26
|
+
__version__ = "0.2.0"
|
|
27
|
+
__all__ = [
|
|
28
|
+
# envelopes
|
|
29
|
+
"validate",
|
|
30
|
+
"load_schema",
|
|
31
|
+
"ValidationError",
|
|
32
|
+
# decisions
|
|
33
|
+
"evaluate",
|
|
34
|
+
"Call",
|
|
35
|
+
"RunState",
|
|
36
|
+
"Decision",
|
|
37
|
+
"UnsupportedCondition",
|
|
38
|
+
"default_data_matcher",
|
|
39
|
+
"default_condition_matcher",
|
|
40
|
+
# enforcement
|
|
41
|
+
"EnforcementPoint",
|
|
42
|
+
"ToolFacts",
|
|
43
|
+
"default_facts",
|
|
44
|
+
"Refused",
|
|
45
|
+
"Escalated",
|
|
46
|
+
"__version__",
|
|
47
|
+
]
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""The enforcement point: an envelope, the run so far, and a wrapper for a tool call.
|
|
2
|
+
|
|
3
|
+
`evaluate` decides one call in isolation. Something has to hold the run together, or
|
|
4
|
+
limits mean nothing: `max_tool_calls` is only a limit if somebody counts, and the agent
|
|
5
|
+
counting its own calls is the arrangement this whole specification exists to replace.
|
|
6
|
+
|
|
7
|
+
`EnforcementPoint` keeps that count outside the agent and refuses on its own authority.
|
|
8
|
+
`guard` wraps an existing tool-call function, so a deployment adds enforcement without
|
|
9
|
+
restructuring its agent. MCP first, because one integration covers every tool a server
|
|
10
|
+
exposes, which is the cheapest reach available.
|
|
11
|
+
|
|
12
|
+
Nothing here can be switched off by the thing it governs. There is no argument an agent
|
|
13
|
+
can pass that widens the envelope, and no exception path that trusts the caller's
|
|
14
|
+
explanation of why this call should be different.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import inspect
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
22
|
+
|
|
23
|
+
from .evaluate import (
|
|
24
|
+
ALLOW,
|
|
25
|
+
DENY,
|
|
26
|
+
ESCALATE,
|
|
27
|
+
Call,
|
|
28
|
+
Decision,
|
|
29
|
+
RunState,
|
|
30
|
+
default_condition_matcher,
|
|
31
|
+
default_data_matcher,
|
|
32
|
+
evaluate,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = ["EnforcementPoint", "ToolFacts", "default_facts", "Refused", "Escalated"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Refused(PermissionError):
|
|
39
|
+
"""Raised when a guarded tool call is denied. Carries the decision and its record."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, decision: Decision):
|
|
42
|
+
self.decision = decision
|
|
43
|
+
super().__init__(f"{decision.rule}: {decision.detail}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Escalated(PermissionError):
|
|
47
|
+
"""Raised when a guarded call needs a named human before it can run.
|
|
48
|
+
|
|
49
|
+
Separate from Refused on purpose. A deployment that treats them alike has collapsed
|
|
50
|
+
"a person must decide this" into "no", which loses the entire point of having an
|
|
51
|
+
escalation path. What waits for the human, and what happens when nobody answers, is
|
|
52
|
+
the deployment's to build: `on_no_response` in the envelope says which way it falls.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self, decision: Decision):
|
|
56
|
+
self.decision = decision
|
|
57
|
+
super().__init__(f"needs {decision.escalate_to}: {decision.detail}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class ToolFacts:
|
|
62
|
+
"""What a call touches, in the terms the envelope is written in.
|
|
63
|
+
|
|
64
|
+
MCP carries a tool name and arguments and nothing else, so somebody has to say which
|
|
65
|
+
argument is a recipient and which is a data target. That mapping is deployment
|
|
66
|
+
knowledge, not protocol.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
data: List[str] = field(default_factory=list)
|
|
70
|
+
recipients: List[str] = field(default_factory=list)
|
|
71
|
+
estimated_cost_usd: float = 0.0
|
|
72
|
+
context: Dict[str, Any] = field(default_factory=dict)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# Conventional argument names, listed rather than guessed at from the shape of values.
|
|
76
|
+
_RECIPIENT_KEYS = ("to", "recipient", "recipients", "to_address", "email", "send_to", "channel")
|
|
77
|
+
_DATA_KEYS = ("data", "dataset", "collection", "collections", "resource", "resources", "scope")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def default_facts(tool: str, arguments: Dict[str, Any]) -> ToolFacts:
|
|
81
|
+
"""Read conventional argument names. Documented, small, and easy to outgrow.
|
|
82
|
+
|
|
83
|
+
A deployment whose tools name things differently passes its own `facts=`. The
|
|
84
|
+
failure mode worth knowing: a recipient this does not recognise is a recipient the
|
|
85
|
+
envelope never checks, so a tool that can send should have its extractor written
|
|
86
|
+
rather than inherited.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def collect(keys: tuple) -> List[str]:
|
|
90
|
+
found: List[str] = []
|
|
91
|
+
for key in keys:
|
|
92
|
+
value = arguments.get(key)
|
|
93
|
+
if isinstance(value, str):
|
|
94
|
+
found.append(value)
|
|
95
|
+
elif isinstance(value, (list, tuple)):
|
|
96
|
+
found.extend(str(v) for v in value)
|
|
97
|
+
return found
|
|
98
|
+
|
|
99
|
+
return ToolFacts(
|
|
100
|
+
data=collect(_DATA_KEYS),
|
|
101
|
+
recipients=collect(_RECIPIENT_KEYS),
|
|
102
|
+
context={k: v for k, v in arguments.items() if isinstance(v, (int, float, bool, str))},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class EnforcementPoint:
|
|
107
|
+
"""Holds one envelope and one run, and decides every call in it."""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
envelope: Dict[str, Any],
|
|
112
|
+
*,
|
|
113
|
+
facts: Callable[[str, Dict[str, Any]], ToolFacts] = default_facts,
|
|
114
|
+
on_decision: Optional[Callable[[Decision], None]] = None,
|
|
115
|
+
data_matcher: Callable[[str, str], bool] = default_data_matcher,
|
|
116
|
+
condition_matcher: Callable[[str, Dict[str, Any]], bool] = default_condition_matcher,
|
|
117
|
+
now: Optional[Callable[[], str]] = None,
|
|
118
|
+
):
|
|
119
|
+
self.envelope = envelope
|
|
120
|
+
self.facts = facts
|
|
121
|
+
self.on_decision = on_decision
|
|
122
|
+
self.data_matcher = data_matcher
|
|
123
|
+
self.condition_matcher = condition_matcher
|
|
124
|
+
self._now = now
|
|
125
|
+
self.state = RunState()
|
|
126
|
+
self.decisions: List[Decision] = []
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------- deciding
|
|
129
|
+
|
|
130
|
+
def check(self, tool: str, arguments: Optional[Dict[str, Any]] = None, **overrides: Any) -> Decision:
|
|
131
|
+
"""Decide a call without running it. Records the decision either way."""
|
|
132
|
+
arguments = arguments or {}
|
|
133
|
+
found = self.facts(tool, arguments)
|
|
134
|
+
call = Call(
|
|
135
|
+
tool=tool,
|
|
136
|
+
arguments=arguments,
|
|
137
|
+
data=overrides.get("data", found.data),
|
|
138
|
+
recipients=overrides.get("recipients", found.recipients),
|
|
139
|
+
estimated_cost_usd=overrides.get("estimated_cost_usd", found.estimated_cost_usd),
|
|
140
|
+
context={**found.context, **overrides.get("context", {})},
|
|
141
|
+
)
|
|
142
|
+
if self._now:
|
|
143
|
+
self.state.now = self._now()
|
|
144
|
+
|
|
145
|
+
decision = evaluate(
|
|
146
|
+
self.envelope, call, self.state,
|
|
147
|
+
data_matcher=self.data_matcher, condition_matcher=self.condition_matcher,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# Every outcome is recorded, refused as well as allowed. A ledger that holds only
|
|
151
|
+
# what succeeded cannot answer the question an incident actually asks.
|
|
152
|
+
self.decisions.append(decision)
|
|
153
|
+
if self.on_decision:
|
|
154
|
+
self.on_decision(decision)
|
|
155
|
+
|
|
156
|
+
# Only a call that is going to happen spends the run's budget. Counting refused
|
|
157
|
+
# calls against the limit would let a blocked agent exhaust its own allowance.
|
|
158
|
+
if decision.result == ALLOW:
|
|
159
|
+
self.state.tool_calls_made += 1
|
|
160
|
+
self.state.spend_usd += call.estimated_cost_usd
|
|
161
|
+
self.state.recipients_contacted += len(call.recipients)
|
|
162
|
+
return decision
|
|
163
|
+
|
|
164
|
+
def enforce(self, tool: str, arguments: Optional[Dict[str, Any]] = None, **overrides: Any) -> Decision:
|
|
165
|
+
"""Decide, and raise unless the answer is allow."""
|
|
166
|
+
decision = self.check(tool, arguments, **overrides)
|
|
167
|
+
if decision.result == DENY:
|
|
168
|
+
raise Refused(decision)
|
|
169
|
+
if decision.result == ESCALATE:
|
|
170
|
+
raise Escalated(decision)
|
|
171
|
+
return decision
|
|
172
|
+
|
|
173
|
+
# ---------------------------------------------------------------- wrapping
|
|
174
|
+
|
|
175
|
+
def guard(self, call_tool: Callable) -> Callable:
|
|
176
|
+
"""Wrap a tool-call function so every call through it is checked first.
|
|
177
|
+
|
|
178
|
+
Works with an MCP client's `call_tool(name, arguments)` as it stands, sync or
|
|
179
|
+
async. The check happens before the call, because a decision made afterwards is
|
|
180
|
+
a report rather than a control.
|
|
181
|
+
"""
|
|
182
|
+
if inspect.iscoroutinefunction(call_tool):
|
|
183
|
+
|
|
184
|
+
async def guarded_async(name: str, arguments: Optional[Dict[str, Any]] = None, *args: Any, **kwargs: Any):
|
|
185
|
+
self.enforce(name, arguments or {})
|
|
186
|
+
return await call_tool(name, arguments or {}, *args, **kwargs)
|
|
187
|
+
|
|
188
|
+
guarded_async.__name__ = getattr(call_tool, "__name__", "call_tool")
|
|
189
|
+
guarded_async.enforcement_point = self # type: ignore[attr-defined]
|
|
190
|
+
return guarded_async
|
|
191
|
+
|
|
192
|
+
def guarded(name: str, arguments: Optional[Dict[str, Any]] = None, *args: Any, **kwargs: Any):
|
|
193
|
+
self.enforce(name, arguments or {})
|
|
194
|
+
return call_tool(name, arguments or {}, *args, **kwargs)
|
|
195
|
+
|
|
196
|
+
guarded.__name__ = getattr(call_tool, "__name__", "call_tool")
|
|
197
|
+
guarded.enforcement_point = self # type: ignore[attr-defined]
|
|
198
|
+
return guarded
|
|
199
|
+
|
|
200
|
+
# ---------------------------------------------------------------- the ledger
|
|
201
|
+
|
|
202
|
+
def ledger(self) -> List[Dict[str, Any]]:
|
|
203
|
+
"""Every decision this run made, in order, as section 5 records."""
|
|
204
|
+
return [d.record() for d in self.decisions]
|
|
205
|
+
|
|
206
|
+
def summary(self) -> Dict[str, int]:
|
|
207
|
+
counts = {ALLOW: 0, DENY: 0, ESCALATE: 0}
|
|
208
|
+
for d in self.decisions:
|
|
209
|
+
counts[d.result] += 1
|
|
210
|
+
return counts
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Decide one proposed tool call against an envelope.
|
|
2
|
+
|
|
3
|
+
This is specification section 3, in its order, and the order is the design rather than
|
|
4
|
+
an implementation detail. Deny is settled before escalate so a forbidden action is never
|
|
5
|
+
put in front of a person as something they could approve.
|
|
6
|
+
|
|
7
|
+
Two rules depend on things version 0.1 leaves deployment-defined: how `data` targets are
|
|
8
|
+
addressed, and the expression syntax in `escalate.when`. Both are injectable. The
|
|
9
|
+
defaults here are documented and deliberately small, because a matcher that quietly
|
|
10
|
+
guesses is worse than one that refuses.
|
|
11
|
+
|
|
12
|
+
Nothing in this module consults the model, the prompt, or the agent's stated reason for
|
|
13
|
+
the call. It reads the envelope, the call, and the run so far.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Call",
|
|
25
|
+
"RunState",
|
|
26
|
+
"Decision",
|
|
27
|
+
"evaluate",
|
|
28
|
+
"UnsupportedCondition",
|
|
29
|
+
"default_data_matcher",
|
|
30
|
+
"default_condition_matcher",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
ALLOW, DENY, ESCALATE = "allow", "deny", "escalate"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class UnsupportedCondition(ValueError):
|
|
37
|
+
"""Raised when the default matcher cannot parse an `escalate.when` expression.
|
|
38
|
+
|
|
39
|
+
Refusing is the point. Returning False for an expression nobody understood would
|
|
40
|
+
silently turn an action that should have paused for a human into one that ran.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Call:
|
|
46
|
+
"""One proposed tool call, as the enforcement point sees it.
|
|
47
|
+
|
|
48
|
+
`context` carries the operands an `escalate.when` expression refers to, and anything
|
|
49
|
+
a deployment's own matchers need. It is evidence about the call, never instructions:
|
|
50
|
+
nothing in it can widen the envelope.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
tool: str
|
|
54
|
+
arguments: Dict[str, Any] = field(default_factory=dict)
|
|
55
|
+
data: List[str] = field(default_factory=list)
|
|
56
|
+
recipients: List[str] = field(default_factory=list)
|
|
57
|
+
estimated_cost_usd: float = 0.0
|
|
58
|
+
context: Dict[str, Any] = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class RunState:
|
|
63
|
+
"""What this run has already spent. Limits are arithmetic over this, not judgement."""
|
|
64
|
+
|
|
65
|
+
now: str = ""
|
|
66
|
+
tool_calls_made: int = 0
|
|
67
|
+
records_returned: int = 0
|
|
68
|
+
spend_usd: float = 0.0
|
|
69
|
+
runtime_seconds: int = 0
|
|
70
|
+
recipients_contacted: int = 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Decision:
|
|
75
|
+
result: str
|
|
76
|
+
rule: str
|
|
77
|
+
detail: str
|
|
78
|
+
envelope: Dict[str, Any]
|
|
79
|
+
call: Call
|
|
80
|
+
decided_at: str
|
|
81
|
+
escalate_to: Optional[str] = None
|
|
82
|
+
timeout_seconds: Optional[int] = None
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def allowed(self) -> bool:
|
|
86
|
+
return self.result == ALLOW
|
|
87
|
+
|
|
88
|
+
def record(self) -> Dict[str, Any]:
|
|
89
|
+
"""The record specification section 5 asks for.
|
|
90
|
+
|
|
91
|
+
Written here, where the decision is made, because this is the only place that
|
|
92
|
+
holds the envelope, the identity, the call and the verdict at the same time.
|
|
93
|
+
Assembling it from logs afterwards means reconstructing a decision from its
|
|
94
|
+
side effects.
|
|
95
|
+
"""
|
|
96
|
+
principal = self.envelope.get("principal") or {}
|
|
97
|
+
return {
|
|
98
|
+
"envelope_id": self.envelope.get("id"),
|
|
99
|
+
"revision": self.envelope.get("revision"),
|
|
100
|
+
"agent_identity": principal.get("agent_identity"),
|
|
101
|
+
"principal": principal.get("on_behalf_of"),
|
|
102
|
+
"tool": self.call.tool,
|
|
103
|
+
"target": self.call.recipients or self.call.data or None,
|
|
104
|
+
"result": self.result,
|
|
105
|
+
"rule": self.rule,
|
|
106
|
+
"detail": self.detail,
|
|
107
|
+
"cost_usd": self.call.estimated_cost_usd,
|
|
108
|
+
"escalated_to": self.escalate_to,
|
|
109
|
+
"decided_at": self.decided_at,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# --------------------------------------------------------------------- matchers
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def default_data_matcher(target: str, pattern: str) -> bool:
|
|
117
|
+
"""Exact match, or the pattern naming a prefix segment of the target.
|
|
118
|
+
|
|
119
|
+
`ledger:read` matches `ledger:read:current_month`. `ledger` matches both. Version
|
|
120
|
+
0.1 leaves addressing to the deployment, so anything richer belongs in a matcher the
|
|
121
|
+
deployment supplies.
|
|
122
|
+
"""
|
|
123
|
+
if target == pattern:
|
|
124
|
+
return True
|
|
125
|
+
return target.startswith(pattern + ":") or target.startswith(pattern + ".")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_COMPARISON = re.compile(
|
|
129
|
+
r"^\s*(?P<key>[A-Za-z_][\w.]*)\s*(?P<op>==|!=|>=|<=|>|<)\s*(?P<value>'[^']*'|\"[^\"]*\"|-?\d+(?:\.\d+)?)\s*$"
|
|
130
|
+
)
|
|
131
|
+
_BARE = re.compile(r"^\s*(?P<key>[A-Za-z_][\w.]*)\s*$")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def default_condition_matcher(condition: str, context: Dict[str, Any]) -> bool:
|
|
135
|
+
"""A deliberately small subset: `key`, or `key <op> number|'string'`.
|
|
136
|
+
|
|
137
|
+
An operand the context does not carry is not a match, because the deployment did not
|
|
138
|
+
report the thing the condition asks about. An expression this cannot parse raises,
|
|
139
|
+
because guessing at an escalation rule is how an action that should have paused runs
|
|
140
|
+
instead.
|
|
141
|
+
"""
|
|
142
|
+
bare = _BARE.match(condition)
|
|
143
|
+
if bare:
|
|
144
|
+
return bool(context.get(bare.group("key")))
|
|
145
|
+
|
|
146
|
+
m = _COMPARISON.match(condition)
|
|
147
|
+
if not m:
|
|
148
|
+
raise UnsupportedCondition(
|
|
149
|
+
f"cannot parse escalate.when {condition!r}. Version 0.1 defines no expression "
|
|
150
|
+
f"syntax, so supply condition_matcher= for this deployment's own."
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
key, op, raw = m.group("key"), m.group("op"), m.group("value")
|
|
154
|
+
if key not in context:
|
|
155
|
+
return False
|
|
156
|
+
actual = context[key]
|
|
157
|
+
expected: Any = raw[1:-1] if raw[0] in "'\"" else float(raw)
|
|
158
|
+
|
|
159
|
+
if op == "==":
|
|
160
|
+
return actual == expected or str(actual) == str(expected)
|
|
161
|
+
if op == "!=":
|
|
162
|
+
return not (actual == expected or str(actual) == str(expected))
|
|
163
|
+
try:
|
|
164
|
+
actual_number = float(actual)
|
|
165
|
+
except (TypeError, ValueError):
|
|
166
|
+
return False
|
|
167
|
+
return {
|
|
168
|
+
">": actual_number > expected,
|
|
169
|
+
"<": actual_number < expected,
|
|
170
|
+
">=": actual_number >= expected,
|
|
171
|
+
"<=": actual_number <= expected,
|
|
172
|
+
}[op]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# --------------------------------------------------------------------- helpers
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _parse_instant(value: str) -> Optional[datetime]:
|
|
179
|
+
try:
|
|
180
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00").replace("z", "+00:00"))
|
|
181
|
+
except (ValueError, AttributeError):
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _grant_for(envelope: Dict[str, Any], tool: str) -> Optional[Dict[str, Any]]:
|
|
186
|
+
for grant in (envelope.get("tools") or {}).get("allow") or []:
|
|
187
|
+
if grant.get("name") == tool:
|
|
188
|
+
return grant
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _constraint_violation(grant: Dict[str, Any], arguments: Dict[str, Any]) -> Optional[str]:
|
|
193
|
+
"""Default constraint semantics, documented rather than inferred.
|
|
194
|
+
|
|
195
|
+
`max_*` bounds above, `min_*` bounds below, anything else must equal exactly. An
|
|
196
|
+
argument the call omits is unbounded for max/min and a violation for an equality
|
|
197
|
+
constraint, because an omitted pin is how a constraint gets sidestepped.
|
|
198
|
+
"""
|
|
199
|
+
for key, expected in (grant.get("constraints") or {}).items():
|
|
200
|
+
actual = arguments.get(key)
|
|
201
|
+
if key.startswith("max_"):
|
|
202
|
+
if actual is not None and _as_number(actual) is not None and _as_number(actual) > _as_number(expected):
|
|
203
|
+
return f"{key} is {actual}, above the permitted {expected}"
|
|
204
|
+
elif key.startswith("min_"):
|
|
205
|
+
if actual is not None and _as_number(actual) is not None and _as_number(actual) < _as_number(expected):
|
|
206
|
+
return f"{key} is {actual}, below the permitted {expected}"
|
|
207
|
+
elif actual is None:
|
|
208
|
+
return f"{key} is pinned to {expected!r} and the call did not supply it"
|
|
209
|
+
elif actual != expected:
|
|
210
|
+
return f"{key} is {actual!r}, not the pinned {expected!r}"
|
|
211
|
+
return None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _as_number(value: Any) -> Optional[float]:
|
|
215
|
+
try:
|
|
216
|
+
return float(value)
|
|
217
|
+
except (TypeError, ValueError):
|
|
218
|
+
return None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _limit_exceeded(limits: Dict[str, Any], call: Call, state: RunState) -> Optional[str]:
|
|
222
|
+
max_calls = limits.get("max_tool_calls")
|
|
223
|
+
if max_calls is not None and state.tool_calls_made + 1 > max_calls:
|
|
224
|
+
return f"this is call {state.tool_calls_made + 1} of a permitted {max_calls}"
|
|
225
|
+
|
|
226
|
+
max_spend = limits.get("max_spend_usd")
|
|
227
|
+
if max_spend is not None and state.spend_usd + call.estimated_cost_usd > max_spend:
|
|
228
|
+
total = state.spend_usd + call.estimated_cost_usd
|
|
229
|
+
return f"this call would take spend to {total:.2f} of a permitted {max_spend:.2f}"
|
|
230
|
+
|
|
231
|
+
max_records = limits.get("max_records")
|
|
232
|
+
if max_records is not None and state.records_returned >= max_records:
|
|
233
|
+
return f"{state.records_returned} records returned, of a permitted {max_records}"
|
|
234
|
+
|
|
235
|
+
max_runtime = limits.get("max_runtime_seconds")
|
|
236
|
+
if max_runtime is not None and state.runtime_seconds > max_runtime:
|
|
237
|
+
return f"the run has lasted {state.runtime_seconds}s, of a permitted {max_runtime}"
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# --------------------------------------------------------------------- the decision
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def evaluate(
|
|
245
|
+
envelope: Dict[str, Any],
|
|
246
|
+
call: Call,
|
|
247
|
+
state: Optional[RunState] = None,
|
|
248
|
+
*,
|
|
249
|
+
data_matcher: Callable[[str, str], bool] = default_data_matcher,
|
|
250
|
+
condition_matcher: Callable[[str, Dict[str, Any]], bool] = default_condition_matcher,
|
|
251
|
+
) -> Decision:
|
|
252
|
+
"""Return exactly one of allow, deny or escalate, and the rule that decided it."""
|
|
253
|
+
state = state or RunState()
|
|
254
|
+
decided_at = state.now or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
255
|
+
|
|
256
|
+
def verdict(result: str, rule: str, detail: str, **extra: Any) -> Decision:
|
|
257
|
+
return Decision(
|
|
258
|
+
result=result, rule=rule, detail=detail, envelope=envelope,
|
|
259
|
+
call=call, decided_at=decided_at, **extra,
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
tools = envelope.get("tools") or {}
|
|
263
|
+
|
|
264
|
+
# 1. An envelope past its expiry denies everything. The check belongs here, at the
|
|
265
|
+
# moment of the call, not at the moment the envelope was issued.
|
|
266
|
+
expires = envelope.get("expires")
|
|
267
|
+
if expires:
|
|
268
|
+
deadline, now = _parse_instant(expires), _parse_instant(state.now) if state.now else datetime.now(timezone.utc)
|
|
269
|
+
if deadline is None:
|
|
270
|
+
return verdict(DENY, "expires", f"expires is {expires!r}, which is not an instant this can compare")
|
|
271
|
+
if now is not None and now >= deadline:
|
|
272
|
+
return verdict(DENY, "expires", f"the envelope expired at {expires}")
|
|
273
|
+
|
|
274
|
+
# 2. Deny always wins, before anything consults the allow list.
|
|
275
|
+
if call.tool in (tools.get("deny") or []):
|
|
276
|
+
return verdict(DENY, "tools.deny", f"{call.tool} is on tools.deny, which no later grant overrides")
|
|
277
|
+
|
|
278
|
+
# 3. Silence is not permission.
|
|
279
|
+
grant = _grant_for(envelope, call.tool)
|
|
280
|
+
if grant is None:
|
|
281
|
+
return verdict(DENY, "tools.allow", f"{call.tool} is not on tools.allow")
|
|
282
|
+
|
|
283
|
+
# 4. The tool is granted. The arguments still have to be the ones that were granted.
|
|
284
|
+
violation = _constraint_violation(grant, call.arguments)
|
|
285
|
+
if violation:
|
|
286
|
+
return verdict(DENY, "tools.constraints", violation)
|
|
287
|
+
|
|
288
|
+
# 5. Data. An absent data block is unconstrained here, unlike recipients, because
|
|
289
|
+
# 0.1 states the default for recipients and not for this one.
|
|
290
|
+
data_rules = envelope.get("data")
|
|
291
|
+
if data_rules is not None:
|
|
292
|
+
for target in call.data:
|
|
293
|
+
for pattern in data_rules.get("deny") or []:
|
|
294
|
+
if data_matcher(target, pattern):
|
|
295
|
+
return verdict(DENY, "data", f"{target} matches data.deny entry {pattern}")
|
|
296
|
+
allowed = data_rules.get("allow")
|
|
297
|
+
if allowed is not None and not any(data_matcher(target, p) for p in allowed):
|
|
298
|
+
return verdict(DENY, "data", f"{target} is not within data.allow")
|
|
299
|
+
|
|
300
|
+
# 6. Recipients. An absent block means nobody, which the specification states.
|
|
301
|
+
recipients_rules = envelope.get("recipients")
|
|
302
|
+
if call.recipients:
|
|
303
|
+
if recipients_rules is None:
|
|
304
|
+
return verdict(DENY, "recipients", "the envelope names no recipients, which permits contacting nobody")
|
|
305
|
+
permitted: Sequence[str] = recipients_rules.get("allow") or []
|
|
306
|
+
for who in call.recipients:
|
|
307
|
+
if not any(who == p or who.endswith(p) for p in permitted):
|
|
308
|
+
return verdict(DENY, "recipients", f"{who} is not on recipients.allow")
|
|
309
|
+
max_per_run = recipients_rules.get("max_per_run")
|
|
310
|
+
if max_per_run is not None and state.recipients_contacted + len(call.recipients) > max_per_run:
|
|
311
|
+
total = state.recipients_contacted + len(call.recipients)
|
|
312
|
+
return verdict(DENY, "recipients", f"this call would contact {total} of a permitted {max_per_run}")
|
|
313
|
+
|
|
314
|
+
# 7. Budgets are arithmetic, which is why they hold when judgement does not.
|
|
315
|
+
exceeded = _limit_exceeded(envelope.get("limits") or {}, call, state)
|
|
316
|
+
if exceeded:
|
|
317
|
+
return verdict(DENY, "limits", exceeded)
|
|
318
|
+
|
|
319
|
+
# 8. Only now, with the call established as permitted, may a human be asked.
|
|
320
|
+
for rule in envelope.get("escalate") or []:
|
|
321
|
+
when = rule.get("when")
|
|
322
|
+
if when and condition_matcher(when, call.context):
|
|
323
|
+
return verdict(
|
|
324
|
+
ESCALATE, "escalate", f"{when} matched",
|
|
325
|
+
escalate_to=rule.get("to"), timeout_seconds=rule.get("timeout_seconds"),
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
# 9. Nothing fired.
|
|
329
|
+
return verdict(ALLOW, "allow", "inside the envelope")
|
|
@@ -38,9 +38,14 @@ def _where(error: Any) -> str:
|
|
|
38
38
|
|
|
39
39
|
def validate(envelope: Dict[str, Any]) -> None:
|
|
40
40
|
"""Validate an envelope. Returns None, raises ValidationError with every problem found."""
|
|
41
|
-
from jsonschema import Draft202012Validator
|
|
42
|
-
|
|
43
|
-
|
|
41
|
+
from jsonschema import Draft202012Validator, FormatChecker
|
|
42
|
+
|
|
43
|
+
# JSON Schema treats "format" as an annotation unless a checker is supplied, so
|
|
44
|
+
# without this the validator accepts expires: "NOT A DATE". That is not a harmless
|
|
45
|
+
# laxness here: section 3 denies every call under an expired envelope, which means an
|
|
46
|
+
# enforcement point has to parse the value. A string that passes validation and then
|
|
47
|
+
# fails to parse turns a deliberate expiry into undefined behaviour at the gate.
|
|
48
|
+
validator = Draft202012Validator(load_schema(), format_checker=FormatChecker())
|
|
44
49
|
errors = sorted(validator.iter_errors(envelope), key=lambda e: list(e.absolute_path))
|
|
45
50
|
if errors:
|
|
46
51
|
raise ValidationError([f"{_where(e)}: {e.message}" for e in errors])
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Every case in conformance/decisions must get the right result for the right reason.
|
|
2
|
+
|
|
3
|
+
These were written before the evaluator, from specification section 3 and from the
|
|
4
|
+
attack patterns in the incident library. The behaviour is pinned by the specification
|
|
5
|
+
and by this suite, not by whatever the first implementation happens to do.
|
|
6
|
+
|
|
7
|
+
The cases are language-neutral JSON. The TypeScript port runs the same files.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
|
|
17
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
18
|
+
CASES = sorted((ROOT / "conformance" / "decisions").glob("*.json"))
|
|
19
|
+
|
|
20
|
+
from intent_envelope.evaluate import Call, RunState, evaluate
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_case(path: Path) -> dict:
|
|
24
|
+
case = json.loads(path.read_text(encoding="utf-8"))
|
|
25
|
+
if "envelope_ref" in case:
|
|
26
|
+
case["envelope"] = json.loads((path.parent / case["envelope_ref"]).read_text(encoding="utf-8"))
|
|
27
|
+
return case
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_cases_exist():
|
|
31
|
+
assert CASES, "no decision cases found in conformance/decisions"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_every_case_is_well_formed():
|
|
35
|
+
"""A malformed case would silently pass or silently never run."""
|
|
36
|
+
results = {"allow", "deny", "escalate"}
|
|
37
|
+
for path in CASES:
|
|
38
|
+
case = load_case(path)
|
|
39
|
+
for field in ("name", "spec_rule", "decided_by", "call", "state", "expect"):
|
|
40
|
+
assert field in case, f"{path.name} has no {field}"
|
|
41
|
+
assert case["expect"]["result"] in results, f"{path.name} expects an unknown result"
|
|
42
|
+
assert case["expect"]["rule"] == case["decided_by"], (
|
|
43
|
+
f"{path.name}: expect.rule and decided_by disagree, so the case cannot check "
|
|
44
|
+
f"that the right rule decided it"
|
|
45
|
+
)
|
|
46
|
+
assert "tool" in case["call"], f"{path.name} proposes no tool"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_the_suite_covers_every_step_of_section_3():
|
|
50
|
+
"""Section 3 has nine steps. A suite that skips one lets an implementation skip it."""
|
|
51
|
+
covered = {load_case(p)["spec_rule"] for p in CASES}
|
|
52
|
+
missing = set(range(1, 10)) - covered
|
|
53
|
+
assert not missing, f"no decision case covers section 3 step(s): {sorted(missing)}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@pytest.mark.parametrize("path", CASES, ids=lambda p: p.stem)
|
|
57
|
+
def test_decision(path: Path):
|
|
58
|
+
case = load_case(path)
|
|
59
|
+
decision = evaluate(
|
|
60
|
+
envelope=case["envelope"],
|
|
61
|
+
call=Call(**case["call"]),
|
|
62
|
+
state=RunState(**case["state"]),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
expected = case["expect"]
|
|
66
|
+
assert decision.result == expected["result"], (
|
|
67
|
+
f"{case['name']}: expected {expected['result']}, got {decision.result}"
|
|
68
|
+
)
|
|
69
|
+
# The reason is not decoration. Section 5 requires the record to name the rule that
|
|
70
|
+
# decided, and an operator reading the ledger acts on that field.
|
|
71
|
+
assert decision.rule == expected["rule"], (
|
|
72
|
+
f"{case['name']}: right answer, wrong reason. Expected rule {expected['rule']}, "
|
|
73
|
+
f"got {decision.rule}"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@pytest.mark.parametrize("path", CASES, ids=lambda p: p.stem)
|
|
78
|
+
def test_decision_produces_a_record(path: Path):
|
|
79
|
+
"""Section 5: every evaluation SHOULD produce one record, written where the decision
|
|
80
|
+
is made. The plan calls for this from the start rather than bolted on later."""
|
|
81
|
+
case = load_case(path)
|
|
82
|
+
decision = evaluate(
|
|
83
|
+
envelope=case["envelope"],
|
|
84
|
+
call=Call(**case["call"]),
|
|
85
|
+
state=RunState(**case["state"]),
|
|
86
|
+
)
|
|
87
|
+
record = decision.record()
|
|
88
|
+
|
|
89
|
+
for field in ("envelope_id", "revision", "agent_identity", "principal", "tool", "result", "rule", "decided_at"):
|
|
90
|
+
assert field in record, f"the decision record has no {field}, which section 5 requires"
|
|
91
|
+
assert record["envelope_id"] == case["envelope"]["id"]
|
|
92
|
+
assert record["result"] == case["expect"]["result"]
|
|
93
|
+
assert record["rule"] == case["expect"]["rule"]
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""The enforcement point holds the run together, and the guard refuses before the call.
|
|
2
|
+
|
|
3
|
+
`evaluate` is pure. These cover the parts that are not: counting a run, refusing ahead
|
|
4
|
+
of the tool rather than reporting afterwards, and recording every outcome.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
from intent_envelope import EnforcementPoint, Escalated, Refused
|
|
16
|
+
|
|
17
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
18
|
+
|
|
19
|
+
ENVELOPE = {
|
|
20
|
+
"intent_envelope": "0.1",
|
|
21
|
+
"id": "test-agent",
|
|
22
|
+
"revision": 1,
|
|
23
|
+
"purpose": "A small envelope used to exercise the enforcement point across a run.",
|
|
24
|
+
"principal": {"agent_identity": "test-agent", "on_behalf_of": "ops.team"},
|
|
25
|
+
"tools": {
|
|
26
|
+
"allow": [{"name": "search"}, {"name": "send_email", "constraints": {"template": "summary"}}],
|
|
27
|
+
"deny": ["issue_payment"],
|
|
28
|
+
},
|
|
29
|
+
"recipients": {"allow": ["ops@example.com"], "max_per_run": 2},
|
|
30
|
+
"limits": {"max_tool_calls": 3, "max_spend_usd": 1.0},
|
|
31
|
+
"escalate": [{"when": "amount > 1000", "to": "ops-duty", "timeout_seconds": 600}],
|
|
32
|
+
"on_no_response": "deny",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def point(**kw) -> EnforcementPoint:
|
|
37
|
+
return EnforcementPoint(ENVELOPE, **kw)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_the_guard_refuses_before_the_tool_runs():
|
|
41
|
+
"""A decision made after the call is a report. The tool must not be reached."""
|
|
42
|
+
ran = []
|
|
43
|
+
|
|
44
|
+
def call_tool(name, arguments=None):
|
|
45
|
+
ran.append(name)
|
|
46
|
+
return "done"
|
|
47
|
+
|
|
48
|
+
guarded = point().guard(call_tool)
|
|
49
|
+
assert guarded("search", {}) == "done"
|
|
50
|
+
with pytest.raises(Refused):
|
|
51
|
+
guarded("issue_payment", {"amount": 50})
|
|
52
|
+
|
|
53
|
+
assert ran == ["search"], "the refused call reached the tool anyway"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_the_guard_works_on_an_async_tool_call():
|
|
57
|
+
"""MCP clients are usually async, and an enforcement point that is not is unusable."""
|
|
58
|
+
ran = []
|
|
59
|
+
|
|
60
|
+
async def call_tool(name, arguments=None):
|
|
61
|
+
ran.append(name)
|
|
62
|
+
return "done"
|
|
63
|
+
|
|
64
|
+
guarded = point().guard(call_tool)
|
|
65
|
+
|
|
66
|
+
async def exercise():
|
|
67
|
+
assert await guarded("search", {}) == "done"
|
|
68
|
+
with pytest.raises(Refused):
|
|
69
|
+
await guarded("issue_payment", {"amount": 50})
|
|
70
|
+
|
|
71
|
+
asyncio.run(exercise())
|
|
72
|
+
assert ran == ["search"]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_a_refused_call_does_not_spend_the_run_budget():
|
|
76
|
+
"""Otherwise a blocked agent can exhaust its own allowance by being blocked."""
|
|
77
|
+
p = point()
|
|
78
|
+
for _ in range(5):
|
|
79
|
+
with pytest.raises(Refused):
|
|
80
|
+
p.enforce("issue_payment", {"amount": 1})
|
|
81
|
+
assert p.state.tool_calls_made == 0
|
|
82
|
+
# The budget is intact, so legitimate work still runs.
|
|
83
|
+
assert p.enforce("search", {}).result == "allow"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_limits_bite_across_a_run_rather_than_per_call():
|
|
87
|
+
"""No single call exceeds max_tool_calls. Three of them do."""
|
|
88
|
+
p = point()
|
|
89
|
+
for _ in range(3):
|
|
90
|
+
assert p.enforce("search", {}).result == "allow"
|
|
91
|
+
with pytest.raises(Refused) as refusal:
|
|
92
|
+
p.enforce("search", {})
|
|
93
|
+
assert refusal.value.decision.rule == "limits"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_recipients_are_counted_across_a_run():
|
|
97
|
+
p = point()
|
|
98
|
+
for _ in range(2):
|
|
99
|
+
p.enforce("send_email", {"template": "summary", "to": "ops@example.com"})
|
|
100
|
+
with pytest.raises(Refused) as refusal:
|
|
101
|
+
p.enforce("send_email", {"template": "summary", "to": "ops@example.com"})
|
|
102
|
+
assert refusal.value.decision.rule == "recipients"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_escalation_is_not_refusal():
|
|
106
|
+
"""Collapsing the two loses the whole point of having an escalation path."""
|
|
107
|
+
p = point()
|
|
108
|
+
with pytest.raises(Escalated) as pause:
|
|
109
|
+
p.enforce("send_email", {"template": "summary", "to": "ops@example.com"}, context={"amount": 5000})
|
|
110
|
+
assert pause.value.decision.escalate_to == "ops-duty"
|
|
111
|
+
assert pause.value.decision.timeout_seconds == 600
|
|
112
|
+
assert not isinstance(pause.value, Refused)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_the_ledger_records_refusals_too():
|
|
116
|
+
"""A ledger holding only what succeeded cannot answer what an incident asks."""
|
|
117
|
+
p = point()
|
|
118
|
+
p.check("search", {})
|
|
119
|
+
p.check("issue_payment", {"amount": 10})
|
|
120
|
+
p.check("send_email", {"template": "summary", "to": "ops@example.com"}, context={"amount": 9999})
|
|
121
|
+
|
|
122
|
+
assert p.summary() == {"allow": 1, "deny": 1, "escalate": 1}
|
|
123
|
+
rules = [entry["rule"] for entry in p.ledger()]
|
|
124
|
+
assert rules == ["allow", "tools.deny", "escalate"]
|
|
125
|
+
for entry in p.ledger():
|
|
126
|
+
assert entry["envelope_id"] == "test-agent"
|
|
127
|
+
assert entry["agent_identity"] == "test-agent"
|
|
128
|
+
assert entry["decided_at"]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_arguments_cannot_widen_the_envelope():
|
|
132
|
+
"""There is no argument an agent can pass that grants itself something."""
|
|
133
|
+
p = point()
|
|
134
|
+
for sneaky in (
|
|
135
|
+
{"amount": 1, "allow": True},
|
|
136
|
+
{"amount": 1, "override": "approved by finance"},
|
|
137
|
+
{"amount": 1, "envelope": {"tools": {"allow": [{"name": "issue_payment"}]}}},
|
|
138
|
+
{"amount": 1, "_bypass": "true"},
|
|
139
|
+
):
|
|
140
|
+
with pytest.raises(Refused) as refusal:
|
|
141
|
+
p.enforce("issue_payment", sneaky)
|
|
142
|
+
assert refusal.value.decision.rule == "tools.deny"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_the_demo_still_refuses_what_it_claims_to_refuse():
|
|
146
|
+
"""The demo is the sales asset. It should fail the build, not a meeting."""
|
|
147
|
+
import importlib.util
|
|
148
|
+
|
|
149
|
+
path = ROOT / "examples" / "demo_poisoned_document.py"
|
|
150
|
+
spec = importlib.util.spec_from_file_location("demo_poisoned_document", path)
|
|
151
|
+
demo = importlib.util.module_from_spec(spec)
|
|
152
|
+
assert spec.loader
|
|
153
|
+
spec.loader.exec_module(demo)
|
|
154
|
+
|
|
155
|
+
p = EnforcementPoint(demo.ENVELOPE)
|
|
156
|
+
results = []
|
|
157
|
+
for _description, tool, arguments, extra in demo.PLAN:
|
|
158
|
+
results.append(p.check(tool, arguments, **extra).result)
|
|
159
|
+
|
|
160
|
+
assert results == ["allow", "allow", "allow", "deny", "deny", "escalate"], (
|
|
161
|
+
"the demo no longer tells the story it claims to"
|
|
162
|
+
)
|
|
163
|
+
rules = [d.rule for d in p.decisions]
|
|
164
|
+
assert rules[3] == "recipients", "the exfiltration attempt stopped for the wrong reason"
|
|
165
|
+
assert rules[4] == "tools.deny", "the payment attempt stopped for the wrong reason"
|
|
166
|
+
assert json.dumps(p.ledger()), "the ledger must be serialisable, since it is written somewhere"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""expires must be a real RFC 3339 instant, not merely a string.
|
|
2
|
+
|
|
3
|
+
Section 3 denies every call under an expired envelope, so an enforcement point has
|
|
4
|
+
to parse this value. jsonschema treats "format" as an annotation unless a checker is
|
|
5
|
+
supplied, and the date-time checker only exists when rfc3339-validator is installed,
|
|
6
|
+
so two separate things have to stay true for expires to mean anything. These tests
|
|
7
|
+
fail if either one is undone.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
from intent_envelope.validate import ValidationError, validate
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def envelope(**overrides):
|
|
16
|
+
base = {
|
|
17
|
+
"intent_envelope": "0.1",
|
|
18
|
+
"id": "expiry-fixture-agent",
|
|
19
|
+
"revision": 1,
|
|
20
|
+
"purpose": "A minimal valid envelope used to test the expires field in isolation.",
|
|
21
|
+
"principal": {"agent_identity": "fixture-agent"},
|
|
22
|
+
"tools": {"allow": [{"name": "kb_search"}]},
|
|
23
|
+
"limits": {"max_tool_calls": 1},
|
|
24
|
+
"on_no_response": "deny",
|
|
25
|
+
}
|
|
26
|
+
base.update(overrides)
|
|
27
|
+
return base
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_the_fixture_itself_is_valid_without_expires():
|
|
31
|
+
validate(envelope())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@pytest.mark.parametrize(
|
|
35
|
+
"value",
|
|
36
|
+
[
|
|
37
|
+
"2027-01-01T00:00:00Z",
|
|
38
|
+
"2027-01-01T00:00:00.500Z",
|
|
39
|
+
"2027-01-01T12:00:00+05:30",
|
|
40
|
+
"2028-02-29T00:00:00Z", # 2028 is a leap year
|
|
41
|
+
],
|
|
42
|
+
)
|
|
43
|
+
def test_real_instants_are_accepted(value):
|
|
44
|
+
validate(envelope(expires=value))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize(
|
|
48
|
+
"value",
|
|
49
|
+
[
|
|
50
|
+
"NOT A DATE",
|
|
51
|
+
"",
|
|
52
|
+
"2026-13-01T00:00:00Z", # month 13
|
|
53
|
+
"2026-02-30T00:00:00Z", # day that does not exist
|
|
54
|
+
"2026-01-01T25:00:00Z", # hour 25
|
|
55
|
+
"2026-01-01", # date with no time
|
|
56
|
+
"01/01/2026", # a different calendar convention entirely
|
|
57
|
+
"2026-01-01T00:00:00", # no offset, so not a fixed instant
|
|
58
|
+
],
|
|
59
|
+
)
|
|
60
|
+
def test_strings_that_are_not_instants_are_rejected(value):
|
|
61
|
+
with pytest.raises(ValidationError) as caught:
|
|
62
|
+
validate(envelope(expires=value))
|
|
63
|
+
assert any("expires" in problem for problem in caught.value.problems), (
|
|
64
|
+
f"{value!r} was rejected, but the problem did not name expires: {caught.value.problems}"
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_the_date_time_checker_is_actually_installed():
|
|
69
|
+
"""Guards the dependency rather than the code.
|
|
70
|
+
|
|
71
|
+
If rfc3339-validator goes missing, FormatChecker keeps working and silently stops
|
|
72
|
+
checking date-time, so every test above would still pass while expires quietly
|
|
73
|
+
accepted anything. This asserts the checker exists.
|
|
74
|
+
"""
|
|
75
|
+
from jsonschema import FormatChecker
|
|
76
|
+
|
|
77
|
+
assert "date-time" in FormatChecker().checkers, (
|
|
78
|
+
"no date-time format checker is registered, so expires is not being validated. "
|
|
79
|
+
"Install rfc3339-validator."
|
|
80
|
+
)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""What gets published has to match what the repository says it is.
|
|
2
|
+
|
|
3
|
+
These are the checks that would have caught the 0.0.1 release, which went to PyPI
|
|
4
|
+
carrying only the validator while the README documented an enforcement point. Anyone
|
|
5
|
+
following the README after installing it got an ImportError. A test suite that only
|
|
6
|
+
ever runs against the source tree cannot see that, because nothing in it imports the
|
|
7
|
+
package the way a person who ran `pip install` does.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
import intent_envelope
|
|
16
|
+
|
|
17
|
+
PYPROJECT = Path(__file__).resolve().parents[1] / "pyproject.toml"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def declared_version() -> str:
|
|
21
|
+
"""The version pip will record, read from the file the build backend reads."""
|
|
22
|
+
# tomllib is 3.11+, and this package supports 3.9, so fall back to a narrow regex
|
|
23
|
+
# rather than taking a dependency for one field.
|
|
24
|
+
text = PYPROJECT.read_text(encoding="utf-8")
|
|
25
|
+
match = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)
|
|
26
|
+
assert match, "no version found in pyproject.toml"
|
|
27
|
+
return match.group(1)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_module_version_matches_pyproject():
|
|
31
|
+
# Two places holding the same number is two places to forget. __init__ said 0.1.0
|
|
32
|
+
# while pyproject said 0.0.1, which would have failed the release workflow's tag
|
|
33
|
+
# check while the installed package reported a version that was never published.
|
|
34
|
+
assert intent_envelope.__version__ == declared_version()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_installed_metadata_matches_the_module():
|
|
38
|
+
# The version pip records comes from the built metadata, not from __init__. If the
|
|
39
|
+
# two disagree, `pip show` and `intent_envelope.__version__` tell different stories
|
|
40
|
+
# and an audit trail citing either one is unreliable.
|
|
41
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
42
|
+
|
|
43
|
+
try:
|
|
44
|
+
installed = version("intent-envelope")
|
|
45
|
+
except PackageNotFoundError:
|
|
46
|
+
pytest.skip("package is not installed; run against an installed copy")
|
|
47
|
+
assert installed == intent_envelope.__version__
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@pytest.mark.parametrize(
|
|
51
|
+
"name",
|
|
52
|
+
[
|
|
53
|
+
# The envelope half.
|
|
54
|
+
"validate",
|
|
55
|
+
"load_schema",
|
|
56
|
+
"ValidationError",
|
|
57
|
+
# The decision half, absent from 0.0.1 despite being in the README.
|
|
58
|
+
"evaluate",
|
|
59
|
+
"Call",
|
|
60
|
+
"RunState",
|
|
61
|
+
"Decision",
|
|
62
|
+
"UnsupportedCondition",
|
|
63
|
+
# The enforcement half, likewise absent.
|
|
64
|
+
"EnforcementPoint",
|
|
65
|
+
"Refused",
|
|
66
|
+
"Escalated",
|
|
67
|
+
"default_facts",
|
|
68
|
+
],
|
|
69
|
+
)
|
|
70
|
+
def test_public_name_is_importable(name):
|
|
71
|
+
"""Everything __all__ promises must actually import from the package root."""
|
|
72
|
+
assert hasattr(intent_envelope, name), f"intent_envelope.{name} is missing"
|
|
73
|
+
assert name in intent_envelope.__all__, f"{name} imports but is not in __all__"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_all_names_resolve():
|
|
77
|
+
"""And nothing in __all__ may be a name that does not exist."""
|
|
78
|
+
missing = [n for n in intent_envelope.__all__ if not hasattr(intent_envelope, n)]
|
|
79
|
+
assert not missing, f"__all__ promises names the package does not have: {missing}"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def test_the_schema_ships_inside_the_package():
|
|
83
|
+
# The package must not reach outside its own directory for the schema, because an
|
|
84
|
+
# installed copy has no repository around it.
|
|
85
|
+
schema = Path(intent_envelope.__file__).parent / "schema" / "intent-envelope-0.1.json"
|
|
86
|
+
assert schema.is_file(), "the schema is not inside the installed package"
|
|
87
|
+
assert intent_envelope.load_schema()["$id"].endswith("intent-envelope/0.1.json")
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Build the package, install the wheel into a clean venv, and make a decision with it.
|
|
3
|
+
|
|
4
|
+
This exists because of 0.0.1. That release went to PyPI carrying only the validator,
|
|
5
|
+
while the README documented an enforcement point, so `pip install intent-envelope`
|
|
6
|
+
followed by the README's own example raised ImportError. Every test in the suite
|
|
7
|
+
passed, because all of them imported from the source tree rather than from an
|
|
8
|
+
installed copy.
|
|
9
|
+
|
|
10
|
+
So this builds the real artifacts, installs the wheel somewhere with no repository
|
|
11
|
+
around it and no source directory on the path, and runs an envelope through it. It
|
|
12
|
+
also checks the sdist, because that is what a consumer on an unsupported platform
|
|
13
|
+
builds from.
|
|
14
|
+
|
|
15
|
+
Run: python packages/python/tools/consumer_smoke.py
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
import tarfile
|
|
23
|
+
import tempfile
|
|
24
|
+
import venv
|
|
25
|
+
import zipfile
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
PKG = Path(__file__).resolve().parents[1]
|
|
29
|
+
|
|
30
|
+
# Everything the README promises. 0.0.1 shipped the first three and none of the rest.
|
|
31
|
+
REQUIRED_MODULES = ["__init__.py", "validate.py", "evaluate.py", "enforce.py", "cli.py"]
|
|
32
|
+
|
|
33
|
+
CONSUMER = r'''
|
|
34
|
+
import sys
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
import intent_envelope
|
|
38
|
+
from intent_envelope import Call, EnforcementPoint, Refused, RunState, evaluate, validate
|
|
39
|
+
|
|
40
|
+
# Nothing may resolve from a source checkout. If it does, this proves nothing.
|
|
41
|
+
location = Path(intent_envelope.__file__).resolve()
|
|
42
|
+
assert "site-packages" in location.parts, f"imported from {location}, not an install"
|
|
43
|
+
|
|
44
|
+
envelope = {
|
|
45
|
+
"intent_envelope": "0.1",
|
|
46
|
+
"id": "invoice-reconciler",
|
|
47
|
+
"revision": 3,
|
|
48
|
+
"purpose": "Reconcile supplier invoices against the ledger and email a summary to the AP team.",
|
|
49
|
+
"principal": {"agent_identity": "invoice-reconciler", "on_behalf_of": "finance.ap_team"},
|
|
50
|
+
"tools": {
|
|
51
|
+
"allow": [{"name": "send_email", "constraints": {"template": "summary"}}],
|
|
52
|
+
"deny": ["issue_payment", "http_request"],
|
|
53
|
+
},
|
|
54
|
+
"recipients": {"allow": ["ap-team@example.com"], "max_per_run": 2},
|
|
55
|
+
"limits": {"max_tool_calls": 10, "max_spend_usd": 2.0},
|
|
56
|
+
"escalate": [{"when": "mismatch_value_gbp > 10000", "to": "ap-duty-controller", "timeout_seconds": 3600}],
|
|
57
|
+
"on_no_response": "deny",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
validate(envelope)
|
|
61
|
+
|
|
62
|
+
point = EnforcementPoint(envelope)
|
|
63
|
+
|
|
64
|
+
allowed = point.check("send_email", {"template": "summary", "to": "ap-team@example.com"})
|
|
65
|
+
assert allowed.result == "allow", allowed.result
|
|
66
|
+
|
|
67
|
+
exfil = point.check("send_email", {"template": "summary", "to": "collector@elsewhere.example"})
|
|
68
|
+
assert exfil.result == "deny" and exfil.rule == "recipients", (exfil.result, exfil.rule)
|
|
69
|
+
|
|
70
|
+
payment = point.check("issue_payment", {"amount": 24900})
|
|
71
|
+
assert payment.result == "deny" and payment.rule == "tools.deny", (payment.result, payment.rule)
|
|
72
|
+
|
|
73
|
+
assert point.summary() == {"allow": 1, "deny": 2, "escalate": 0}, point.summary()
|
|
74
|
+
|
|
75
|
+
# The guard must refuse before the tool is reached.
|
|
76
|
+
ran = []
|
|
77
|
+
guarded = point.guard(lambda name, args=None: ran.append(name))
|
|
78
|
+
try:
|
|
79
|
+
guarded("issue_payment", {"amount": 1})
|
|
80
|
+
except Refused:
|
|
81
|
+
pass
|
|
82
|
+
else:
|
|
83
|
+
raise AssertionError("the guard let a denied call through")
|
|
84
|
+
assert ran == [], f"the refused call reached the tool anyway: {ran}"
|
|
85
|
+
|
|
86
|
+
# Note the asymmetry with the TypeScript package, which takes a plain object here.
|
|
87
|
+
# Python takes the dataclasses, which is what the conformance runner constructs too.
|
|
88
|
+
assert evaluate(envelope, Call(tool="issue_payment"), RunState()).rule == "tools.deny"
|
|
89
|
+
|
|
90
|
+
# The schema has to travel inside the package, since an install has no repo around it.
|
|
91
|
+
assert intent_envelope.load_schema()["$id"].endswith("intent-envelope/0.1.json")
|
|
92
|
+
|
|
93
|
+
# The CLI is an entry point, so it is installed separately from the module.
|
|
94
|
+
print(f"installed {intent_envelope.__version__}: validates, decides, refuses, ships its schema")
|
|
95
|
+
'''
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def run(args: list[str], cwd: Path | None = None) -> str:
|
|
99
|
+
done = subprocess.run(args, cwd=cwd, capture_output=True, text=True)
|
|
100
|
+
if done.returncode != 0:
|
|
101
|
+
# A smoke test that hides the failure it found is worse than no smoke test.
|
|
102
|
+
raise SystemExit(
|
|
103
|
+
f"\n{' '.join(args[-2:])} failed with status {done.returncode}\n"
|
|
104
|
+
f"{done.stdout}{done.stderr}"
|
|
105
|
+
)
|
|
106
|
+
return done.stdout
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def contents(artifact: Path) -> set[str]:
|
|
110
|
+
if artifact.suffix == ".whl":
|
|
111
|
+
with zipfile.ZipFile(artifact) as z:
|
|
112
|
+
return {Path(n).name for n in z.namelist()}
|
|
113
|
+
with tarfile.open(artifact) as t:
|
|
114
|
+
return {Path(n).name for n in t.getnames()}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main() -> int:
|
|
118
|
+
with tempfile.TemporaryDirectory(prefix="intent-envelope-consumer-") as tmp:
|
|
119
|
+
scratch = Path(tmp)
|
|
120
|
+
dist = scratch / "dist"
|
|
121
|
+
|
|
122
|
+
print("building sdist and wheel")
|
|
123
|
+
run([sys.executable, "-m", "build", "--outdir", str(dist)], cwd=PKG)
|
|
124
|
+
|
|
125
|
+
artifacts = sorted(dist.iterdir())
|
|
126
|
+
if len(artifacts) != 2:
|
|
127
|
+
print(f"expected an sdist and a wheel, got {[a.name for a in artifacts]}")
|
|
128
|
+
return 1
|
|
129
|
+
|
|
130
|
+
# Check both: a wheel is what most people install, an sdist is what the rest build.
|
|
131
|
+
for artifact in artifacts:
|
|
132
|
+
names = contents(artifact)
|
|
133
|
+
missing = [m for m in REQUIRED_MODULES if m not in names]
|
|
134
|
+
if missing:
|
|
135
|
+
print(f"{artifact.name} is missing {missing}")
|
|
136
|
+
return 1
|
|
137
|
+
if "intent-envelope-0.1.json" not in names:
|
|
138
|
+
print(f"{artifact.name} does not carry the schema")
|
|
139
|
+
return 1
|
|
140
|
+
print(f"{artifact.name}: every module and the schema are present")
|
|
141
|
+
|
|
142
|
+
wheel = next(a for a in artifacts if a.suffix == ".whl")
|
|
143
|
+
|
|
144
|
+
print("installing the wheel into a clean environment")
|
|
145
|
+
env_dir = scratch / "venv"
|
|
146
|
+
venv.create(env_dir, with_pip=True)
|
|
147
|
+
# Windows puts executables in Scripts and adds .exe. Hardcoding bin/ is the
|
|
148
|
+
# same mistake the TypeScript smoke test made by assuming npm was not a .cmd.
|
|
149
|
+
windows = sys.platform == "win32"
|
|
150
|
+
bindir = env_dir / ("Scripts" if windows else "bin")
|
|
151
|
+
suffix = ".exe" if windows else ""
|
|
152
|
+
python = bindir / f"python{suffix}"
|
|
153
|
+
run([str(python), "-m", "pip", "install", "--quiet", str(wheel)])
|
|
154
|
+
|
|
155
|
+
app = scratch / "consumer.py"
|
|
156
|
+
app.write_text(CONSUMER, encoding="utf-8")
|
|
157
|
+
# cwd is the scratch directory, so the repository is not importable from here.
|
|
158
|
+
print(run([str(python), str(app)], cwd=scratch).strip())
|
|
159
|
+
|
|
160
|
+
cli = run([str(bindir / f"intent-envelope{suffix}"), "--help"]).strip()
|
|
161
|
+
if "validate" not in cli:
|
|
162
|
+
print("the installed CLI does not offer validate")
|
|
163
|
+
return 1
|
|
164
|
+
print("the installed CLI works")
|
|
165
|
+
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
if __name__ == "__main__":
|
|
170
|
+
sys.exit(main())
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
"""Declared intent envelopes for AI agents.
|
|
2
|
-
|
|
3
|
-
An envelope states what an agent is for: the tools it may call, the data it may
|
|
4
|
-
touch, who it may contact, what it may spend, and which actions need a human.
|
|
5
|
-
It is written before the agent runs and checked in code at every tool call.
|
|
6
|
-
|
|
7
|
-
Specification: https://securedai.org/agent-intent
|
|
8
|
-
"""
|
|
9
|
-
|
|
10
|
-
from .validate import ValidationError, load_schema, validate
|
|
11
|
-
|
|
12
|
-
__version__ = "0.0.1"
|
|
13
|
-
__all__ = ["validate", "load_schema", "ValidationError", "__version__"]
|
|
File without changes
|
{intent_envelope-0.0.1 → intent_envelope-0.2.0}/src/intent_envelope/schema/intent-envelope-0.1.json
RENAMED
|
File without changes
|
|
File without changes
|