cortexhub 0.3.5__tar.gz → 0.4.1__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.
Files changed (63) hide show
  1. {cortexhub-0.3.5 → cortexhub-0.4.1}/PKG-INFO +6 -4
  2. {cortexhub-0.3.5 → cortexhub-0.4.1}/README.md +4 -2
  3. {cortexhub-0.3.5 → cortexhub-0.4.1}/pyproject.toml +4 -4
  4. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/__init__.py +23 -44
  5. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/backend/__init__.py +1 -1
  6. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/backend/client.py +94 -76
  7. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/client.py +165 -330
  8. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/config.py +1 -1
  9. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/errors.py +1 -19
  10. cortexhub-0.4.1/src/cortexhub/interceptors/mcp.py +181 -0
  11. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/__init__.py +1 -1
  12. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/effects.py +24 -46
  13. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/evaluator.py +38 -43
  14. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/loader.py +16 -15
  15. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/sync.py +18 -18
  16. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/telemetry/otel.py +18 -18
  17. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/tool.py +2 -4
  18. cortexhub-0.3.5/src/cortexhub/interceptors/mcp.py +0 -129
  19. {cortexhub-0.3.5 → cortexhub-0.4.1}/.gitignore +0 -0
  20. {cortexhub-0.3.5 → cortexhub-0.4.1}/LICENSE +0 -0
  21. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/audit/__init__.py +0 -0
  22. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/audit/events.py +0 -0
  23. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/constants.py +0 -0
  24. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/context/__init__.py +0 -0
  25. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/context/enricher.py +0 -0
  26. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/__init__.py +0 -0
  27. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/injection.py +0 -0
  28. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/__init__.py +0 -0
  29. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSE +0 -0
  30. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/LICENSES_SOURCES +0 -0
  31. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/README.md +0 -0
  32. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/accuracy.json +0 -0
  33. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/attribute_ruler/patterns +0 -0
  34. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/config.cfg +0 -0
  35. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/lemmatizer/lookups/lookups.bin +0 -0
  36. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/meta.json +0 -0
  37. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/cfg +0 -0
  38. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/model +0 -0
  39. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/ner/moves +0 -0
  40. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/cfg +0 -0
  41. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/model +0 -0
  42. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/parser/moves +0 -0
  43. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/cfg +0 -0
  44. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/senter/model +0 -0
  45. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/cfg +0 -0
  46. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tagger/model +0 -0
  47. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/cfg +0 -0
  48. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tok2vec/model +0 -0
  49. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/tokenizer +0 -0
  50. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/key2row +0 -0
  51. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/lookups.bin +0 -0
  52. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/strings.json +0 -0
  53. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors +0 -0
  54. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/en_core_web_sm-3.8.0/vocab/vectors.cfg +0 -0
  55. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/models/en_core_web_sm/meta.json +0 -0
  56. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/pii.py +0 -0
  57. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/guardrails/secrets.py +0 -0
  58. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/interceptors/__init__.py +0 -0
  59. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/logging.py +0 -0
  60. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/policy/models.py +0 -0
  61. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/signing.py +0 -0
  62. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/telemetry/__init__.py +0 -0
  63. {cortexhub-0.3.5 → cortexhub-0.4.1}/src/cortexhub/version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cortexhub
3
- Version: 0.3.5
3
+ Version: 0.4.1
4
4
  Summary: CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework.
5
5
  Project-URL: Homepage, https://cortexhub.ai
6
6
  Project-URL: Documentation, https://docs.cortexhub.ai
@@ -8,7 +8,7 @@ Project-URL: Examples, https://github.com/CortexHub-AI/examples/
8
8
  Author-email: CortexHub <hello@cortexhub.ai>
9
9
  License: MIT
10
10
  License-File: LICENSE
11
- Keywords: agents,ai,authorization,cedar,governance,policy
11
+ Keywords: agents,ai,authorization,governance,policy
12
12
  Classifier: Development Status :: 4 - Beta
13
13
  Classifier: Intended Audience :: Developers
14
14
  Classifier: License :: OSI Approved :: MIT License
@@ -46,10 +46,12 @@ Python 3.10–3.12.
46
46
 
47
47
  ## Quick start
48
48
 
