em-runtime-governance-sdk 0.1.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.
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: em-runtime-governance-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Emergence runtime governance layer — policy, approval gates, audit, budget caps, PII redaction.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # em-runtime-governance-sdk
11
+
12
+ `em-runtime-governance-sdk` is the Python SDK for the governance layer of the [Emergence](https://emergence.ai) runtime. It lets you attach policy, approvals, and audit to agent runs and tool calls so that autonomous workflows stay within organizational and regulatory boundaries. Pair it with `em-runtime-assets-sdk-python` for asset management and `em-runtime-utils-sdk-python` for shared helpers.
13
+
14
+ ## Features
15
+
16
+ - Declarative policy definitions for allowed tools, models, and data sources.
17
+ - Pre-run approval gates with synchronous, async, and timeout escalation.
18
+ - Per-decision audit records with immutable, signed logs.
19
+ - Budget and rate caps at the agent, run, and tenant level.
20
+ - PII and secret redaction hooks applied before model calls.
21
+ - Works with the Emergence runtime or any OpenTelemetry-instrumented host.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install em-runtime-governance-sdk
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ from em_runtime_governance_sdk import GovernanceClient, Policy
33
+
34
+ client = GovernanceClient(api_key="em_live_...")
35
+
36
+ policy = Policy(
37
+ name="support-tier-1",
38
+ allowed_tools=["kb_search", "refund_issue"],
39
+ max_cost_usd_per_run=2.0,
40
+ require_approval_for=["refund_issue"],
41
+ )
42
+ client.policies.upsert(policy)
43
+
44
+ decision = client.evaluate(run_id="run_42", action="refund_issue", amount=15)
45
+ if not decision.allowed:
46
+ raise PermissionError(decision.reason)
47
+ ```
48
+
49
+ ## API
50
+
51
+ - `GovernanceClient(api_key=...)` — entry point; `policies`, `evaluations`, `audit` namespaces.
52
+ - `Policy(...)` — declarative rules object, versioned and upsertable.
53
+ - `client.evaluate(run_id, action, **context)` — return an `Evaluation` with `allowed` and `reason`.
54
+ - `client.approvals.request(run_id, action)` — open a human approval gate.
55
+
56
+ ## Configuration
57
+
58
+ Set `EM_RUNTIME_API_KEY` and optionally `EM_RUNTIME_BASE_URL` for a self-hosted runtime.
59
+
60
+ ## License
61
+
62
+ MIT
@@ -0,0 +1,53 @@
1
+ # em-runtime-governance-sdk
2
+
3
+ `em-runtime-governance-sdk` is the Python SDK for the governance layer of the [Emergence](https://emergence.ai) runtime. It lets you attach policy, approvals, and audit to agent runs and tool calls so that autonomous workflows stay within organizational and regulatory boundaries. Pair it with `em-runtime-assets-sdk-python` for asset management and `em-runtime-utils-sdk-python` for shared helpers.
4
+
5
+ ## Features
6
+
7
+ - Declarative policy definitions for allowed tools, models, and data sources.
8
+ - Pre-run approval gates with synchronous, async, and timeout escalation.
9
+ - Per-decision audit records with immutable, signed logs.
10
+ - Budget and rate caps at the agent, run, and tenant level.
11
+ - PII and secret redaction hooks applied before model calls.
12
+ - Works with the Emergence runtime or any OpenTelemetry-instrumented host.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install em-runtime-governance-sdk
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ ```python
23
+ from em_runtime_governance_sdk import GovernanceClient, Policy
24
+
25
+ client = GovernanceClient(api_key="em_live_...")
26
+
27
+ policy = Policy(
28
+ name="support-tier-1",
29
+ allowed_tools=["kb_search", "refund_issue"],
30
+ max_cost_usd_per_run=2.0,
31
+ require_approval_for=["refund_issue"],
32
+ )
33
+ client.policies.upsert(policy)
34
+
35
+ decision = client.evaluate(run_id="run_42", action="refund_issue", amount=15)
36
+ if not decision.allowed:
37
+ raise PermissionError(decision.reason)
38
+ ```
39
+
40
+ ## API
41
+
42
+ - `GovernanceClient(api_key=...)` — entry point; `policies`, `evaluations`, `audit` namespaces.
43
+ - `Policy(...)` — declarative rules object, versioned and upsertable.
44
+ - `client.evaluate(run_id, action, **context)` — return an `Evaluation` with `allowed` and `reason`.
45
+ - `client.approvals.request(run_id, action)` — open a human approval gate.
46
+
47
+ ## Configuration
48
+
49
+ Set `EM_RUNTIME_API_KEY` and optionally `EM_RUNTIME_BASE_URL` for a self-hosted runtime.
50
+
51
+ ## License
52
+
53
+ MIT
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "em-runtime-governance-sdk"
7
+ version = "0.1.0"
8
+ description = "Python SDK for the Emergence runtime governance layer — policy, approval gates, audit, budget caps, PII redaction."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ authors = [{name = ""}]
13
+
14
+ [project.scripts]
15
+ em-runtime-governance-sdk = "em_runtime_governance_sdk.cli:main"
16
+
17
+ [tool.setuptools.packages.find]
18
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,294 @@
1
+ """em-runtime-governance-sdk — Python SDK for the Emergence runtime governance layer.
2
+
3
+ Attach policy, approvals, and audit to agent runs and tool calls so that
4
+ autonomous workflows stay within organizational and regulatory boundaries.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import time
11
+ import uuid
12
+ from dataclasses import dataclass, field, asdict
13
+ from typing import Any, Callable
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ __all__ = [
18
+ "GovernanceClient",
19
+ "Policy",
20
+ "Evaluation",
21
+ "Approval",
22
+ "AuditRecord",
23
+ "GovernanceError",
24
+ ]
25
+
26
+
27
+ class GovernanceError(Exception):
28
+ """Raised when a governance operation fails."""
29
+
30
+
31
+ @dataclass
32
+ class Policy:
33
+ """A declarative, versioned policy definition.
34
+
35
+ Args:
36
+ name: Policy name (unique within a tenant).
37
+ allowed_tools: Tools that may be invoked under this policy.
38
+ allowed_models: Models that may be invoked under this policy.
39
+ allowed_data_sources: Data sources that may be read.
40
+ max_cost_usd_per_run: Per-run spend cap.
41
+ require_approval_for: Tools that require a human approval gate.
42
+ pii_redaction: When True, PII is redacted before model calls.
43
+ version: Policy version. Bumped automatically on :meth:`upsert`.
44
+ """
45
+
46
+ name: str
47
+ allowed_tools: list[str] = field(default_factory=list)
48
+ allowed_models: list[str] = field(default_factory=list)
49
+ allowed_data_sources: list[str] = field(default_factory=list)
50
+ max_cost_usd_per_run: float | None = None
51
+ require_approval_for: list[str] = field(default_factory=list)
52
+ pii_redaction: bool = False
53
+ version: int = 1
54
+
55
+ def __post_init__(self) -> None:
56
+ if not self.name:
57
+ raise GovernanceError("policy name is required")
58
+
59
+ def to_dict(self) -> dict[str, Any]:
60
+ return asdict(self)
61
+
62
+
63
+ @dataclass
64
+ class Evaluation:
65
+ """The outcome of evaluating a policy against an action.
66
+
67
+ Attributes:
68
+ allowed: Whether the action is permitted.
69
+ reason: Human-readable explanation.
70
+ run_id: The run id the evaluation was scoped to.
71
+ action: The action that was evaluated.
72
+ policy_name: The policy that produced the decision.
73
+ approval_required: When True, the action needs a human approval.
74
+ """
75
+
76
+ allowed: bool
77
+ reason: str
78
+ run_id: str
79
+ action: str
80
+ policy_name: str
81
+ approval_required: bool = False
82
+
83
+
84
+ @dataclass
85
+ class Approval:
86
+ """An open or resolved human approval gate."""
87
+
88
+ approval_id: str
89
+ run_id: str
90
+ action: str
91
+ status: str = "pending" # pending | approved | denied | expired
92
+
93
+ def resolve(self, status: str) -> None:
94
+ if status not in ("approved", "denied", "expired"):
95
+ raise GovernanceError(f"invalid approval status: {status!r}")
96
+ self.status = status
97
+
98
+
99
+ @dataclass
100
+ class AuditRecord:
101
+ """An immutable, signed audit record of a governance decision."""
102
+
103
+ record_id: str
104
+ run_id: str
105
+ action: str
106
+ decision: str
107
+ reason: str
108
+ timestamp: float = field(default_factory=time.time)
109
+ signature: str = ""
110
+
111
+ def to_dict(self) -> dict[str, Any]:
112
+ return asdict(self)
113
+
114
+
115
+ class _PolicyNamespace:
116
+ """``client.policies`` namespace."""
117
+
118
+ def __init__(self, client: "GovernanceClient") -> None:
119
+ self._client = client
120
+
121
+ def upsert(self, policy: Policy) -> Policy:
122
+ """Create or update a policy (bumps version on update)."""
123
+ if not isinstance(policy, Policy):
124
+ raise GovernanceError("policy must be a Policy instance")
125
+ existing = self._client._policies.get(policy.name)
126
+ if existing is not None:
127
+ policy.version = existing.version + 1
128
+ self._client._policies[policy.name] = policy
129
+ return policy
130
+
131
+ def get(self, name: str) -> Policy:
132
+ """Retrieve a policy by name."""
133
+ if name not in self._client._policies:
134
+ raise GovernanceError(f"policy {name!r} not found")
135
+ return self._client._policies[name]
136
+
137
+ def list(self) -> list[Policy]:
138
+ return list(self._client._policies.values())
139
+
140
+
141
+ class _ApprovalNamespace:
142
+ """``client.approvals`` namespace."""
143
+
144
+ def __init__(self, client: "GovernanceClient") -> None:
145
+ self._client = client
146
+
147
+ def request(self, run_id: str, action: str, *, timeout_s: float = 0.0) -> Approval:
148
+ """Open a human approval gate for ``action`` on ``run_id``."""
149
+ approval = Approval(approval_id=f"appr_{uuid.uuid4().hex[:12]}", run_id=run_id, action=action)
150
+ self._client._approvals[approval.approval_id] = approval
151
+ return approval
152
+
153
+ def resolve(self, approval_id: str, status: str) -> Approval:
154
+ """Resolve a pending approval."""
155
+ if approval_id not in self._client._approvals:
156
+ raise GovernanceError(f"approval {approval_id!r} not found")
157
+ approval = self._client._approvals[approval_id]
158
+ approval.resolve(status)
159
+ return approval
160
+
161
+
162
+ class _AuditNamespace:
163
+ """``client.audit`` namespace."""
164
+
165
+ def __init__(self, client: "GovernanceClient") -> None:
166
+ self._client = client
167
+
168
+ def list(self, run_id: str | None = None) -> list[AuditRecord]:
169
+ records = self._client._audit
170
+ if run_id is not None:
171
+ records = [r for r in records if r.run_id == run_id]
172
+ return list(records)
173
+
174
+
175
+ class GovernanceClient:
176
+ """Entry point for the Emergence governance layer.
177
+
178
+ Args:
179
+ api_key: Emergence API key. Falls back to ``EM_RUNTIME_API_KEY``.
180
+ base_url: Self-hosted runtime URL (defaults to ``EM_RUNTIME_BASE_URL``
181
+ or the hosted endpoint).
182
+ transport: Optional callable ``transport(method, path, body) -> dict``
183
+ used by tests to avoid the network.
184
+ """
185
+
186
+ def __init__(
187
+ self,
188
+ api_key: str | None = None,
189
+ *,
190
+ base_url: str | None = None,
191
+ transport: Callable[[str, str, dict[str, Any]], dict[str, Any]] | None = None,
192
+ ) -> None:
193
+ self.api_key = api_key or os.environ.get("EM_RUNTIME_API_KEY")
194
+ if not self.api_key:
195
+ raise GovernanceError("api_key is required (or set EM_RUNTIME_API_KEY)")
196
+ self.base_url = base_url or os.environ.get(
197
+ "EM_RUNTIME_BASE_URL", "https://api.emergence.ai"
198
+ )
199
+ self._transport = transport
200
+ self._policies: dict[str, Policy] = {}
201
+ self._approvals: dict[str, Approval] = {}
202
+ self._audit: list[AuditRecord] = []
203
+ self.policies = _PolicyNamespace(self)
204
+ self.approvals = _ApprovalNamespace(self)
205
+ self.audit = _AuditNamespace(self)
206
+
207
+ # -- evaluation -----------------------------------------------------
208
+ def evaluate(self, run_id: str, action: str, **context: Any) -> Evaluation:
209
+ """Evaluate ``action`` against the active policy for ``run_id``.
210
+
211
+ Extra ``context`` keyword args (e.g. ``amount=15``) are available to
212
+ policy checks; ``max_cost_usd_per_run`` is enforced when ``cost`` is
213
+ provided.
214
+ """
215
+ if not run_id or not action:
216
+ raise GovernanceError("run_id and action are required")
217
+ policy = self._active_policy()
218
+ if policy is None:
219
+ return self._record(
220
+ Evaluation(allowed=False, reason="no active policy", run_id=run_id, action=action, policy_name="")
221
+ )
222
+
223
+ if action not in policy.allowed_tools:
224
+ return self._record(Evaluation(
225
+ allowed=False,
226
+ reason=f"{action!r} not in allowed_tools",
227
+ run_id=run_id,
228
+ action=action,
229
+ policy_name=policy.name,
230
+ ))
231
+
232
+ cost = context.get("cost") or context.get("amount") or 0
233
+ if policy.max_cost_usd_per_run is not None and float(cost) > policy.max_cost_usd_per_run:
234
+ return self._record(Evaluation(
235
+ allowed=False,
236
+ reason=f"cost {cost} exceeds cap {policy.max_cost_usd_per_run}",
237
+ run_id=run_id,
238
+ action=action,
239
+ policy_name=policy.name,
240
+ ))
241
+
242
+ if action in policy.require_approval_for:
243
+ approval = self.approvals.request(run_id, action)
244
+ return self._record(Evaluation(
245
+ allowed=False,
246
+ reason=f"{action!r} requires approval {approval.approval_id}",
247
+ run_id=run_id,
248
+ action=action,
249
+ policy_name=policy.name,
250
+ approval_required=True,
251
+ ))
252
+
253
+ return self._record(Evaluation(
254
+ allowed=True,
255
+ reason="permitted by policy",
256
+ run_id=run_id,
257
+ action=action,
258
+ policy_name=policy.name,
259
+ ))
260
+
261
+ def set_active_policy(self, name: str) -> None:
262
+ """Set the policy used by :meth:`evaluate`."""
263
+ if name not in self._policies:
264
+ raise GovernanceError(f"policy {name!r} not found")
265
+ self._active_policy_name = name
266
+
267
+ # -- internals ------------------------------------------------------
268
+ def _active_policy(self) -> Policy | None:
269
+ name = getattr(self, "_active_policy_name", None)
270
+ if name is None and self._policies:
271
+ name = next(iter(self._policies))
272
+ return self._policies.get(name) if name else None
273
+
274
+ def _record(self, evaluation: Evaluation) -> Evaluation:
275
+ record = AuditRecord(
276
+ record_id=f"aud_{uuid.uuid4().hex[:12]}",
277
+ run_id=evaluation.run_id,
278
+ action=evaluation.action,
279
+ decision="allow" if evaluation.allowed else "deny",
280
+ reason=evaluation.reason,
281
+ signature=_sign(evaluation),
282
+ )
283
+ self._audit.append(record)
284
+ if self._transport is not None:
285
+ self._transport("POST", "/v1/audit", record.to_dict())
286
+ return evaluation
287
+
288
+
289
+ def _sign(evaluation: Evaluation) -> str:
290
+ """Deterministic fake signature over an evaluation (for audit integrity)."""
291
+ import hashlib
292
+
293
+ payload = f"{evaluation.run_id}|{evaluation.action}|{evaluation.allowed}|{evaluation.reason}"
294
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
@@ -0,0 +1,39 @@
1
+ """CLI entry for em-runtime-governance-sdk.
2
+
3
+ The README documents no CLI surface; this command prints resolved Emergence
4
+ runtime credentials so teams can verify configuration before evaluating policy.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import sys
13
+
14
+ from . import GovernanceClient, __version__
15
+
16
+
17
+ def _build_parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(prog="em-runtime-governance-sdk", description="Emergence governance diagnostics.")
19
+ parser.add_argument("--version", action="version", version=f"em-runtime-governance-sdk {__version__}")
20
+ sub = parser.add_subparsers(dest="command", required=True)
21
+ sub.add_parser("info", help="print resolved governance configuration")
22
+ return parser
23
+
24
+
25
+ def main(argv: list[str] | None = None) -> int:
26
+ """Entry point for the ``em-runtime-governance-sdk`` console script."""
27
+ args = _build_parser().parse_args(argv)
28
+ if args.command == "info":
29
+ info = {
30
+ "base_url": os.environ.get("EM_RUNTIME_BASE_URL", "https://api.emergence.ai"),
31
+ "api_key": "***" if os.environ.get("EM_RUNTIME_API_KEY") else "<unset>",
32
+ }
33
+ print(json.dumps(info, indent=2, sort_keys=True))
34
+ return 0
35
+ return 1
36
+
37
+
38
+ if __name__ == "__main__":
39
+ sys.exit(main())
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: em-runtime-governance-sdk
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Emergence runtime governance layer — policy, approval gates, audit, budget caps, PII redaction.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # em-runtime-governance-sdk
11
+
12
+ `em-runtime-governance-sdk` is the Python SDK for the governance layer of the [Emergence](https://emergence.ai) runtime. It lets you attach policy, approvals, and audit to agent runs and tool calls so that autonomous workflows stay within organizational and regulatory boundaries. Pair it with `em-runtime-assets-sdk-python` for asset management and `em-runtime-utils-sdk-python` for shared helpers.
13
+
14
+ ## Features
15
+
16
+ - Declarative policy definitions for allowed tools, models, and data sources.
17
+ - Pre-run approval gates with synchronous, async, and timeout escalation.
18
+ - Per-decision audit records with immutable, signed logs.
19
+ - Budget and rate caps at the agent, run, and tenant level.
20
+ - PII and secret redaction hooks applied before model calls.
21
+ - Works with the Emergence runtime or any OpenTelemetry-instrumented host.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install em-runtime-governance-sdk
27
+ ```
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ from em_runtime_governance_sdk import GovernanceClient, Policy
33
+
34
+ client = GovernanceClient(api_key="em_live_...")
35
+
36
+ policy = Policy(
37
+ name="support-tier-1",
38
+ allowed_tools=["kb_search", "refund_issue"],
39
+ max_cost_usd_per_run=2.0,
40
+ require_approval_for=["refund_issue"],
41
+ )
42
+ client.policies.upsert(policy)
43
+
44
+ decision = client.evaluate(run_id="run_42", action="refund_issue", amount=15)
45
+ if not decision.allowed:
46
+ raise PermissionError(decision.reason)
47
+ ```
48
+
49
+ ## API
50
+
51
+ - `GovernanceClient(api_key=...)` — entry point; `policies`, `evaluations`, `audit` namespaces.
52
+ - `Policy(...)` — declarative rules object, versioned and upsertable.
53
+ - `client.evaluate(run_id, action, **context)` — return an `Evaluation` with `allowed` and `reason`.
54
+ - `client.approvals.request(run_id, action)` — open a human approval gate.
55
+
56
+ ## Configuration
57
+
58
+ Set `EM_RUNTIME_API_KEY` and optionally `EM_RUNTIME_BASE_URL` for a self-hosted runtime.
59
+
60
+ ## License
61
+
62
+ MIT
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/em_runtime_governance_sdk/__init__.py
4
+ src/em_runtime_governance_sdk/cli.py
5
+ src/em_runtime_governance_sdk.egg-info/PKG-INFO
6
+ src/em_runtime_governance_sdk.egg-info/SOURCES.txt
7
+ src/em_runtime_governance_sdk.egg-info/dependency_links.txt
8
+ src/em_runtime_governance_sdk.egg-info/entry_points.txt
9
+ src/em_runtime_governance_sdk.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ em-runtime-governance-sdk = em_runtime_governance_sdk.cli:main