limetry 1.2.99__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.
limetry/__init__.py ADDED
@@ -0,0 +1,101 @@
1
+ """
2
+ Public entry for the Limetry Python SDK.
3
+
4
+ Re-exports policy engine clients, typed policy/intent contracts, privacy
5
+ helpers for audit projections, and Limetry error classes.
6
+ """
7
+
8
+ from limetry.compatibility import COMPATIBILITY
9
+ from limetry.engine import (
10
+ AsyncRemotePolicyEngine,
11
+ RemotePolicyEngine,
12
+ create_async_remote_engine,
13
+ create_remote_engine,
14
+ )
15
+ from limetry.errors import (
16
+ EngineLoadError,
17
+ LimetryError,
18
+ PaymentInterceptionError,
19
+ PolicyViolationError,
20
+ RateLimitExceededError,
21
+ )
22
+ from limetry.policy.slim import create_slim_action_policy, create_slim_policy
23
+ from limetry.privacy.redact import (
24
+ DEFAULT_AUDIT_MODE,
25
+ AuditIntentProjection,
26
+ AuditMode,
27
+ build_evaluated_audit_details,
28
+ build_minimized_authorization_request,
29
+ build_minimized_authorization_response,
30
+ build_recorded_audit_details,
31
+ is_sensitive_key,
32
+ project_intent_for_audit,
33
+ redact_action_intent,
34
+ redact_details,
35
+ redact_metadata,
36
+ resolve_audit_mode,
37
+ scrub_embedded_secrets,
38
+ scrub_resource,
39
+ )
40
+ from limetry.urls import (
41
+ DEFAULT_LIMETRY_BASE_URL,
42
+ DEFAULT_LIMETRY_CLOUD_BASE_URL,
43
+ LIMETRY_CLOUD_APP_ORIGIN,
44
+ LIMETRY_CLOUD_ORIGINS,
45
+ LIMETRY_OSS_ORIGINS,
46
+ resolve_limetry_base_url,
47
+ resolve_limetry_cloud_base_url,
48
+ )
49
+ from limetry.version import (
50
+ APP_VERSION,
51
+ AppVersion,
52
+ AppVersionChannel,
53
+ AppVersionInfo,
54
+ app_version,
55
+ format_app_version_label,
56
+ resolve_app_version,
57
+ )
58
+
59
+ __all__ = [
60
+ "APP_VERSION",
61
+ "AppVersion",
62
+ "AppVersionChannel",
63
+ "AppVersionInfo",
64
+ "AsyncRemotePolicyEngine",
65
+ "AuditIntentProjection",
66
+ "AuditMode",
67
+ "COMPATIBILITY",
68
+ "DEFAULT_AUDIT_MODE",
69
+ "DEFAULT_LIMETRY_BASE_URL",
70
+ "DEFAULT_LIMETRY_CLOUD_BASE_URL",
71
+ "EngineLoadError",
72
+ "LIMETRY_CLOUD_APP_ORIGIN",
73
+ "LIMETRY_CLOUD_ORIGINS",
74
+ "LIMETRY_OSS_ORIGINS",
75
+ "LimetryError",
76
+ "PaymentInterceptionError",
77
+ "PolicyViolationError",
78
+ "RateLimitExceededError",
79
+ "RemotePolicyEngine",
80
+ "app_version",
81
+ "build_evaluated_audit_details",
82
+ "build_minimized_authorization_request",
83
+ "build_minimized_authorization_response",
84
+ "build_recorded_audit_details",
85
+ "create_async_remote_engine",
86
+ "create_remote_engine",
87
+ "create_slim_action_policy",
88
+ "create_slim_policy",
89
+ "format_app_version_label",
90
+ "is_sensitive_key",
91
+ "project_intent_for_audit",
92
+ "redact_action_intent",
93
+ "redact_details",
94
+ "redact_metadata",
95
+ "resolve_app_version",
96
+ "resolve_audit_mode",
97
+ "resolve_limetry_base_url",
98
+ "resolve_limetry_cloud_base_url",
99
+ "scrub_embedded_secrets",
100
+ "scrub_resource",
101
+ ]
limetry/_build_info.py ADDED
@@ -0,0 +1,9 @@
1
+ """Embedded build metadata. Regenerated by scripts/embed_build_info.py."""
2
+
3
+ BUILD_INFO = {
4
+ "version": "1.2.100",
5
+ "build": 10,
6
+ "builtAt": "2026-11-22T23:26:31.353Z",
7
+ "contentHash": "sha256:13947e15403153ab345aef154bf4583890427b4642f6311b2b8333de8a1025f6",
8
+ "gitSha": "8e62639"
9
+ }
@@ -0,0 +1,25 @@
1
+ """Product, package, website, and schema compatibility for this release."""
2
+
3
+ COMPATIBILITY = {
4
+ "product": "1.2.99",
5
+ "compatibleProduct": ">=1.2.0 <1.3.0",
6
+ "packages": {
7
+ "@limetry/ci": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
8
+ "@limetry/cli": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
9
+ "@limetry/mcp": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
10
+ "@limetry/preflight": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
11
+ "@limetry/sdk": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
12
+ "@limetry/shopify": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
13
+ "@limetry/sql": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
14
+ "@limetry/ui": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
15
+ "limetry": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
16
+ },
17
+ "websites": {
18
+ "@limetry/web": {"version": "1.2.99", "compatible": ">=1.2.0 <1.3.0"},
19
+ },
20
+ "schemas": {
21
+ "openapi.evaluate": {"version": "1.0.5", "compatible": ">=1.0.0 <2.0.0"},
22
+ "openapi.custom-gpt": {"version": "1.0.0", "compatible": ">=1.0.0 <2.0.0"},
23
+ "json.evaluate": {"version": "1.0.0", "compatible": ">=1.0.0 <2.0.0"},
24
+ },
25
+ }
limetry/engine.py ADDED
@@ -0,0 +1,249 @@
1
+ """HTTPS policy engine that delegates action evaluation to a Limetry server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Mapping
7
+
8
+ import httpx
9
+
10
+ from limetry.errors import EngineLoadError
11
+ from limetry.types import ActionEvaluationResponse, ActionIntent
12
+ from limetry.urls import resolve_limetry_base_url
13
+
14
+
15
+ class RemotePolicyEngine:
16
+ """Synchronous remote policy engine using httpx."""
17
+
18
+ def __init__(
19
+ self,
20
+ *,
21
+ api_key: str,
22
+ base_url: str | None = None,
23
+ tenant_id: str = "default",
24
+ client: httpx.Client | None = None,
25
+ env: Mapping[str, str] | None = None,
26
+ ) -> None:
27
+ source = env if env is not None else os.environ
28
+ self.base_url = resolve_limetry_base_url(source, base_url)
29
+ self.api_key = api_key
30
+ self.tenant_id = tenant_id
31
+ self._client = client
32
+ self._owns_client = client is None
33
+
34
+ def _get_client(self) -> httpx.Client:
35
+ if self._client is None:
36
+ self._client = httpx.Client(timeout=30.0)
37
+ return self._client
38
+
39
+ def _headers(self) -> dict[str, str]:
40
+ return {
41
+ "Authorization": f"Bearer {self.api_key}",
42
+ "Content-Type": "application/json",
43
+ }
44
+
45
+ def evaluate_action(self, intent: ActionIntent) -> ActionEvaluationResponse:
46
+ """Evaluate an ActionIntent via POST /v1/policy/evaluate."""
47
+ url = f"{self.base_url}/v1/policy/evaluate"
48
+ body = {
49
+ "tenant_id": self.tenant_id,
50
+ "policy_id": intent["policy_id"],
51
+ "intent": intent,
52
+ }
53
+ response = self._get_client().post(url, json=body, headers=self._headers())
54
+ if response.status_code >= 400:
55
+ raise EngineLoadError(
56
+ f"Limetry remote engine error ({response.status_code}): {response.text}",
57
+ )
58
+ return response.json() # type: ignore[return-value]
59
+
60
+ def upsert_policy(self, policy: Mapping[str, Any]) -> None:
61
+ """Thin helper: PUT /v1/policies/{policy_id} for example bootstrap flows."""
62
+ policy_id = policy["policy_id"]
63
+ url = f"{self.base_url}/v1/policies/{policy_id}"
64
+ body = {"tenant_id": self.tenant_id, "policy": policy}
65
+ response = self._get_client().put(url, json=body, headers=self._headers())
66
+ if response.status_code not in (200, 201):
67
+ raise EngineLoadError(
68
+ f"Limetry policy upsert failed ({response.status_code}): {response.text}",
69
+ )
70
+
71
+ def record_action(
72
+ self,
73
+ intent: ActionIntent,
74
+ *,
75
+ decision_id: str,
76
+ outcome: str,
77
+ ) -> None:
78
+ """Thin helper: POST /v1/actions/record for example audit flows."""
79
+ url = f"{self.base_url}/v1/actions/record"
80
+ body = {
81
+ "tenant_id": self.tenant_id,
82
+ "intent": intent,
83
+ "decision_id": decision_id,
84
+ "outcome": outcome,
85
+ }
86
+ response = self._get_client().post(url, json=body, headers=self._headers())
87
+ if response.status_code not in (200, 201):
88
+ raise EngineLoadError(
89
+ f"Limetry action record failed ({response.status_code}): {response.text}",
90
+ )
91
+
92
+ def close(self) -> None:
93
+ if self._owns_client and self._client is not None:
94
+ self._client.close()
95
+ self._client = None
96
+
97
+ def __enter__(self) -> RemotePolicyEngine:
98
+ return self
99
+
100
+ def __exit__(self, *args: object) -> None:
101
+ self.close()
102
+
103
+
104
+ class AsyncRemotePolicyEngine:
105
+ """Async remote policy engine using httpx.AsyncClient."""
106
+
107
+ def __init__(
108
+ self,
109
+ *,
110
+ api_key: str,
111
+ base_url: str | None = None,
112
+ tenant_id: str = "default",
113
+ client: httpx.AsyncClient | None = None,
114
+ env: Mapping[str, str] | None = None,
115
+ ) -> None:
116
+ source = env if env is not None else os.environ
117
+ self.base_url = resolve_limetry_base_url(source, base_url)
118
+ self.api_key = api_key
119
+ self.tenant_id = tenant_id
120
+ self._client = client
121
+ self._owns_client = client is None
122
+
123
+ def _headers(self) -> dict[str, str]:
124
+ return {
125
+ "Authorization": f"Bearer {self.api_key}",
126
+ "Content-Type": "application/json",
127
+ }
128
+
129
+ async def _get_client(self) -> httpx.AsyncClient:
130
+ if self._client is None:
131
+ self._client = httpx.AsyncClient(timeout=30.0)
132
+ return self._client
133
+
134
+ async def evaluate_action(self, intent: ActionIntent) -> ActionEvaluationResponse:
135
+ """Evaluate an ActionIntent via POST /v1/policy/evaluate."""
136
+ url = f"{self.base_url}/v1/policy/evaluate"
137
+ body = {
138
+ "tenant_id": self.tenant_id,
139
+ "policy_id": intent["policy_id"],
140
+ "intent": intent,
141
+ }
142
+ client = await self._get_client()
143
+ response = await client.post(url, json=body, headers=self._headers())
144
+ if response.status_code >= 400:
145
+ raise EngineLoadError(
146
+ f"Limetry remote engine error ({response.status_code}): {response.text}",
147
+ )
148
+ return response.json() # type: ignore[return-value]
149
+
150
+ async def upsert_policy(self, policy: Mapping[str, Any]) -> None:
151
+ """Thin helper: PUT /v1/policies/{policy_id} for example bootstrap flows."""
152
+ policy_id = policy["policy_id"]
153
+ url = f"{self.base_url}/v1/policies/{policy_id}"
154
+ body = {"tenant_id": self.tenant_id, "policy": policy}
155
+ client = await self._get_client()
156
+ response = await client.put(url, json=body, headers=self._headers())
157
+ if response.status_code not in (200, 201):
158
+ raise EngineLoadError(
159
+ f"Limetry policy upsert failed ({response.status_code}): {response.text}",
160
+ )
161
+
162
+ async def record_action(
163
+ self,
164
+ intent: ActionIntent,
165
+ *,
166
+ decision_id: str,
167
+ outcome: str,
168
+ ) -> None:
169
+ """Thin helper: POST /v1/actions/record for example audit flows."""
170
+ url = f"{self.base_url}/v1/actions/record"
171
+ body = {
172
+ "tenant_id": self.tenant_id,
173
+ "intent": intent,
174
+ "decision_id": decision_id,
175
+ "outcome": outcome,
176
+ }
177
+ client = await self._get_client()
178
+ response = await client.post(url, json=body, headers=self._headers())
179
+ if response.status_code not in (200, 201):
180
+ raise EngineLoadError(
181
+ f"Limetry action record failed ({response.status_code}): {response.text}",
182
+ )
183
+
184
+ async def aclose(self) -> None:
185
+ if self._owns_client and self._client is not None:
186
+ await self._client.aclose()
187
+ self._client = None
188
+
189
+ async def __aenter__(self) -> AsyncRemotePolicyEngine:
190
+ return self
191
+
192
+ async def __aexit__(self, *args: object) -> None:
193
+ await self.aclose()
194
+
195
+
196
+ def _resolve_api_key(
197
+ overrides: Mapping[str, Any] | None,
198
+ env: Mapping[str, str],
199
+ ) -> str:
200
+ if overrides and overrides.get("api_key"):
201
+ return str(overrides["api_key"])
202
+ api_key = env.get("LIMETRY_API_KEY") or env.get("LIMETRY_BEARER_TOKEN")
203
+ if not api_key:
204
+ raise EngineLoadError(
205
+ "No Limetry API key found. Set LIMETRY_API_KEY or run `limetry setup`.",
206
+ )
207
+ return api_key
208
+
209
+
210
+ def create_remote_engine(
211
+ *,
212
+ api_key: str | None = None,
213
+ base_url: str | None = None,
214
+ tenant_id: str = "default",
215
+ client: httpx.Client | None = None,
216
+ env: Mapping[str, str] | None = None,
217
+ ) -> RemotePolicyEngine:
218
+ """Create a sync RemotePolicyEngine from options and environment variables."""
219
+ source = env if env is not None else os.environ
220
+ overrides = {"api_key": api_key} if api_key else None
221
+ resolved_key = _resolve_api_key(overrides, source)
222
+ return RemotePolicyEngine(
223
+ api_key=resolved_key,
224
+ base_url=resolve_limetry_base_url(source, base_url),
225
+ tenant_id=tenant_id,
226
+ client=client,
227
+ env=source,
228
+ )
229
+
230
+
231
+ def create_async_remote_engine(
232
+ *,
233
+ api_key: str | None = None,
234
+ base_url: str | None = None,
235
+ tenant_id: str = "default",
236
+ client: httpx.AsyncClient | None = None,
237
+ env: Mapping[str, str] | None = None,
238
+ ) -> AsyncRemotePolicyEngine:
239
+ """Create an async AsyncRemotePolicyEngine from options and environment variables."""
240
+ source = env if env is not None else os.environ
241
+ overrides = {"api_key": api_key} if api_key else None
242
+ resolved_key = _resolve_api_key(overrides, source)
243
+ return AsyncRemotePolicyEngine(
244
+ api_key=resolved_key,
245
+ base_url=resolve_limetry_base_url(source, base_url),
246
+ tenant_id=tenant_id,
247
+ client=client,
248
+ env=source,
249
+ )
limetry/errors.py ADDED
@@ -0,0 +1,53 @@
1
+ """Error classes thrown by the Limetry Python SDK."""
2
+
3
+
4
+ class LimetryError(Exception):
5
+ """Base error for Limetry SDK failures with a stable machine-readable code."""
6
+
7
+ def __init__(self, code: str, message: str) -> None:
8
+ super().__init__(message)
9
+ self.code = code
10
+ self.name = "LimetryError"
11
+
12
+
13
+ class PolicyViolationError(LimetryError):
14
+ """Raised when policy evaluation rejects an intent."""
15
+
16
+ def __init__(self, violation: dict[str, object]) -> None:
17
+ raw_code = violation.get("code")
18
+ code = raw_code if isinstance(raw_code, str) else "policy_violation"
19
+ super().__init__(code, f"Policy violation: {code}")
20
+ self.name = "PolicyViolationError"
21
+ self.violation = violation
22
+
23
+
24
+ class RateLimitExceededError(LimetryError):
25
+ """Raised when a client-side velocity circuit breaker blocks a transaction."""
26
+
27
+ def __init__(self, cooldown_period_ms: int, elapsed_ms: int) -> None:
28
+ super().__init__(
29
+ "rate_limit_exceeded",
30
+ (
31
+ "Transaction blocked by client velocity circuit breaker. "
32
+ f"Cooldown {cooldown_period_ms}ms, elapsed {elapsed_ms}ms"
33
+ ),
34
+ )
35
+ self.name = "RateLimitExceededError"
36
+ self.cooldown_period_ms = cooldown_period_ms
37
+ self.elapsed_ms = elapsed_ms
38
+
39
+
40
+ class EngineLoadError(LimetryError):
41
+ """Raised when a remote policy engine fails to load or respond."""
42
+
43
+ def __init__(self, message: str) -> None:
44
+ super().__init__("engine_load_error", message)
45
+ self.name = "EngineLoadError"
46
+
47
+
48
+ class PaymentInterceptionError(LimetryError):
49
+ """Raised when payment tool interception cannot proceed safely."""
50
+
51
+ def __init__(self, message: str) -> None:
52
+ super().__init__("payment_interception_error", message)
53
+ self.name = "PaymentInterceptionError"
File without changes
limetry/policy/slim.py ADDED
@@ -0,0 +1,155 @@
1
+ """Helpers that expand a small set of limits into full Limetry policy documents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Literal, TypedDict
7
+ from uuid import uuid4
8
+
9
+ from limetry.types import ActionPolicy, SpendingPolicy
10
+
11
+
12
+ class SlimPolicyInput(TypedDict, total=False):
13
+ agent_id: str
14
+ organization_id: str
15
+ max_single_transaction_minor: int
16
+ max_daily_spend_minor: int
17
+ max_monthly_spend_minor: int
18
+ currency: str
19
+ max_transactions_per_minute: int
20
+ allowed_merchant_ids: list[str]
21
+ policy_id: str
22
+
23
+
24
+ class SlimActionPolicyInput(TypedDict, total=False):
25
+ agent_id: str
26
+ organization_id: str
27
+ allowed_action_types: list[str]
28
+ denied_action_types: list[str]
29
+ allowed_resource_patterns: list[str]
30
+ blocked_resource_patterns: list[str]
31
+ max_cost_minor: int
32
+ currency: str
33
+ policy_id: str
34
+ audit_mode: Literal["minimal", "forensics"]
35
+ require_approval_action_types: list[str]
36
+ require_approval_resource_patterns: list[str]
37
+ approval_cost_minor: int
38
+
39
+
40
+ def _now_iso() -> str:
41
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
42
+
43
+
44
+ def create_slim_policy(
45
+ *,
46
+ agent_id: str,
47
+ max_single_transaction_minor: int,
48
+ max_daily_spend_minor: int,
49
+ organization_id: str = "default",
50
+ max_monthly_spend_minor: int | None = None,
51
+ currency: str = "USD",
52
+ max_transactions_per_minute: int = 10,
53
+ allowed_merchant_ids: list[str] | None = None,
54
+ policy_id: str | None = None,
55
+ ) -> SpendingPolicy:
56
+ """Build a full SpendingPolicy from a small set of limits."""
57
+ resolved_policy_id = policy_id or str(uuid4())
58
+ now = _now_iso()
59
+ allowed = allowed_merchant_ids or []
60
+ max_single = max_single_transaction_minor
61
+ max_daily = max_daily_spend_minor
62
+ max_monthly = max_monthly_spend_minor if max_monthly_spend_minor is not None else max_daily * 30
63
+
64
+ return {
65
+ "policy_id": resolved_policy_id,
66
+ "version": 1,
67
+ "organization_id": organization_id,
68
+ "agent_id": agent_id,
69
+ "limits": {
70
+ "max_single_transaction_minor": max_single,
71
+ "max_daily_spend_minor": max_daily,
72
+ "max_monthly_spend_minor": max_monthly,
73
+ "currency": currency,
74
+ },
75
+ "velocity": {
76
+ "max_transactions_per_minute": max_transactions_per_minute,
77
+ "max_transactions_per_hour": max_transactions_per_minute * 20,
78
+ "max_transactions_per_day": max_transactions_per_minute * 100,
79
+ "max_aggregate_amount_per_hour_minor": min(max_daily, max_single * 20),
80
+ },
81
+ "replay": {
82
+ "nonce_window_seconds": 300,
83
+ "max_clock_skew_seconds": 300,
84
+ "require_monotonic_nonce": True,
85
+ },
86
+ "isolation": {
87
+ "max_concurrent_pending_intents": 5,
88
+ "max_pending_aggregate_minor": max_single * 5,
89
+ "intent_ttl_seconds": 300,
90
+ "enforce_unique_payee_per_intent_batch": True,
91
+ },
92
+ "destination_rules": {
93
+ "allowed_merchant_ids": allowed,
94
+ "allowed_mcc_codes": [],
95
+ "blocked_merchant_ids": [],
96
+ "require_merchant_allowlist": len(allowed) > 0,
97
+ },
98
+ "effective_window": {
99
+ "effective_from": now,
100
+ "expires_at": None,
101
+ },
102
+ "status": "active",
103
+ "updated_at": now,
104
+ }
105
+
106
+
107
+ def create_slim_action_policy(
108
+ *,
109
+ agent_id: str,
110
+ allowed_action_types: list[str],
111
+ organization_id: str = "default",
112
+ denied_action_types: list[str] | None = None,
113
+ allowed_resource_patterns: list[str] | None = None,
114
+ blocked_resource_patterns: list[str] | None = None,
115
+ max_cost_minor: int | None = None,
116
+ currency: str | None = None,
117
+ policy_id: str | None = None,
118
+ audit_mode: Literal["minimal", "forensics"] = "minimal",
119
+ require_approval_action_types: list[str] | None = None,
120
+ require_approval_resource_patterns: list[str] | None = None,
121
+ approval_cost_minor: int | None = None,
122
+ ) -> ActionPolicy:
123
+ """Build a generic ActionPolicy from a small set of action constraints."""
124
+ resolved_policy_id = policy_id or str(uuid4())
125
+ now = _now_iso()
126
+
127
+ policy: ActionPolicy = {
128
+ "policy_id": resolved_policy_id,
129
+ "version": 1,
130
+ "organization_id": organization_id,
131
+ "agent_id": agent_id,
132
+ "allowed_action_types": allowed_action_types,
133
+ "audit_mode": audit_mode,
134
+ "status": "active",
135
+ "updated_at": now,
136
+ "effective_from": now,
137
+ "expires_at": None,
138
+ }
139
+ if denied_action_types is not None:
140
+ policy["denied_action_types"] = denied_action_types
141
+ if allowed_resource_patterns is not None:
142
+ policy["allowed_resource_patterns"] = allowed_resource_patterns
143
+ if blocked_resource_patterns is not None:
144
+ policy["blocked_resource_patterns"] = blocked_resource_patterns
145
+ if max_cost_minor is not None:
146
+ policy["max_cost_minor"] = max_cost_minor
147
+ if currency is not None:
148
+ policy["currency"] = currency
149
+ if require_approval_action_types is not None:
150
+ policy["require_approval_action_types"] = require_approval_action_types
151
+ if require_approval_resource_patterns is not None:
152
+ policy["require_approval_resource_patterns"] = require_approval_resource_patterns
153
+ if approval_cost_minor is not None:
154
+ policy["approval_cost_minor"] = approval_cost_minor
155
+ return policy
File without changes