capsule-strands 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- capsule_strands/__init__.py +9 -0
- capsule_strands/config.py +65 -0
- capsule_strands/plugin.py +253 -0
- capsule_strands/transport.py +50 -0
- capsule_strands-0.1.0.dist-info/METADATA +124 -0
- capsule_strands-0.1.0.dist-info/RECORD +8 -0
- capsule_strands-0.1.0.dist-info/WHEEL +4 -0
- capsule_strands-0.1.0.dist-info/licenses/LICENSE +32 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Capsule plugin for Strands Agents.
|
|
2
|
+
|
|
3
|
+
Puts a Strands agent's prompts and tool calls behind Capsule policies and reports every session for audit.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from .config import CapsuleConfig
|
|
7
|
+
from .plugin import PLUGIN_VERSION, CapsuleBlockedError, CapsulePlugin
|
|
8
|
+
|
|
9
|
+
__all__ = ["CapsuleBlockedError", "CapsuleConfig", "CapsulePlugin", "PLUGIN_VERSION"]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Configuration for the Capsule Strands plugin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
_ENV_PREFIX = "CAPSULE_STRANDS_"
|
|
9
|
+
_TRUE_VALUES = {"1", "true", "yes", "on"}
|
|
10
|
+
DEFAULT_TIMEOUT_MS = 35_000
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _env(key: str) -> str | None:
|
|
14
|
+
value = os.environ.get(f"{_ENV_PREFIX}{key}")
|
|
15
|
+
return value if value else None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _env_bool(key: str, default: bool) -> bool:
|
|
19
|
+
value = _env(key)
|
|
20
|
+
return default if value is None else value.strip().lower() in _TRUE_VALUES
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _env_int(key: str, default: int) -> int:
|
|
24
|
+
value = _env(key)
|
|
25
|
+
if value is None:
|
|
26
|
+
return default
|
|
27
|
+
try:
|
|
28
|
+
return int(value)
|
|
29
|
+
except ValueError as error:
|
|
30
|
+
raise ValueError(f"capsule_strands: {_ENV_PREFIX}{key} must be an integer, got {value!r}") from error
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class CapsuleConfig:
|
|
35
|
+
"""Plugin settings. Constructor arguments win; `CAPSULE_STRANDS_*` environment variables fill in the rest."""
|
|
36
|
+
|
|
37
|
+
endpoint: str
|
|
38
|
+
token: str
|
|
39
|
+
block_on_risk: bool
|
|
40
|
+
fail_open: bool
|
|
41
|
+
timeout_ms: int
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def load(
|
|
45
|
+
cls,
|
|
46
|
+
*,
|
|
47
|
+
endpoint: str | None = None,
|
|
48
|
+
token: str | None = None,
|
|
49
|
+
block_on_risk: bool | None = None,
|
|
50
|
+
fail_open: bool | None = None,
|
|
51
|
+
timeout_ms: int | None = None,
|
|
52
|
+
) -> CapsuleConfig:
|
|
53
|
+
resolved_endpoint = endpoint or _env("ENDPOINT")
|
|
54
|
+
resolved_token = token or _env("TOKEN")
|
|
55
|
+
if not resolved_endpoint:
|
|
56
|
+
raise ValueError(f"capsule_strands: endpoint missing (pass endpoint= or set {_ENV_PREFIX}ENDPOINT)")
|
|
57
|
+
if not resolved_token:
|
|
58
|
+
raise ValueError(f"capsule_strands: token missing (pass token= or set {_ENV_PREFIX}TOKEN)")
|
|
59
|
+
return cls(
|
|
60
|
+
endpoint=resolved_endpoint,
|
|
61
|
+
token=resolved_token,
|
|
62
|
+
block_on_risk=block_on_risk if block_on_risk is not None else _env_bool("BLOCK_ON_RISK", True),
|
|
63
|
+
fail_open=fail_open if fail_open is not None else _env_bool("FAIL_OPEN", True),
|
|
64
|
+
timeout_ms=timeout_ms if timeout_ms is not None else _env_int("TIMEOUT_MS", DEFAULT_TIMEOUT_MS),
|
|
65
|
+
)
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Strands Agents plugin that puts an agent's prompts and tool calls behind Capsule policies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import threading
|
|
9
|
+
import uuid
|
|
10
|
+
import weakref
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from strands import Agent
|
|
17
|
+
from strands.hooks import AfterInvocationEvent, AfterToolCallEvent, BeforeInvocationEvent, BeforeToolCallEvent
|
|
18
|
+
from strands.plugins import Plugin, hook
|
|
19
|
+
|
|
20
|
+
from .config import CapsuleConfig
|
|
21
|
+
from .transport import CapsuleTransport
|
|
22
|
+
|
|
23
|
+
PLUGIN_VERSION = "0.1.0"
|
|
24
|
+
# Strands gives every agent this id unless the caller sets `agent_id`.
|
|
25
|
+
_SDK_DEFAULT_AGENT_ID = "default"
|
|
26
|
+
_DEFAULT_BLOCK_REASON = "Blocked by Capsule policy"
|
|
27
|
+
_UNAVAILABLE_REASON = "Capsule policy unavailable"
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger("capsule_strands")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CapsuleBlockedError(RuntimeError):
|
|
33
|
+
"""Raised by the deprecated `Agent.structured_output()` when Capsule blocks its prompt."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class _Session:
|
|
38
|
+
id: str
|
|
39
|
+
started: bool = False
|
|
40
|
+
last_report: threading.Thread | None = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CapsulePlugin(Plugin):
|
|
44
|
+
"""Sends each prompt and tool call to Capsule for an allow/block verdict, and reports the rest of the session.
|
|
45
|
+
|
|
46
|
+
Prompts and tool calls wait for the verdict. Tool results and replies are posted in the background.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
name = "capsule"
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
*,
|
|
54
|
+
endpoint: str | None = None,
|
|
55
|
+
token: str | None = None,
|
|
56
|
+
block_on_risk: bool | None = None,
|
|
57
|
+
fail_open: bool | None = None,
|
|
58
|
+
timeout_ms: int | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__()
|
|
61
|
+
self._config = CapsuleConfig.load(
|
|
62
|
+
endpoint=endpoint, token=token, block_on_risk=block_on_risk, fail_open=fail_open, timeout_ms=timeout_ms
|
|
63
|
+
)
|
|
64
|
+
self._transport = CapsuleTransport(self._config)
|
|
65
|
+
self._sessions: weakref.WeakKeyDictionary[Agent, _Session] = weakref.WeakKeyDictionary()
|
|
66
|
+
|
|
67
|
+
def init_agent(self, agent: Agent) -> None:
|
|
68
|
+
# The deprecated structured_output() hands hooks neither its prompt nor a cancel, so it is gated here instead.
|
|
69
|
+
structured_output_async = agent.structured_output_async
|
|
70
|
+
|
|
71
|
+
async def gated_structured_output_async(output_model: Any, prompt: Any = None) -> Any:
|
|
72
|
+
reason = await self._judge_prompt(agent, _input_text(prompt))
|
|
73
|
+
if reason is not None:
|
|
74
|
+
raise CapsuleBlockedError(reason)
|
|
75
|
+
return await structured_output_async(output_model, prompt)
|
|
76
|
+
|
|
77
|
+
agent.structured_output_async = gated_structured_output_async
|
|
78
|
+
|
|
79
|
+
@hook
|
|
80
|
+
async def gate_prompt(self, event: BeforeInvocationEvent) -> None:
|
|
81
|
+
reason = await self._judge_prompt(event.agent, _prompt_text(event.messages))
|
|
82
|
+
if reason is not None:
|
|
83
|
+
event.cancel = reason
|
|
84
|
+
|
|
85
|
+
@hook
|
|
86
|
+
async def gate_tool_call(self, event: BeforeToolCallEvent) -> None:
|
|
87
|
+
tool = {"tool_use_id": event.tool_use["toolUseId"], "name": event.tool_use["name"], "input": _tool_input(event.tool_use)}
|
|
88
|
+
reason = await self._block_reason(self._event("tool_invocation", event.agent, self._session(event.agent), tool=tool))
|
|
89
|
+
if reason is not None:
|
|
90
|
+
event.cancel_tool = reason
|
|
91
|
+
|
|
92
|
+
@hook
|
|
93
|
+
def report_tool_result(self, event: AfterToolCallEvent) -> None:
|
|
94
|
+
# A cancelled call never ran, and Capsule already recorded why when it blocked it.
|
|
95
|
+
if event.cancel_message is not None:
|
|
96
|
+
return
|
|
97
|
+
tool = {
|
|
98
|
+
"tool_use_id": event.tool_use["toolUseId"],
|
|
99
|
+
"name": event.tool_use["name"],
|
|
100
|
+
"input": _tool_input(event.tool_use),
|
|
101
|
+
"output": _content_text(event.result.get("content", [])),
|
|
102
|
+
"status": event.result.get("status", "error"),
|
|
103
|
+
}
|
|
104
|
+
session = self._session(event.agent)
|
|
105
|
+
self._observe(session, self._event("tool_result", event.agent, session, tool=tool))
|
|
106
|
+
|
|
107
|
+
@hook
|
|
108
|
+
def report_reply(self, event: AfterInvocationEvent) -> None:
|
|
109
|
+
# No result means the invocation was cancelled or failed before the model answered.
|
|
110
|
+
if event.result is None:
|
|
111
|
+
return
|
|
112
|
+
reply = _content_text(event.result.message.get("content", []))
|
|
113
|
+
if reply:
|
|
114
|
+
session = self._session(event.agent)
|
|
115
|
+
self._observe(session, self._event("agent_message", event.agent, session, message={"content": reply}))
|
|
116
|
+
|
|
117
|
+
def _session(self, agent: Agent) -> _Session:
|
|
118
|
+
session = self._sessions.get(agent)
|
|
119
|
+
if session is None:
|
|
120
|
+
session = _Session(id=_session_id(agent))
|
|
121
|
+
self._sessions[agent] = session
|
|
122
|
+
return session
|
|
123
|
+
|
|
124
|
+
def _event(self, event_type: str, agent: Agent, session: _Session, **fields: Any) -> dict[str, Any]:
|
|
125
|
+
return {
|
|
126
|
+
"event_type": event_type,
|
|
127
|
+
"session_id": session.id,
|
|
128
|
+
"timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
129
|
+
"agent": _agent_info(agent),
|
|
130
|
+
"plugin_version": PLUGIN_VERSION,
|
|
131
|
+
**fields,
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async def _judge_prompt(self, agent: Agent, prompt: str | None) -> str | None:
|
|
135
|
+
session = self._session(agent)
|
|
136
|
+
if not session.started:
|
|
137
|
+
session.started = True
|
|
138
|
+
# Capsule timestamps each event when it arrives, so the session start must land before the first prompt.
|
|
139
|
+
start = self._event("session_start", agent, session, tools=_tool_specs(agent))
|
|
140
|
+
await asyncio.to_thread(self._post_quietly, start)
|
|
141
|
+
if prompt is None:
|
|
142
|
+
return None
|
|
143
|
+
return await self._block_reason(self._event("user_message", agent, session, message={"content": prompt}))
|
|
144
|
+
|
|
145
|
+
async def _block_reason(self, event: dict[str, Any]) -> str | None:
|
|
146
|
+
"""Why Capsule blocks the event, or None to let it through."""
|
|
147
|
+
try:
|
|
148
|
+
response = await self._transport.post_async(event)
|
|
149
|
+
except Exception as error:
|
|
150
|
+
logger.warning("capsule_strands: Capsule unreachable for %s: %r", event["event_type"], error)
|
|
151
|
+
return None if self._config.fail_open else _UNAVAILABLE_REASON
|
|
152
|
+
if not response.ok:
|
|
153
|
+
logger.warning("capsule_strands: Capsule answered %s for %s", response.status, event["event_type"])
|
|
154
|
+
return None if self._config.fail_open else _UNAVAILABLE_REASON
|
|
155
|
+
decision = response.body.get("response") if isinstance(response.body, Mapping) else None
|
|
156
|
+
if not isinstance(decision, Mapping) or decision.get("action") != "block":
|
|
157
|
+
return None
|
|
158
|
+
reason = decision.get("reason") or _DEFAULT_BLOCK_REASON
|
|
159
|
+
if not self._config.block_on_risk:
|
|
160
|
+
logger.info("capsule_strands: observe-only, letting through %s Capsule would block: %s", event["event_type"], reason)
|
|
161
|
+
return None
|
|
162
|
+
return reason
|
|
163
|
+
|
|
164
|
+
def _observe(self, session: _Session, event: dict[str, Any]) -> None:
|
|
165
|
+
# Not a daemon thread: the interpreter waits for it at exit, so a short-lived script still reports its last events.
|
|
166
|
+
thread = threading.Thread(
|
|
167
|
+
target=self._post_after, args=(session.last_report, event), name=f"capsule-{event['event_type']}"
|
|
168
|
+
)
|
|
169
|
+
session.last_report = thread
|
|
170
|
+
thread.start()
|
|
171
|
+
|
|
172
|
+
def _post_after(self, previous: threading.Thread | None, event: dict[str, Any]) -> None:
|
|
173
|
+
# Capsule timestamps each event when it arrives, so a session's reports go out one after another, in order.
|
|
174
|
+
if previous is not None:
|
|
175
|
+
previous.join()
|
|
176
|
+
self._post_quietly(event)
|
|
177
|
+
|
|
178
|
+
def _post_quietly(self, event: dict[str, Any]) -> None:
|
|
179
|
+
try:
|
|
180
|
+
response = self._transport.post(event)
|
|
181
|
+
except Exception as error:
|
|
182
|
+
logger.warning("capsule_strands: could not report %s: %r", event["event_type"], error)
|
|
183
|
+
return
|
|
184
|
+
if not response.ok:
|
|
185
|
+
logger.warning("capsule_strands: Capsule answered %s for %s", response.status, event["event_type"])
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _agent_info(agent: Agent) -> dict[str, Any]:
|
|
189
|
+
return {
|
|
190
|
+
"id": agent.name if agent.agent_id == _SDK_DEFAULT_AGENT_ID else agent.agent_id,
|
|
191
|
+
"name": agent.name,
|
|
192
|
+
"description": agent.description,
|
|
193
|
+
"instructions": agent.system_prompt,
|
|
194
|
+
"model": _model_id(agent),
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _model_id(agent: Agent) -> str | None:
|
|
199
|
+
try:
|
|
200
|
+
config = agent.model.get_config()
|
|
201
|
+
except Exception:
|
|
202
|
+
return None
|
|
203
|
+
model_id = config.get("model_id") if isinstance(config, Mapping) else None
|
|
204
|
+
return model_id if isinstance(model_id, str) and model_id else None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _session_id(agent: Agent) -> str:
|
|
208
|
+
trace_session_id = agent.trace_attributes.get("session.id")
|
|
209
|
+
if isinstance(trace_session_id, str) and trace_session_id:
|
|
210
|
+
return trace_session_id
|
|
211
|
+
# Agent keeps its session manager private; reading it keeps a restored session on the same id across processes.
|
|
212
|
+
manager_session_id = getattr(getattr(agent, "_session_manager", None), "session_id", None)
|
|
213
|
+
if isinstance(manager_session_id, str) and manager_session_id:
|
|
214
|
+
return manager_session_id
|
|
215
|
+
return str(uuid.uuid4())
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _tool_specs(agent: Agent) -> list[dict[str, Any]]:
|
|
219
|
+
return [
|
|
220
|
+
{"name": spec["name"], "description": spec.get("description")} for spec in agent.tool_registry.get_all_tool_specs()
|
|
221
|
+
]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _tool_input(tool_use: Mapping[str, Any]) -> dict[str, Any]:
|
|
225
|
+
tool_input = tool_use.get("input")
|
|
226
|
+
return dict(tool_input) if isinstance(tool_input, Mapping) else {"input": tool_input}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _prompt_text(messages: list[Mapping[str, Any]] | None) -> str | None:
|
|
230
|
+
texts = [_content_text(message.get("content", [])) for message in messages or [] if message.get("role") == "user"]
|
|
231
|
+
prompt = "\n".join(text for text in texts if text)
|
|
232
|
+
return prompt or None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _input_text(prompt: Any) -> str | None:
|
|
236
|
+
"""The text of an agent input: a string, a list of content blocks, or a list of messages."""
|
|
237
|
+
if isinstance(prompt, str):
|
|
238
|
+
return prompt or None
|
|
239
|
+
if isinstance(prompt, list) and all(isinstance(item, Mapping) for item in prompt):
|
|
240
|
+
if all("role" in item for item in prompt):
|
|
241
|
+
return _prompt_text(prompt)
|
|
242
|
+
return _content_text(prompt) or None
|
|
243
|
+
return None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _content_text(content: list[Mapping[str, Any]]) -> str:
|
|
247
|
+
parts = []
|
|
248
|
+
for block in content:
|
|
249
|
+
if "text" in block:
|
|
250
|
+
parts.append(str(block["text"]))
|
|
251
|
+
elif "json" in block:
|
|
252
|
+
parts.append(json.dumps(block["json"], default=str))
|
|
253
|
+
return "\n".join(parts)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""HTTP transport from the plugin to the Capsule Strands hooks endpoint."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .config import CapsuleConfig
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class CapsuleResponse:
|
|
16
|
+
ok: bool
|
|
17
|
+
status: int
|
|
18
|
+
body: Any
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CapsuleTransport:
|
|
22
|
+
"""Posts one event per request. Non-2xx responses come back as `ok=False`; the caller decides fail-open or fail-closed."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, config: CapsuleConfig) -> None:
|
|
25
|
+
self._config = config
|
|
26
|
+
self._timeout = config.timeout_ms / 1000
|
|
27
|
+
|
|
28
|
+
def _headers(self) -> dict[str, str]:
|
|
29
|
+
return {
|
|
30
|
+
"Authorization": f"Bearer {self._config.token}",
|
|
31
|
+
"X-Correlation-Id": str(uuid.uuid4()),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
def _response(response: httpx.Response) -> CapsuleResponse:
|
|
36
|
+
try:
|
|
37
|
+
body = response.json() if response.content else None
|
|
38
|
+
except ValueError:
|
|
39
|
+
body = response.text
|
|
40
|
+
return CapsuleResponse(ok=response.is_success, status=response.status_code, body=body)
|
|
41
|
+
|
|
42
|
+
async def post_async(self, event: dict[str, Any]) -> CapsuleResponse:
|
|
43
|
+
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
|
44
|
+
response = await client.post(self._config.endpoint, json=event, headers=self._headers())
|
|
45
|
+
return self._response(response)
|
|
46
|
+
|
|
47
|
+
def post(self, event: dict[str, Any]) -> CapsuleResponse:
|
|
48
|
+
with httpx.Client(timeout=self._timeout) as client:
|
|
49
|
+
response = client.post(self._config.endpoint, json=event, headers=self._headers())
|
|
50
|
+
return self._response(response)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: capsule-strands
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Capsule plugin for Strands Agents - gates prompts and tool calls against Capsule policies and reports every session for audit.
|
|
5
|
+
Project-URL: Homepage, https://github.com/capsulesecurity
|
|
6
|
+
Project-URL: Documentation, https://docs.capsulesecurity.io/guides/strands
|
|
7
|
+
Author: Capsule Security
|
|
8
|
+
License: Capsule Security Commercial License
|
|
9
|
+
|
|
10
|
+
Copyright (c) Capsule Security, Inc. All rights reserved.
|
|
11
|
+
|
|
12
|
+
This software is licensed, not sold, and is made available solely to customers
|
|
13
|
+
of Capsule Security, Inc. ("Capsule") under the terms of an active commercial
|
|
14
|
+
agreement (the "Subscription Agreement") between the customer and Capsule.
|
|
15
|
+
|
|
16
|
+
Subject to the Subscription Agreement, Capsule grants the customer a
|
|
17
|
+
non-exclusive, non-transferable, non-sublicensable, revocable license to install
|
|
18
|
+
and run this software in connection with the customer's authorized use of the
|
|
19
|
+
Capsule platform, solely for the customer's internal business operations.
|
|
20
|
+
|
|
21
|
+
Except as expressly permitted by the Subscription Agreement, you may not:
|
|
22
|
+
(a) copy, modify, or create derivative works of the software;
|
|
23
|
+
(b) reverse engineer, decompile, or disassemble the software;
|
|
24
|
+
(c) redistribute, sublicense, sell, rent, lease, or otherwise transfer the
|
|
25
|
+
software to any third party;
|
|
26
|
+
(d) remove or alter any proprietary notices contained in the software; or
|
|
27
|
+
(e) use the software except in connection with an active Subscription
|
|
28
|
+
Agreement.
|
|
29
|
+
|
|
30
|
+
Without a valid Subscription Agreement with Capsule, no rights are granted to
|
|
31
|
+
use this software. Unauthorized use is prohibited.
|
|
32
|
+
|
|
33
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND CAPSULE DISCLAIMS ALL WARRANTIES, EXPRESS
|
|
34
|
+
OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY WARRANTIES OF MERCHANTABILITY,
|
|
35
|
+
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. CAPSULE SHALL NOT BE
|
|
36
|
+
LIABLE FOR ANY DAMAGES ARISING FROM OR RELATING TO USE OF THE SOFTWARE EXCEPT
|
|
37
|
+
AS EXPRESSLY SET FORTH IN THE SUBSCRIPTION AGREEMENT.
|
|
38
|
+
|
|
39
|
+
For licensing inquiries, contact: sales@capsulesecurity.io
|
|
40
|
+
License-File: LICENSE
|
|
41
|
+
Keywords: agent-security,capsule,policy,security,strands,strands-agents
|
|
42
|
+
Classifier: License :: Other/Proprietary License
|
|
43
|
+
Classifier: Programming Language :: Python :: 3
|
|
44
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
45
|
+
Requires-Python: >=3.10
|
|
46
|
+
Requires-Dist: httpx>=0.27
|
|
47
|
+
Requires-Dist: strands-agents>=1.43
|
|
48
|
+
Description-Content-Type: text/markdown
|
|
49
|
+
|
|
50
|
+
# capsule-strands
|
|
51
|
+
|
|
52
|
+
Capsule plugin for [Strands Agents](https://strandsagents.com). It sends every prompt and tool call of a Strands agent to Capsule for an allow/block verdict before it runs, and reports the rest of the session for audit.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install capsule-strands
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
It requires `strands-agents` 1.43 or later.
|
|
61
|
+
|
|
62
|
+
## Configure
|
|
63
|
+
|
|
64
|
+
Attach the plugin to each agent:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from strands import Agent
|
|
68
|
+
from capsule_strands import CapsulePlugin
|
|
69
|
+
|
|
70
|
+
agent = Agent(
|
|
71
|
+
agent_id="support-agent",
|
|
72
|
+
name="Acme Support Agent",
|
|
73
|
+
system_prompt="You answer Acme billing questions.",
|
|
74
|
+
tools=[...],
|
|
75
|
+
plugins=[CapsulePlugin()],
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Set the endpoint and token where the agent runs:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
export CAPSULE_STRANDS_ENDPOINT="https://agents.capsule.security/v1/strands/hooks/events"
|
|
83
|
+
export CAPSULE_STRANDS_TOKEN="<token from the Capsule portal>"
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The `endpoint` and `token` values are issued by Capsule when you install the Strands Agents integration in the portal (**Integrations → Strands Agents**). The token is a JWT scoped to your tenant and environment, so treat it as a secret.
|
|
87
|
+
|
|
88
|
+
Every setting can also be passed to `CapsulePlugin(...)`. A constructor argument wins over its environment variable.
|
|
89
|
+
|
|
90
|
+
| Argument | Environment variable | Default | Description |
|
|
91
|
+
| --------------- | ------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
92
|
+
| `endpoint` | `CAPSULE_STRANDS_ENDPOINT` | | Required. |
|
|
93
|
+
| `token` | `CAPSULE_STRANDS_TOKEN` | | Required. |
|
|
94
|
+
| `block_on_risk` | `CAPSULE_STRANDS_BLOCK_ON_RISK` | `true` | Apply Capsule's `block` verdicts. Set to `false` to run the plugin in observe-only mode. |
|
|
95
|
+
| `fail_open` | `CAPSULE_STRANDS_FAIL_OPEN` | `true` | Let a prompt or tool call through when Capsule is unreachable or answers with an error. Set to `false` to block. |
|
|
96
|
+
| `timeout_ms` | `CAPSULE_STRANDS_TIMEOUT_MS` | `35000` | How long to wait for Capsule's verdict. When it passes first, the prompt or tool call follows `fail_open`. |
|
|
97
|
+
|
|
98
|
+
## How it works
|
|
99
|
+
|
|
100
|
+
| Strands hook | Type | Event | What happens on a block |
|
|
101
|
+
| ----------------------- | ----------- | ----------------- | ------------------------------------------------------------------------------------- |
|
|
102
|
+
| `BeforeInvocationEvent` | Blocking | `user_message` | The invocation is cancelled before the model is called; the agent returns the reason. |
|
|
103
|
+
| `BeforeToolCallEvent` | Blocking | `tool_invocation` | The tool never runs; the model gets an error tool result carrying the reason. |
|
|
104
|
+
| `AfterToolCallEvent` | Observation | `tool_result` | |
|
|
105
|
+
| `AfterInvocationEvent` | Observation | `agent_message` | |
|
|
106
|
+
|
|
107
|
+
The first invocation of each agent also reports a `session_start` with the agent's system prompt, model id and registered tools, before its prompt is judged. Tool results and replies are posted from a background thread, in the order they happened, so they never slow the agent down.
|
|
108
|
+
|
|
109
|
+
The deprecated `Agent.structured_output()` method is gated too. Strands gives hooks neither its prompt nor a way to cancel it, so the plugin judges the prompt before the call and raises `capsule_strands.CapsuleBlockedError` with the reason when Capsule blocks it.
|
|
110
|
+
|
|
111
|
+
Every event carries the agent's identity: its `agent_id`, or its `name` when `agent_id` is left at the Strands default. Set `agent_id` on each agent so Capsule keeps them apart. The session id is `trace_attributes["session.id"]` when the agent sets one, then the session manager's session id, and otherwise a random id per `Agent` instance.
|
|
112
|
+
|
|
113
|
+
## Tests
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pip install "strands-agents==<version>" -e . -r tests/requirements.txt
|
|
117
|
+
pytest tests
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The tests run real Strands agents against a scripted model and a fake Capsule. The end-to-end suite against the real Capsule backend lives in `apps/agentsecurity` (`nx run agentsecurity:test:strands-evals`).
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
Capsule Security Commercial License. See [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
capsule_strands/__init__.py,sha256=0QGofJtICO0fdFBFrgKFmnhdjybp_COGAOUJAZOzd7k,343
|
|
2
|
+
capsule_strands/config.py,sha256=pxMLysaTB1z8B9P9fszClmNxdAAX7ychH8mh1E9WiTk,2132
|
|
3
|
+
capsule_strands/plugin.py,sha256=io8K2vDvZMVaxr2Y5OB-3qGym8oCtQMmiRiI3d29oas,10548
|
|
4
|
+
capsule_strands/transport.py,sha256=BRBJ6-1m3Bnt9thEOrt-gPrT42swY3GixYx2fLfYJ_M,1654
|
|
5
|
+
capsule_strands-0.1.0.dist-info/METADATA,sha256=xVOF4N1ifnF-eoD6oF-bwHd61fohY-OyU2yRUCaSjQY,7332
|
|
6
|
+
capsule_strands-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
capsule_strands-0.1.0.dist-info/licenses/LICENSE,sha256=ctNJeenLlW05FMJY8-d9pQS_JFwezztB2ErieZ-37zk,1666
|
|
8
|
+
capsule_strands-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Capsule Security Commercial License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Capsule Security, Inc. All rights reserved.
|
|
4
|
+
|
|
5
|
+
This software is licensed, not sold, and is made available solely to customers
|
|
6
|
+
of Capsule Security, Inc. ("Capsule") under the terms of an active commercial
|
|
7
|
+
agreement (the "Subscription Agreement") between the customer and Capsule.
|
|
8
|
+
|
|
9
|
+
Subject to the Subscription Agreement, Capsule grants the customer a
|
|
10
|
+
non-exclusive, non-transferable, non-sublicensable, revocable license to install
|
|
11
|
+
and run this software in connection with the customer's authorized use of the
|
|
12
|
+
Capsule platform, solely for the customer's internal business operations.
|
|
13
|
+
|
|
14
|
+
Except as expressly permitted by the Subscription Agreement, you may not:
|
|
15
|
+
(a) copy, modify, or create derivative works of the software;
|
|
16
|
+
(b) reverse engineer, decompile, or disassemble the software;
|
|
17
|
+
(c) redistribute, sublicense, sell, rent, lease, or otherwise transfer the
|
|
18
|
+
software to any third party;
|
|
19
|
+
(d) remove or alter any proprietary notices contained in the software; or
|
|
20
|
+
(e) use the software except in connection with an active Subscription
|
|
21
|
+
Agreement.
|
|
22
|
+
|
|
23
|
+
Without a valid Subscription Agreement with Capsule, no rights are granted to
|
|
24
|
+
use this software. Unauthorized use is prohibited.
|
|
25
|
+
|
|
26
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND CAPSULE DISCLAIMS ALL WARRANTIES, EXPRESS
|
|
27
|
+
OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY WARRANTIES OF MERCHANTABILITY,
|
|
28
|
+
FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. CAPSULE SHALL NOT BE
|
|
29
|
+
LIABLE FOR ANY DAMAGES ARISING FROM OR RELATING TO USE OF THE SOFTWARE EXCEPT
|
|
30
|
+
AS EXPRESSLY SET FORTH IN THE SUBSCRIPTION AGREEMENT.
|
|
31
|
+
|
|
32
|
+
For licensing inquiries, contact: sales@capsulesecurity.io
|