49
+ Identity comes from your **agent key** only — the control plane assigns the canonical agent id. Set `CORTEXHUB_AGENT_KEY` (or pass `agent_key=` to `init()`).
50
+
49
51
  ```python
50
52
  import cortexhub
51
53
 
52
- cx = cortexhub.init("my-agent") # or set CORTEXHUB_API_KEY
54
+ cx = cortexhub.init() # requires CORTEXHUB_AGENT_KEY (or pass agent_key=)
53
55
 
54
56
  @cx.tool
55
57
  def process_payment(customer_id: str, amount: str, reference: str) -> dict:
@@ -63,7 +65,7 @@ def process_payment(customer_id: str, amount: str, reference: str) -> dict:
63
65
 
64
66
  | Env var | Description |
65
67
  |--------|-------------|
66
- | `CORTEXHUB_API_KEY` | API key (required for cloud enforcement) |
68
+ | `CORTEXHUB_AGENT_KEY` | Agent identity secret (required for cloud enforcement) |
67
69
  | `CORTEXHUB_DEBUG` | Set to `1` or `true` for readable SDK logs: tool + arguments, policy name + condition, and decision |
68
70
  | `CORTEXHUB_LOG_LEVEL` | e.g. `DEBUG`, `INFO` (default `INFO`) |
69
71
 
@@ -10,10 +10,12 @@ Python 3.10–3.12.
10
10
 
11
11
  ## Quick start
12
12
 
13
+ Identity comes from your **agent key** only — the control plane assigns the canonical agent id. Set `CORTEXHUB_AGENT_KEY` (or pass `agent_key=` to `init()`).
14
+
13
15
  ```python
14
16
  import cortexhub
15
17
 
16
- cx = cortexhub.init("my-agent") # or set CORTEXHUB_API_KEY
18
+ cx = cortexhub.init() # requires CORTEXHUB_AGENT_KEY (or pass agent_key=)
17
19
 
18
20
  @cx.tool
19
21
  def process_payment(customer_id: str, amount: str, reference: str) -> dict:
@@ -27,7 +29,7 @@ def process_payment(customer_id: str, amount: str, reference: str) -> dict:
27
29
 
28
30
  | Env var | Description |
29
31
  |--------|-------------|
30
- | `CORTEXHUB_API_KEY` | API key (required for cloud enforcement) |
32
+ | `CORTEXHUB_AGENT_KEY` | Agent identity secret (required for cloud enforcement) |
31
33
  | `CORTEXHUB_DEBUG` | Set to `1` or `true` for readable SDK logs: tool + arguments, policy name + condition, and decision |
32
34
  | `CORTEXHUB_LOG_LEVEL` | e.g. `DEBUG`, `INFO` (default `INFO`) |
33
35
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cortexhub"
3
- version = "0.3.5"
3
+ version = "0.4.1"
4
4
  description = "CortexHub Python SDK — Runtime governance for AI systems. One decorator, any tool, any framework."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10,<3.13"
@@ -8,7 +8,7 @@ license = { text = "MIT" }
8
8
  authors = [
9
9
  { name = "CortexHub", email = "hello@cortexhub.ai" }
10
10
  ]
