xtrom-sdk 0.5.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.
xtrom_sdk/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """Xtrom SDK — wrap agent tools with runtime enforcement (taint/IFC + policy)."""
2
+ from .session import Session, BlockedError, StepUpRequired
3
+
4
+ __all__ = ["Session", "BlockedError", "StepUpRequired", "xtrom_headers", "API_VERSION"]
5
+ __version__ = "0.5.0"
6
+
7
+ # Version headers any future HTTP integration (e.g. remote authorize call,
8
+ # telemetry ship, control-plane sync) should attach so the server can log SDK
9
+ # skew, emit deprecation warnings, and correlate incidents with SDK build.
10
+ # Same handshake as the control plane's `X-Xtrom-API-Version`.
11
+ API_VERSION = "1"
12
+
13
+
14
+ def xtrom_headers() -> dict:
15
+ """HTTP headers every SDK-originated request MUST carry. Kept as one helper so
16
+ a version bump is a single-file change and no call site can silently omit."""
17
+ return {
18
+ "X-Xtrom-API-Version": API_VERSION,
19
+ "X-Xtrom-SDK-Version": __version__,
20
+ "X-Xtrom-SDK-Lang": "python",
21
+ }
xtrom_sdk/__main__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Module entrypoint: ``python -m xtrom_sdk`` == the ``xtrom`` console script.
2
+
3
+ Lets Windows users (and anyone whose per-user Scripts dir isn't on PATH) run the
4
+ CLI without the installed ``xtrom``/``xtrom.exe`` launcher being resolvable.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .local.cli import main
9
+
10
+ if __name__ == "__main__":
11
+ raise SystemExit(main())
@@ -0,0 +1,322 @@
1
+ """Framework adapters for guarding agent tool calls with an Xtrom Session.
2
+
3
+ The adapters are intentionally dependency-free: OpenAI/Anthropic payloads are
4
+ duck-typed dicts/objects, and LangChain/CrewAI tools are wrapped by interface
5
+ shape rather than imported base classes.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import inspect
11
+ from collections.abc import Callable, Mapping
12
+ from typing import Any
13
+
14
+ from xtrom.core import Verdict
15
+
16
+ from xtrom_sdk import BlockedError, StepUpRequired
17
+
18
+ __all__ = [
19
+ "wrap_openai_tools",
20
+ "wrap_anthropic_tools",
21
+ "wrap_langchain_tool",
22
+ "wrap_crewai_tool",
23
+ ]
24
+
25
+
26
+ _MISSING = object()
27
+
28
+
29
+ def _get(obj: Any, key: str, default: Any = _MISSING) -> Any:
30
+ if isinstance(obj, Mapping):
31
+ return obj.get(key, default if default is not _MISSING else None)
32
+ return getattr(obj, key, default if default is not _MISSING else None)
33
+
34
+
35
+ def _loads_args(raw: Any) -> dict:
36
+ if raw in (None, ""):
37
+ return {}
38
+ if isinstance(raw, dict):
39
+ return raw
40
+ if isinstance(raw, str):
41
+ parsed = json.loads(raw)
42
+ if not isinstance(parsed, dict):
43
+ raise ValueError("tool arguments must decode to a JSON object")
44
+ return parsed
45
+ raise ValueError("tool arguments must be a dict or JSON object string")
46
+
47
+
48
+ def _jsonable(value: Any) -> str:
49
+ if isinstance(value, str):
50
+ return value
51
+ try:
52
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
53
+ except Exception: # noqa: BLE001 - result rendering must not break enforcement
54
+ return str(value)
55
+
56
+
57
+ def _source_for(name: str, sources: Any) -> bool:
58
+ if sources is None:
59
+ return False
60
+ if isinstance(sources, Mapping):
61
+ return bool(sources.get(name, False))
62
+ if isinstance(sources, (str, bytes)):
63
+ return name == str(sources)
64
+ return name in set(sources)
65
+
66
+
67
+ def _call_tool(func: Callable, args: dict) -> Any:
68
+ try:
69
+ return func(**args)
70
+ except TypeError:
71
+ if len(args) == 1:
72
+ return func(next(iter(args.values())))
73
+ raise
74
+
75
+
76
+ def _with_action_name(name: str, func: Callable) -> Callable:
77
+ try:
78
+ func.__name__ = name
79
+ except Exception:
80
+ pass
81
+ return func
82
+
83
+
84
+ def _with_arg_signature(func: Callable, names) -> Callable:
85
+ try:
86
+ params = [
87
+ inspect.Parameter(str(n), inspect.Parameter.KEYWORD_ONLY, default=None)
88
+ for n in names
89
+ ]
90
+ func.__signature__ = inspect.Signature(params) # type: ignore[attr-defined]
91
+ except Exception:
92
+ pass
93
+ return func
94
+
95
+
96
+ def _blocked_payload(action: str, reason: str, *, layer: str = "adapter", code: str = "xtrom.block") -> dict:
97
+ return {
98
+ "xtrom": {"verdict": "BLOCK", "action": action, "layer": layer, "reason": reason, "code": code},
99
+ "error": "Tool call denied by Xtrom.",
100
+ }
101
+
102
+
103
+ def _step_up_payload(exc: StepUpRequired) -> dict:
104
+ d = exc.decision
105
+ return {
106
+ "xtrom": {
107
+ "verdict": "STEP_UP",
108
+ "action": getattr(d, "action", ""),
109
+ "layer": getattr(d, "layer", ""),
110
+ "reason": getattr(d, "reason", ""),
111
+ "code": getattr(d, "reason_code", "") or "xtrom.step_up",
112
+ },
113
+ "error": "Tool call requires human approval.",
114
+ }
115
+
116
+
117
+ def _run_guarded(session, name: str, func: Callable, args: dict, *, source: bool, origin: str | None) -> Any:
118
+ ran = False
119
+
120
+ def invoke(**kwargs):
121
+ nonlocal ran
122
+ ran = True
123
+ return _call_tool(func, kwargs)
124
+
125
+ guarded = session.guard(source=source, origin=origin or f"tool:{name}")(
126
+ _with_arg_signature(_with_action_name(name, invoke), args.keys())
127
+ )
128
+ try:
129
+ return guarded(**args)
130
+ except (BlockedError, StepUpRequired):
131
+ raise
132
+ except Exception as exc:
133
+ if not ran:
134
+ # Anything that breaks adjudication fails closed. The tool has not run.
135
+ raise BlockedError(type("Decision", (), {
136
+ "verdict": Verdict.BLOCK,
137
+ "layer": "adapter:fail-closed",
138
+ "reason": f"adjudication failed: {exc.__class__.__name__}",
139
+ "action": name,
140
+ "reason_code": "xtrom.adjudication_error",
141
+ })()) from exc
142
+ raise
143
+
144
+
145
+ def _openai_parts(tool_call: Any) -> tuple[str, dict, str | None]:
146
+ fn = _get(tool_call, "function", {}) or {}
147
+ name = _get(fn, "name", None) or _get(tool_call, "name", None)
148
+ raw_args = _get(fn, "arguments", None)
149
+ if raw_args is None:
150
+ raw_args = _get(tool_call, "arguments", None)
151
+ if not name:
152
+ raise ValueError("OpenAI tool_call is missing a tool name")
153
+ return str(name), _loads_args(raw_args), _get(tool_call, "id", None)
154
+
155
+
156
+ def _anthropic_parts(tool_use: Any) -> tuple[str, dict, str | None]:
157
+ name = _get(tool_use, "name", None)
158
+ if not name:
159
+ raise ValueError("Anthropic tool_use is missing a tool name")
160
+ raw = _get(tool_use, "input", {}) or {}
161
+ return str(name), _loads_args(raw), _get(tool_use, "id", None)
162
+
163
+
164
+ def wrap_openai_tools(session, tools: dict[str, Callable], *, sources=(), origins: dict[str, str] | None = None,
165
+ return_message: bool = True):
166
+ """Return a dispatcher for OpenAI Chat Completions / Responses tool calls."""
167
+
168
+ def dispatch(tool_call):
169
+ name, args, call_id = _openai_parts(tool_call)
170
+ if name not in tools:
171
+ content = _jsonable(_blocked_payload(name, "unknown tool", code="xtrom.unknown_tool"))
172
+ else:
173
+ try:
174
+ result = _run_guarded(
175
+ session, name, tools[name], args, source=_source_for(name, sources),
176
+ origin=(origins or {}).get(name),
177
+ )
178
+ content = _jsonable(result)
179
+ except BlockedError as exc:
180
+ d = exc.decision
181
+ content = _jsonable(_blocked_payload(
182
+ getattr(d, "action", name), getattr(d, "reason", str(exc)),
183
+ layer=getattr(d, "layer", ""), code=getattr(d, "reason_code", "") or "xtrom.block",
184
+ ))
185
+ except StepUpRequired as exc:
186
+ content = _jsonable(_step_up_payload(exc))
187
+ if not return_message:
188
+ return content
189
+ msg = {"role": "tool", "name": name, "content": content}
190
+ if call_id:
191
+ msg["tool_call_id"] = call_id
192
+ return msg
193
+
194
+ return dispatch
195
+
196
+
197
+ def wrap_anthropic_tools(session, tools: dict[str, Callable], *, sources=(), origins: dict[str, str] | None = None):
198
+ """Return a dispatcher for Anthropic Messages `tool_use` blocks."""
199
+
200
+ def dispatch(tool_use):
201
+ name, args, use_id = _anthropic_parts(tool_use)
202
+ is_error = False
203
+ if name not in tools:
204
+ content = _jsonable(_blocked_payload(name, "unknown tool", code="xtrom.unknown_tool"))
205
+ is_error = True
206
+ else:
207
+ try:
208
+ result = _run_guarded(
209
+ session, name, tools[name], args, source=_source_for(name, sources),
210
+ origin=(origins or {}).get(name),
211
+ )
212
+ content = _jsonable(result)
213
+ except BlockedError as exc:
214
+ d = exc.decision
215
+ content = _jsonable(_blocked_payload(
216
+ getattr(d, "action", name), getattr(d, "reason", str(exc)),
217
+ layer=getattr(d, "layer", ""), code=getattr(d, "reason_code", "") or "xtrom.block",
218
+ ))
219
+ is_error = True
220
+ except StepUpRequired as exc:
221
+ content = _jsonable(_step_up_payload(exc))
222
+ is_error = True
223
+ block = {"type": "tool_result", "content": [{"type": "text", "text": content}], "is_error": is_error}
224
+ if use_id:
225
+ block["tool_use_id"] = use_id
226
+ return block
227
+
228
+ return dispatch
229
+
230
+
231
+ class _WrappedTool:
232
+ def __init__(self, session, tool, *, source: bool, origin: str | None, prefer: tuple[str, ...]):
233
+ self._xtrom_session = session
234
+ self._xtrom_tool = tool
235
+ self._xtrom_source = source
236
+ self._xtrom_origin = origin
237
+ self._xtrom_prefer = prefer
238
+ self.name = getattr(tool, "name", tool.__class__.__name__)
239
+ if hasattr(tool, "description"):
240
+ self.description = getattr(tool, "description")
241
+ if hasattr(tool, "args_schema"):
242
+ self.args_schema = getattr(tool, "args_schema")
243
+
244
+ def __getattr__(self, item):
245
+ return getattr(self._xtrom_tool, item)
246
+
247
+ def _target(self, preferred: str | None = None):
248
+ names = (preferred,) if preferred else self._xtrom_prefer
249
+ for attr in names:
250
+ if attr and callable(getattr(self._xtrom_tool, attr, None)):
251
+ return getattr(self._xtrom_tool, attr)
252
+ raise AttributeError(f"wrapped tool {self.name!r} has no callable interface")
253
+
254
+ def _call(self, method: str | None, *args, **kwargs):
255
+ target = self._target(method)
256
+ ran = False
257
+
258
+ flat_args = {}
259
+ if kwargs:
260
+ flat_args = dict(kwargs)
261
+ elif method == "invoke" and len(args) == 1 and isinstance(args[0], dict):
262
+ flat_args = dict(args[0])
263
+
264
+ def invoke(**flat):
265
+ nonlocal ran
266
+ ran = True
267
+ if flat_args:
268
+ if method == "invoke" and len(args) == 1 and isinstance(args[0], dict) and not kwargs:
269
+ return target(flat)
270
+ return target(**flat)
271
+ return target(*args, **kwargs)
272
+
273
+ guarded = self._xtrom_session.guard(
274
+ source=self._xtrom_source, origin=self._xtrom_origin or f"tool:{self.name}"
275
+ )(_with_arg_signature(_with_action_name(str(self.name), invoke), flat_args.keys()))
276
+ try:
277
+ if flat_args:
278
+ return guarded(**flat_args)
279
+ return guarded()
280
+ except (BlockedError, StepUpRequired):
281
+ raise
282
+ except Exception as exc:
283
+ if not ran:
284
+ raise BlockedError(type("Decision", (), {
285
+ "verdict": Verdict.BLOCK,
286
+ "layer": "adapter:fail-closed",
287
+ "reason": f"adjudication failed: {exc.__class__.__name__}",
288
+ "action": str(self.name),
289
+ "reason_code": "xtrom.adjudication_error",
290
+ })()) from exc
291
+ raise
292
+
293
+ def invoke(self, *args, **kwargs):
294
+ return self._call("invoke", *args, **kwargs)
295
+
296
+ def _run(self, *args, **kwargs):
297
+ return self._call("_run", *args, **kwargs)
298
+
299
+ def run(self, *args, **kwargs):
300
+ return self._call("run", *args, **kwargs)
301
+
302
+
303
+ def wrap_langchain_tool(session, tool, *, sources=(), source: bool | None = None, origin: str | None = None):
304
+ """Wrap a LangChain/LangGraph-style BaseTool without importing LangChain."""
305
+ name = getattr(tool, "name", tool.__class__.__name__)
306
+ return _WrappedTool(
307
+ session, tool,
308
+ source=_source_for(str(name), sources) if source is None else bool(source),
309
+ origin=origin,
310
+ prefer=("invoke", "_run", "run"),
311
+ )
312
+
313
+
314
+ def wrap_crewai_tool(session, tool, *, sources=(), source: bool | None = None, origin: str | None = None):
315
+ """Wrap a CrewAI-style BaseTool without importing CrewAI."""
316
+ name = getattr(tool, "name", tool.__class__.__name__)
317
+ return _WrappedTool(
318
+ session, tool,
319
+ source=_source_for(str(name), sources) if source is None else bool(source),
320
+ origin=origin,
321
+ prefer=("_run", "run", "invoke"),
322
+ )
@@ -0,0 +1,7 @@
1
+ """Anthropic tool-use adapter."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def wrap_anthropic_tools(*args, **kwargs):
6
+ from . import wrap_anthropic_tools as _impl
7
+ return _impl(*args, **kwargs)
@@ -0,0 +1,7 @@
1
+ """CrewAI tool adapter."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def wrap_crewai_tool(*args, **kwargs):
6
+ from . import wrap_crewai_tool as _impl
7
+ return _impl(*args, **kwargs)
@@ -0,0 +1,7 @@
1
+ """LangChain/LangGraph tool adapter."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def wrap_langchain_tool(*args, **kwargs):
6
+ from . import wrap_langchain_tool as _impl
7
+ return _impl(*args, **kwargs)
@@ -0,0 +1,7 @@
1
+ """OpenAI tool-call adapter."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def wrap_openai_tools(*args, **kwargs):
6
+ from . import wrap_openai_tools as _impl
7
+ return _impl(*args, **kwargs)
@@ -0,0 +1,52 @@
1
+ """Just-in-time AWS credentials from the Xtrom gateway (docs/design/JIT-BROKER.md in the Xtrom repo).
2
+
3
+ The agent asks its gateway for one of the roles its operator configured; the gateway checks it is a signed-in
4
+ agent allowed that role, assumes the role for this grant only, and returns short-lived credentials. Nothing is
5
+ stored here: call it when you need credentials, use them, let them expire (or Xtrom revokes them).
6
+
7
+ from xtrom_sdk.credentials import credentials
8
+ c = credentials("reader", ttl=900) # XTROM_GATEWAY_URL, XTROM_GATEWAY_TOKEN
9
+ s3 = boto3.client("s3", aws_access_key_id=c["AccessKeyId"],
10
+ aws_secret_access_key=c["SecretAccessKey"], aws_session_token=c["SessionToken"])
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import urllib.error
17
+ import urllib.request
18
+
19
+ from .reporter import require_secure_url, token_opener
20
+
21
+
22
+ class CredentialsError(Exception):
23
+ """The gateway refused or couldn't issue credentials (the message says why; it never contains a secret)."""
24
+
25
+
26
+ def credentials(role: str, ttl: int | None = None, gateway_url: str | None = None, token: str | None = None,
27
+ timeout: float = 10.0) -> dict:
28
+ """{AccessKeyId, SecretAccessKey, SessionToken, Expiration, grant} for `role`, issued to this agent."""
29
+ url = require_secure_url((gateway_url or os.environ.get("XTROM_GATEWAY_URL", "")).rstrip("/")) + "/v1/credentials"
30
+ tok = token or os.environ.get("XTROM_GATEWAY_TOKEN", "")
31
+ if not tok:
32
+ raise CredentialsError("no caller token: set XTROM_GATEWAY_TOKEN (credentials go only to a signed-in agent)")
33
+ body = {"role": role, **({"ttl": int(ttl)} if ttl else {})}
34
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
35
+ headers={"content-type": "application/json", "authorization": "Bearer " + tok})
36
+ try:
37
+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- scheme enforced by require_secure_url()
38
+ with token_opener.open(req, timeout=timeout) as r:
39
+ out = json.loads(r.read(64 << 10).decode())
40
+ except urllib.error.HTTPError as e:
41
+ try:
42
+ msg = json.loads(e.read(4096).decode()).get("message") or e.reason
43
+ except Exception: # noqa: BLE001
44
+ msg = e.reason
45
+ raise CredentialsError(f"the gateway refused ({e.code}): {msg}") from None
46
+ except (urllib.error.URLError, ValueError) as e:
47
+ raise CredentialsError(f"the gateway could not be reached: {e}") from None
48
+ c = dict(out.get("credentials") or {})
49
+ if not c.get("AccessKeyId"):
50
+ raise CredentialsError("the gateway returned no credentials")
51
+ c["grant"] = out.get("grant")
52
+ return c
xtrom_sdk/directive.py ADDED
@@ -0,0 +1,85 @@
1
+ """The signed enforcement directive, as an SDK checks it (control plane: app/directive.py; the gateway does the
2
+ same in settings_cache.go).
3
+
4
+ The ingest response carries `directive`: {payload (base64), kid, alg, sig}, ES256 over the canonical JSON of
5
+ {schema, tenant, enforcement_enabled, enforcement_kill_expires_at, workspace_mode, signed_at}. With
6
+ XTROM_POLICY_VERIFY_KEY (the PEM from GET /v1/signing-keys) and XTROM_TENANT set, the SDK takes the workspace
7
+ mode ONLY from a directive that verifies, is for this tenant, and is no older than the last one accepted.
8
+ Anything else means enforce: a response edited in transit can't switch an agent to monitor. Without the key
9
+ the mode is taken from the response over TLS, as before.
10
+
11
+ ES256 needs the optional `cryptography` package (`pip install xtrom-sdk[update]`). With a key configured and
12
+ the package missing, nothing verifies, so monitor is never honoured (fail safe).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import base64
17
+ import json
18
+ import os
19
+ import threading
20
+
21
+ SCHEMA = "xtrom.directive/1"
22
+
23
+
24
+ class DirectiveVerifier:
25
+ def __init__(self, public_key_pem: str, tenant: str, kid: str = "") -> None:
26
+ self._pem, self._tenant, self._kid = public_key_pem, tenant, kid
27
+ self._min_signed_at = 0
28
+ self._lock = threading.Lock()
29
+
30
+ def verify(self, envelope) -> dict | None:
31
+ """The verified payload, or None. Never raises, never parses unauthenticated bytes."""
32
+ try:
33
+ from cryptography.exceptions import InvalidSignature
34
+ from cryptography.hazmat.primitives import hashes
35
+ from cryptography.hazmat.primitives.asymmetric import ec
36
+ from cryptography.hazmat.primitives.serialization import load_pem_public_key
37
+ except Exception: # noqa: BLE001 — the optional extra is absent: nothing verifies
38
+ return None
39
+ try:
40
+ if not isinstance(envelope, dict) or envelope.get("alg") != "ES256":
41
+ return None
42
+ if self._kid and envelope.get("kid") != self._kid:
43
+ return None
44
+ payload = base64.b64decode(envelope["payload"], validate=True)
45
+ sig = base64.b64decode(envelope["sig"], validate=True)
46
+ try:
47
+ load_pem_public_key(self._pem.encode()).verify(sig, payload, ec.ECDSA(hashes.SHA256()))
48
+ except InvalidSignature:
49
+ return None
50
+ d = json.loads(payload.decode("utf-8"))
51
+ if not isinstance(d, dict) or d.get("schema") != SCHEMA or d.get("tenant") != self._tenant:
52
+ return None
53
+ signed_at = d.get("signed_at")
54
+ if not isinstance(signed_at, int):
55
+ return None
56
+ with self._lock:
57
+ if signed_at < self._min_signed_at:
58
+ return None # older than the one in force: a replay
59
+ self._min_signed_at = signed_at
60
+ return d
61
+ except Exception: # noqa: BLE001 — malformed → not verified
62
+ return None
63
+
64
+
65
+ _cached: tuple[tuple[str, str, str], DirectiveVerifier] | None = None
66
+
67
+
68
+ def from_env() -> DirectiveVerifier | None:
69
+ """The process's verifier from XTROM_POLICY_VERIFY_KEY (a PEM, or a path to one), XTROM_TENANT and the
70
+ optional XTROM_POLICY_VERIFY_KID, or None when no key is set. A key without a tenant can't bind the
71
+ directive to this workspace, so it verifies nothing (monitor is never honoured)."""
72
+ global _cached
73
+ raw = os.environ.get("XTROM_POLICY_VERIFY_KEY", "").strip()
74
+ if not raw:
75
+ return None
76
+ if not raw.startswith("-----BEGIN"):
77
+ try:
78
+ with open(raw, encoding="utf-8") as f:
79
+ raw = f.read()
80
+ except OSError:
81
+ raw = ""
82
+ key = (raw, os.environ.get("XTROM_TENANT", "").strip(), os.environ.get("XTROM_POLICY_VERIFY_KID", "").strip())
83
+ if _cached is None or _cached[0] != key:
84
+ _cached = (key, DirectiveVerifier(key[0], key[1] or "\0no-tenant", key[2]))
85
+ return _cached[1]
File without changes