11
- keywords = ["ai", "agents", "policy", "governance", "authorization", "cedar"]
11
+ keywords = ["ai", "agents", "policy", "governance", "authorization"]
12
12
  classifiers = [
13
13
  "Development Status :: 4 - Beta",
14
14
  "Intended Audience :: Developers",
@@ -31,7 +31,7 @@ dependencies = [
31
31
  "opentelemetry-api>=1.20.0",
32
32
  "opentelemetry-sdk>=1.20.0",
33
33
  "opentelemetry-exporter-otlp-proto-http>=1.20.0",
34
- # Cedar policy engine — local policy evaluation (no network per call)
34
+ # In-process policy evaluation (no network per call)
35
35
  "cedarpy>=4.0.0",
36
36
  # Guardrails — PII and secrets detection before LLM calls
37
37
  "presidio-analyzer>=2.2.360",
@@ -42,7 +42,7 @@ dependencies = [
42
42
  "spacy-lookups-data>=1.0.0",
43
43
  # Ed25519 decision signing — tamper-evident cryptographic audit trail
44
44
  "cryptography>=43.0.0",
45
- # .env file loading for CORTEXHUB_API_KEY etc.
45
+ # .env file loading for CORTEXHUB_AGENT_KEY etc.
46
46
  "python-dotenv>=1.0.0",
47
47
  ]
48
48
 
@@ -4,33 +4,26 @@ One decorator. Any tool. Any framework. Anywhere.
4
4
 
5
5
  import cortexhub
6
6
 
7
- cx = cortexhub.init("healthcare-agent")
7
+ cx = cortexhub.init()
8
8
 
9
9
  @cx.tool
10
10
  def prescribe_medication(patient_id: str, medication: str, dosage: str) -> str:
11
- \"\"\"Prescribe medication to a patient.\"\"\"
11
+ \"\"\"Prescribe a medication to a patient.\"\"\"
12
12
  return db.prescribe(patient_id, medication, dosage)
13
13
 
14
14
  async with cx.run():
15
15
  try:
16
16
  result = await my_agent(user_input)
17
- except cortexhub.ApprovalRequired as e:
17
+ except cortexhub.ApprovalRequiredError as e:
18
18
  await cx.wait_for_approval(e)
19
19
  result = cx.retry_tool(e)
20
20
  except cortexhub.PolicyViolationError as e:
21
21
  return {"blocked": True, "reason": e.reasoning}
22
22
 
23
- CortexHub provides:
24
- - Policy enforcement (block, require approval, throttle, circuit-break)
25
- - PII, secrets, and prompt injection guardrails
26
- - Cryptographically signed audit trail (Ed25519)
27
- - Human-in-the-loop approval workflows
28
- - EU AI Act Article 12 compliance telemetry
23
+ Set ``CORTEXHUB_AGENT_KEY`` to the key from your governed agent in CortexHub; the SDK
24
+ loads canonical ``agent_id`` and display metadata from the control plane on startup.
29
25
 
30
- Zero framework dependencies. Works with LangGraph, CrewAI, OpenAI Agents,
31
- Claude Agents, raw Python, Flask, FastAPI, scripts, cron jobs — anything.
32
-
33
- Get your API key at https://app.cortexhub.ai
26
+ Create an agent and copy its key from https://app.cortexhub.ai
34
27
  """
35
28
 
36
29
  from cortexhub.client import CortexHub, SessionContext
@@ -42,8 +35,6 @@ from cortexhub.errors import (
42
35
  GuardrailViolationError,
43
36
  ApprovalRequiredError,
44
37
  ApprovalDeniedError,
45
- ThrottleError,
46
- CircuitBreakError,
47
38
  PolicyLoadError,
48
39
  )
49
40
  from cortexhub.signing import verify_signature
@@ -53,21 +44,23 @@ _global_instance: CortexHub | None = None
53
44
 
54
45
 
55
46
  def init(
56
- agent_id: str,
57
47
  *,
58
- api_key: str | None = None,
48
+ agent_key: str | None = None,
59
49
  enable_mcp: bool = False,
60
50
  log_level: str | None = None,
61
51
  log_file: str | None = None,
62
52
  log_to_console: bool | None = None,
63
- parent_agent_id: str | None = None,
64
- delegation_chain: list[str] | None = None,
53
+ framework: str | None = None,
65
54
  ) -> CortexHub:
66
55
  """Initialise CortexHub governance and return a CortexHub instance.
67
56
 
68
- Call once per agent identity, typically at module level::
57
+ Call once per process (one governed agent key). Identity comes from the key::
58
+
59
+ cx = cortexhub.init()
60
+
61
+ Or pass the key explicitly::
69
62
 
70
- cx = cortexhub.init("healthcare-agent")
63
+ cx = cortexhub.init(agent_key="ch_live_...")
71
64
 
72
65
  Then use the returned instance to govern tools and LLM calls::
73
66
 
@@ -77,21 +70,15 @@ def init(
77
70
  async with cx.run():
78
71
  result = await my_agent(input)
79
72
 
80
- Privacy (redact vs raw telemetry) is controlled by the project setting in the
81
- CortexHub dashboard (Privacy: On / Off). There is no SDK-level override.
73
+ Privacy (redact vs raw telemetry) is controlled in the CortexHub dashboard.
82
74
 
83
75
  Args:
84
- agent_id: Stable identifier shown in the control plane
85
- (e.g. "healthcare-agent", "finance-crew").
86
- api_key: CortexHub API key. Defaults to CORTEXHUB_API_KEY env var.
87
- enable_mcp: If True, patch mcp.ClientSession.call_tool for MCP
88
- tool governance. Defaults to False; call cx.enable_mcp()
89
- explicitly when needed.
90
- log_level: Log level override ("DEBUG", "INFO", "WARNING", "ERROR").
91
- log_file: Path to write structured JSON logs.
92
- log_to_console: If True, echo logs to stdout.
93
- parent_agent_id: For multi-agent systems: the parent agent's ID.
94
- delegation_chain: For multi-agent systems: pass parent.child_delegation_chain.
76
+ agent_key: Secret for this governed agent. Defaults to ``CORTEXHUB_AGENT_KEY``.
77
+ enable_mcp: If True, patch mcp.ClientSession.call_tool for MCP tool governance.
78
+ log_level: Log level override ("DEBUG", "INFO", "WARNING", "ERROR").
79
+ log_file: Path to write structured JSON logs.
80
+ log_to_console: If True, echo logs to stdout.
81
+ framework: Optional label sent on validation (e.g. ``langgraph``).
95
82
 
96
83
  Returns:
97
84
  CortexHub instance with .tool(), .run(), .enforce(), etc.
@@ -99,19 +86,16 @@ def init(
99
86
  global _global_instance
100
87
 
101
88
  instance = CortexHub(
102
- api_key=api_key,
103
- agent_id=agent_id,
89
+ agent_key=agent_key,
104
90
  log_level=log_level,
105
91
  log_file=log_file,
106
92
  log_to_console=log_to_console,
107
- parent_agent_id=parent_agent_id,
108
- delegation_chain=delegation_chain,
93
+ framework=framework,
109
94
  )
110
95
 
111
96
  if enable_mcp:
112
97
  instance.enable_mcp()
113
98
 
114
- # Store as global for get_instance() convenience
115
99
  _global_instance = instance
116
100
  return instance
117
101
 
@@ -122,22 +106,17 @@ def get_instance() -> CortexHub | None:
122
106
 
123
107
 
124
108
  __all__ = [
125
- # Primary API
126
109
  "init",
127
110
  "get_instance",
128
111
  "CortexHub",
129
112
  "SessionContext",
130
113
  "__version__",
131
- # Audit / compliance verification
132
114
  "verify_signature",
133
- # Governance errors — catch these in your agent code
134
115
  "CortexHubError",
135
116
  "ConfigurationError",
136
117
  "PolicyViolationError",
137
118
  "GuardrailViolationError",
138
119
  "ApprovalRequiredError",
139
120
  "ApprovalDeniedError",
140
- "ThrottleError",
141
- "CircuitBreakError",
142
121
  "PolicyLoadError",
143
122
  ]
@@ -1,4 +1,4 @@
1
- """Backend communication for API key validation."""
1
+ """Backend communication (agent key validation, SDK endpoints)."""
2
2
 
3
3
  from cortexhub.backend.client import BackendClient
4
4
 
@@ -40,54 +40,56 @@ class GuardrailConfig:
40
40
 
41
41
  @dataclass
42
42
  class PolicyBundle:
43
- """Policy bundle from backend.
44
-
45
- enforcement_mode controls how policies are applied:
46
- - "active" : policies evaluate and enforce (block / escalate / allow)
47
- - "observation" : policies are NOT evaluated; all actions pass through unblocked
48
-
43
+ """Policy bundle from backend (v2).
44
+
45
+ When no active policies exist for the governed agent, the bundle is empty and every tool is
46
+ **ungoverned** (SDK does not run Cedar). When policies exist, evaluation is per-tool:
47
+ tools without an entry in ``tool_policies`` are ungoverned (permit).
48
+
49
49
  privacy_mode controls telemetry redaction:
50
50
  - "on" : redact PII/secrets in telemetry before sending (default)
51
51
  - "off" : send raw data (dev/staging only)
52
-
53
- When policies is empty AND enforcement_mode is "active", SDK is in observation mode
54
- (no policies to evaluate). When policies is non-empty and enforcement_mode is "active",
55
- full enforcement is active.
56
52
 
57
- tool_policies: when present, SDK evaluates only the policies for the tool being invoked
58
- (per-tool Cedar + per-tool schema). Preferred over flat policies + merged schema.
53
+ tool_policies: when present, SDK evaluates only the policies for the tool being invoked.
59
54
  """
60
55
  version: str
61
- policies: str # Cedar policies (empty = no enforcement; fallback when tool_policies not used)
62
- schema: dict[str, Any] | None = None # Cedar schema (merged; fallback when tool_policies not used)
56
+ policies: str # Policy source text (empty when using per-tool bundles only)
57
+ schema: dict[str, Any] | None = None # Merged schema when tool_policies not used
63
58
  policy_metadata: dict[str, dict[str, Any]] | None = None
64
- # Per-tool policies: tool_name -> { "cedar", "schema", "policy_metadata" }; SDK uses this at runtime.
65
59
  tool_policies: dict[str, dict[str, Any]] | None = None
66
- # Guardrail configurations (keyed by policy type: "pii", "secrets")
67
60
  guardrail_configs: dict[str, GuardrailConfig] | None = None
68
61
  policy_defaults: dict[str, Any] | None = None
69
62
  policy_packs: list[dict[str, Any]] | None = None
70
- enforcement_mode: str = "active" # "active" | "observation"
71
- # NoDecision behavior: allow_and_log | deny_and_log | escalate (project-level from backend)
63
+ # NoDecision / engine edge cases only (not used for ungoverned tools in per-tool mode)
72
64
  default_behavior: str = "allow_and_log"
73
- guardrail_version: str = "0" # hash of guardrail config; SDK refreshes when this changes
74
- privacy_mode: str = "on" # "on" = redact telemetry; "off" = send raw
65
+ guardrail_version: str = "0"
66
+ privacy_mode: str = "on"
75
67
 
76
68
 
77
69
  @dataclass
78
70
  class SDKConfig:
79
71
  """SDK configuration from backend.
80
-
81
- Returned during API key validation.
72
+
73
+ Returned after successful agent-key validation.
82
74
  """
83
- project_id: str
75
+
76
+ agent_id: str
84
77
  organization_id: str
85
78
  plan: str
86
79
  policies: PolicyBundle
87
-
80
+ agent_name: str | None = None
81
+ agent_slug: str | None = None
82
+ environment: str | None = None
83
+ group_id: str | None = None
84
+
85
+ @property
86
+ def project_id(self) -> str:
87
+ """Alias for :attr:`agent_id` (governed agent ObjectId string)."""
88
+ return self.agent_id
89
+
88
90
  @property
89
91
  def has_policies(self) -> bool:
90
- """Check if policies are present (enforcement mode)."""
92
+ """True if the governed agent has at least one active policy row (governed tools may exist)."""
91
93
  if self.policies.tool_policies:
92
94
  return True
93
95
  return bool(self.policies.policies.strip())
@@ -95,61 +97,73 @@ class SDKConfig:
95
97
 
96
98
  class BackendClient:
97
99
  """Client for communicating with CortexHub backend.
98
-
99
- Handles:
100
- - API key validation + policy retrieval
100
+
101
+ Handles agent-key validation, policy retrieval, and SDK HTTP calls.
101
102
  """
102
103
 
103
- def __init__(self, api_key: str | None, backend_url: str):
104
+ def __init__(self, agent_key: str | None, backend_url: str):
104
105
  """Initialize backend client.
105
-
106
+
106
107
  Args:
107
- api_key: API key for authentication
108
- backend_url: Backend API URL
108
+ agent_key: Secret issued for this agent identity (sent as ``X-API-Key``).
109
+ backend_url: Backend API URL (must include ``/v1`` base path used by the SDK).
109
110
  """
110
- self.api_key = api_key
111
+ self.agent_key = agent_key
111
112
  self.backend_url = backend_url.rstrip("/")
112
113
  self._client: httpx.Client | None = None
113
-
114
- if api_key:
114
+
115
+ if agent_key:
115
116
  self._client = httpx.Client(
116
117
  base_url=self.backend_url,
117
- headers={"X-API-Key": api_key},
118
+ headers={"X-API-Key": agent_key},
118
119
  timeout=10.0,
119
120
  )
120
-
121
- def validate_api_key(self, *, agent_id: str | None = None) -> tuple[bool, SDKConfig | None]:
122
- """Validate API key with backend and get SDK configuration.
123
-
121
+
122
+ def validate_agent_key(
123
+ self,
124
+ *,
125
+ mode: str | None = None,
126
+ framework: str | None = None,
127
+ ) -> tuple[bool, SDKConfig | None]:
128
+ """Validate the agent key with the backend and load SDK configuration.
129
+
124
130
  Returns:
125
131
  (is_valid, SDKConfig or None)
126
-
127
- SDKConfig includes:
128
- - project_id, organization_id
129
- - policies (empty = observation mode, non-empty = enforcement mode)
132
+
133
+ SDKConfig includes governed ``agent_id`` (ObjectId string), display metadata, and policies.
130
134
  """
131
- if not self.api_key or not self._client:
135
+ if not self.agent_key or not self._client:
132
136
  return False, None
133
137
 
134
138
  try:
135
139
  # Note: base_url already includes /v1, so just /api-keys/validate.
136
- # Send agent_id so the backend returns only policies that apply to this agent.
137
- payload = {}
138
- if agent_id:
139
- payload["agent_id"] = agent_id
140
+ payload: dict[str, str] = {}
141
+ if mode:
142
+ payload["mode"] = mode
143
+ if framework:
144
+ payload["framework"] = framework
140
145
  response = self._client.post(
141
146
  "/api-keys/validate",
142
- headers={"X-API-Key": self.api_key},
147
+ headers={"X-API-Key": self.agent_key},
143
148
  json=payload if payload else None,
144
149
  timeout=5.0,
145
150
  )
146
151
 
147
152
  if response.status_code == 200:
148
- data = response.json()
153
+ try:
154
+ data = response.json()
155
+ except Exception as parse_err:
156
+ logger.error(
157
+ "Agent key validate returned non-JSON body",
158
+ status=response.status_code,
159
+ preview=(response.text or "")[:300],
160
+ error=str(parse_err),
161
+ )
162
+ return False, None
149
163
 
150
164
  # Check if valid
151
165
  if not data.get("valid", False):
152
- logger.warning("API key validation failed", message=data.get("message"))
166
+ logger.warning("Agent key validation failed", message=data.get("message"))
153
167
  return False, None
154
168
 
155
169
  # Parse policy bundle from backend
@@ -159,12 +173,6 @@ class BackendClient:
159
173
  if not isinstance(policies_data, dict):
160
174
  policies_data = {}
161
175
  raw_policies = policies_data.get("policies", [])
162
- if agent_id:
163
- raw_policies = [
164
- policy
165
- for policy in raw_policies
166
- if policy.get("agent_id") in (agent_id, "all", None, "")
167
- ]
168
176
  guardrail_configs: dict[str, GuardrailConfig] = {}
169
177
 
170
178
  # Project-level guardrail config (applies to all agents; used for data sent to LLMs)
@@ -203,10 +211,10 @@ class BackendClient:
203
211
  )
204
212
 
205
213
  if isinstance(raw_policies, list):
206
- # Backend returns list of policy objects - extract Cedar code (no guardrail_config on policies)
214
+ # Backend returns list of policy objects - extract policy text (no guardrail_config on policies)
207
215
  cedar_parts = []
208
216
  # Default permit: allow all tool invocations unless a forbid policy matches.
209
- # Without this, Cedar's "default deny" would deny every tool that has no policy
217
+ # Without this, the engine default would deny every tool that has no policy
210
218
  # (e.g. lookup_patient when only prescribe_medication has a policy).
211
219
  if raw_policies:
212
220
  cedar_parts.append("// Default: allow unless a forbid matches (tools with no policy are allowed)")
@@ -265,25 +273,31 @@ class BackendClient:
265
273
  guardrail_configs=guardrail_configs if guardrail_configs else None,
266
274
  policy_defaults=policies_data.get("policy_defaults"),
267
275
  policy_packs=policies_data.get("policy_packs"),
268
- enforcement_mode=policies_data.get("enforcement_mode", "active"),
269
276
  default_behavior=policies_data.get("default_behavior", "allow_and_log"),
270
277
  guardrail_version=policies_data.get("guardrail_version", "0"),
271
278
  privacy_mode=_privacy,
272
279
  )
273
280
  logger.debug("Validate response privacy_mode", privacy_mode=_privacy)
274
281
 
282
+ _aid = data.get("agent_id") or data.get("project_id") or ""
283
+ _gid = data.get("group_id")
275
284
  config = SDKConfig(
276
- project_id=data.get("project_id", ""),
285
+ agent_id=str(_aid),
277
286
  organization_id=data.get("org_id", ""),
278
287
  plan=data.get("plan", "free"),
279
288
  policies=policies,
289
+ agent_name=data.get("agent_name"),
290
+ agent_slug=data.get("agent_slug"),
291
+ environment=data.get("environment"),
292
+ group_id=str(_gid) if _gid else None,
280
293
  )
281
-
282
- mode = "enforcement" if config.has_policies else "observation"
294
+
295
+ gov = "governed" if config.has_policies else "ungoverned"
283
296
  logger.info(
284
- "API key validated",
285
- project_id=config.project_id,
286
- mode=mode,
297
+ "Agent key validated",
298
+ agent_id=config.agent_id,
299
+ agent_name=config.agent_name,
300
+ governance=gov,
287
301
  policy_version=policies.version,
288
302
  )
289
303
  _debug_bundle = os.getenv("CORTEXHUB_DEBUG_POLICY_BUNDLE", "").lower() in ("1", "true", "yes")
@@ -298,13 +312,17 @@ class BackendClient:
298
312
  tool_names=[v.get("tool_name") for v in policy_map.values()],
299
313
  )
300
314
  if _debug_text or _debug_any:
301
- logger.info("Policy bundle cedar (full)", policies=policies_str)
315
+ logger.info("Policy bundle source (full)", policies=policies_str)
302
316
  return True, config
303
317
  else:
304
- error_detail = response.json().get("detail", "Invalid API key")
305
- logger.warning("API key validation failed", error=error_detail)
318
+ try:
319
+ body = response.json()
320
+ error_detail = body.get("detail", "Invalid agent key") if isinstance(body, dict) else str(body)
321
+ except Exception:
322
+ error_detail = (response.text or "")[:500] or f"HTTP {response.status_code}"
323
+ logger.warning("Agent key validation failed", error=error_detail)
306
324
  return False, None
307
-
325
+
308
326
  except httpx.ConnectError:
309
327
  logger.warning(
310
328
  "Backend unreachable - running in offline observation mode",
@@ -312,7 +330,7 @@ class BackendClient:
312
330
  )
313
331
  return False, None
314
332
  except Exception as e:
315
- logger.error("API key validation error", error=str(e))
333
+ logger.error("Agent key validation error", error=str(e))
316
334
  return False, None
317
335
 
318
336
  def close(self):
@@ -323,8 +341,8 @@ class BackendClient:
323
341
  def register_public_key(self, public_key_b64: str, fingerprint: str) -> bool:
324
342
  """Register the session's Ed25519 public key with the backend.
325
343
 
326
- Called once on SDK init after API key validation. The backend stores
327
- the public key against the API key so it can verify span signatures
344
+ Called once on SDK init after agent-key validation. The backend stores
345
+ the public key against the agent key so it can verify span signatures
328
346
  on receipt and serve it to external auditors.
329
347
 
330
348
  Args:
@@ -334,7 +352,7 @@ class BackendClient:
334
352
  Returns:
335
353
  True if registered successfully, False on failure (non-fatal).
336
354
  """
337
- if not self._client or not self.api_key:
355
+ if not self._client or not self.agent_key:
338
356
  return False
339
357
  try:
340
358
  response = self._client.post(
@@ -356,7 +374,7 @@ class BackendClient:
356
374
 
357
375
  def register_tools(self, tools: list[dict[str, Any]]) -> bool:
358
376
  """Register tool inventory with backend (best-effort)."""
359
- if not self._client or not self.api_key:
377
+ if not self._client or not self.agent_key:
360
378
  return False
361
379
  if not tools:
362
380
  return True