quantawatch 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.
@@ -0,0 +1,37 @@
1
+ """QuantaWatch Python SDK -- AI agent security gateway client.
2
+
3
+ Quickstart::
4
+
5
+ from quantawatch import QuantaWatchClient, protect
6
+
7
+ # Option 1: Direct gateway client
8
+ async with QuantaWatchClient() as qw:
9
+ sessions = await qw.get_sessions()
10
+ stats = await qw.get_stats()
11
+
12
+ # Option 2: Wrap an existing AI client
13
+ from anthropic import Anthropic
14
+ client = protect(Anthropic(), gateway_url="http://localhost:9090")
15
+ """
16
+
17
+ from quantawatch.client import QuantaWatchClient
18
+ from quantawatch.protect import protect
19
+ from quantawatch.types import (
20
+ AuditEntry,
21
+ DetectedThreat,
22
+ GatewayStats,
23
+ SessionInfo,
24
+ ThreatAssessment,
25
+ )
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "QuantaWatchClient",
31
+ "protect",
32
+ "AuditEntry",
33
+ "DetectedThreat",
34
+ "GatewayStats",
35
+ "SessionInfo",
36
+ "ThreatAssessment",
37
+ ]
quantawatch/client.py ADDED
@@ -0,0 +1,166 @@
1
+ """QuantaWatch gateway client.
2
+
3
+ Provides an async client for interacting with both the QuantaWatch gateway
4
+ (proxying AI API requests) and the admin API (sessions, audit, stats).
5
+
6
+ Usage::
7
+
8
+ async with QuantaWatchClient() as qw:
9
+ # Proxy a request through the gateway
10
+ resp = await qw.proxy_request("POST", "/v1/messages", headers, body)
11
+
12
+ # Query the admin API
13
+ sessions = await qw.get_sessions()
14
+ stats = await qw.get_stats()
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ import httpx
22
+
23
+ from quantawatch.types import AuditEntry, GatewayStats, SessionInfo
24
+
25
+
26
+ class QuantaWatchClient:
27
+ """Async client for the QuantaWatch security gateway.
28
+
29
+ Parameters
30
+ ----------
31
+ gateway_url:
32
+ Base URL of the QuantaWatch gateway proxy (default ``http://localhost:9090``).
33
+ admin_url:
34
+ Base URL of the QuantaWatch admin API (default ``http://localhost:9091``).
35
+ timeout:
36
+ Request timeout in seconds (default 30).
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ gateway_url: str = "http://localhost:9090",
42
+ admin_url: str = "http://localhost:9091",
43
+ *,
44
+ timeout: float = 30.0,
45
+ ) -> None:
46
+ self.gateway_url = gateway_url.rstrip("/")
47
+ self.admin_url = admin_url.rstrip("/")
48
+ self._client = httpx.AsyncClient(timeout=timeout)
49
+
50
+ # -- Gateway proxy --------------------------------------------------------
51
+
52
+ async def proxy_request(
53
+ self,
54
+ method: str,
55
+ path: str,
56
+ headers: dict[str, str] | None = None,
57
+ body: bytes | None = None,
58
+ ) -> httpx.Response:
59
+ """Proxy an HTTP request through the QuantaWatch gateway.
60
+
61
+ The gateway will inspect the request for threats, log it to the
62
+ audit trail, and forward it to the upstream AI provider.
63
+
64
+ Parameters
65
+ ----------
66
+ method:
67
+ HTTP method (GET, POST, etc.).
68
+ path:
69
+ Request path (e.g. ``/v1/messages``).
70
+ headers:
71
+ HTTP headers to forward. The ``Authorization`` header is typically
72
+ required by the upstream provider.
73
+ body:
74
+ Raw request body bytes, or *None* for bodyless requests.
75
+
76
+ Returns
77
+ -------
78
+ httpx.Response
79
+ The upstream response, as received through the gateway.
80
+ """
81
+ url = f"{self.gateway_url}{path}"
82
+ return await self._client.request(
83
+ method,
84
+ url,
85
+ headers=headers or {},
86
+ content=body,
87
+ )
88
+
89
+ # -- Admin API ------------------------------------------------------------
90
+
91
+ async def get_sessions(self) -> list[SessionInfo]:
92
+ """Fetch all sessions from the admin API.
93
+
94
+ Returns
95
+ -------
96
+ list[SessionInfo]
97
+ A list of current and historical gateway sessions.
98
+ """
99
+ resp = await self._client.get(f"{self.admin_url}/api/sessions")
100
+ resp.raise_for_status()
101
+ return [SessionInfo.model_validate(s) for s in resp.json()]
102
+
103
+ async def get_audit_entries(self, limit: int = 100) -> list[AuditEntry]:
104
+ """Fetch recent audit log entries.
105
+
106
+ Parameters
107
+ ----------
108
+ limit:
109
+ Maximum number of entries to return (default 100).
110
+
111
+ Returns
112
+ -------
113
+ list[AuditEntry]
114
+ Audit entries ordered by sequence number (most recent last).
115
+ """
116
+ resp = await self._client.get(
117
+ f"{self.admin_url}/api/audit",
118
+ params={"limit": limit},
119
+ )
120
+ resp.raise_for_status()
121
+ return [AuditEntry.model_validate(e) for e in resp.json()]
122
+
123
+ async def get_stats(self) -> GatewayStats:
124
+ """Fetch aggregate gateway statistics.
125
+
126
+ Returns
127
+ -------
128
+ GatewayStats
129
+ Current gateway statistics (sessions, requests, threats, etc.).
130
+ """
131
+ resp = await self._client.get(f"{self.admin_url}/api/stats")
132
+ resp.raise_for_status()
133
+ return GatewayStats.model_validate(resp.json())
134
+
135
+ async def verify_audit_chain(self) -> dict[str, Any]:
136
+ """Verify the integrity of the cryptographic audit chain.
137
+
138
+ The admin API checks that every audit entry's signature is valid
139
+ and that the chain is unbroken from the first entry.
140
+
141
+ Returns
142
+ -------
143
+ dict
144
+ Verification result with keys like ``valid`` (bool),
145
+ ``entries_checked`` (int), and ``errors`` (list).
146
+ """
147
+ resp = await self._client.get(f"{self.admin_url}/api/audit/verify")
148
+ resp.raise_for_status()
149
+ return resp.json()
150
+
151
+ # -- Lifecycle ------------------------------------------------------------
152
+
153
+ async def close(self) -> None:
154
+ """Close the underlying HTTP client and release resources."""
155
+ await self._client.aclose()
156
+
157
+ async def __aenter__(self) -> "QuantaWatchClient":
158
+ return self
159
+
160
+ async def __aexit__(
161
+ self,
162
+ exc_type: type[BaseException] | None,
163
+ exc_val: BaseException | None,
164
+ exc_tb: Any,
165
+ ) -> None:
166
+ await self.close()
@@ -0,0 +1,185 @@
1
+ """Framework middleware for QuantaWatch.
2
+
3
+ Provides integration points for popular AI and web frameworks:
4
+
5
+ - **LangChain**: ``QuantaWatchLangChainCallback`` -- a callback handler that
6
+ logs LangChain events to the QuantaWatch audit trail.
7
+ - **ASGI**: ``quantawatch_middleware`` -- wraps any ASGI application to proxy
8
+ outbound AI requests through the gateway.
9
+
10
+ .. note::
11
+
12
+ The LangChain callback handler requires the ``langchain`` optional
13
+ dependency: ``pip install quantawatch[langchain]``
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any, Callable, Awaitable
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # LangChain callback handler (Phase 2 stub)
23
+ # ---------------------------------------------------------------------------
24
+
25
+ class QuantaWatchLangChainCallback:
26
+ """LangChain callback handler that logs chain events to QuantaWatch.
27
+
28
+ This handler integrates with LangChain's callback system to capture
29
+ LLM calls, chain runs, tool invocations, and errors, forwarding them
30
+ to the QuantaWatch admin API as audit entries.
31
+
32
+ .. admonition:: Phase 2
33
+
34
+ This class is a stub. A full implementation will be provided in a
35
+ future release once the LangChain callback protocol is finalised.
36
+
37
+ Parameters
38
+ ----------
39
+ admin_url:
40
+ Base URL of the QuantaWatch admin API.
41
+ session_id:
42
+ Optional session ID to associate events with. If *None*, a new
43
+ session will be created automatically.
44
+
45
+ Example
46
+ -------
47
+ ::
48
+
49
+ from langchain.chat_models import ChatAnthropic
50
+ from quantawatch.middleware import QuantaWatchLangChainCallback
51
+
52
+ handler = QuantaWatchLangChainCallback(admin_url="http://localhost:9091")
53
+ llm = ChatAnthropic(callbacks=[handler])
54
+ llm.invoke("Summarize this document.")
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ admin_url: str = "http://localhost:9091",
60
+ session_id: str | None = None,
61
+ ) -> None:
62
+ self.admin_url = admin_url.rstrip("/")
63
+ self.session_id = session_id
64
+
65
+ # -- LangChain callback protocol stubs -----------------------------------
66
+ # These will be fully implemented in Phase 2.
67
+
68
+ def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> None:
69
+ """Called when an LLM call begins."""
70
+
71
+ def on_llm_end(self, response: Any, **kwargs: Any) -> None:
72
+ """Called when an LLM call completes."""
73
+
74
+ def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
75
+ """Called when an LLM call raises an error."""
76
+
77
+ def on_chain_start(self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any) -> None:
78
+ """Called when a chain run begins."""
79
+
80
+ def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
81
+ """Called when a chain run completes."""
82
+
83
+ def on_chain_error(self, error: BaseException, **kwargs: Any) -> None:
84
+ """Called when a chain run raises an error."""
85
+
86
+ def on_tool_start(self, serialized: dict[str, Any], input_str: str, **kwargs: Any) -> None:
87
+ """Called when a tool invocation begins."""
88
+
89
+ def on_tool_end(self, output: str, **kwargs: Any) -> None:
90
+ """Called when a tool invocation completes."""
91
+
92
+ def on_tool_error(self, error: BaseException, **kwargs: Any) -> None:
93
+ """Called when a tool invocation raises an error."""
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # Generic ASGI middleware
98
+ # ---------------------------------------------------------------------------
99
+
100
+ # ASGI type aliases
101
+ Scope = dict[str, Any]
102
+ Receive = Callable[[], Awaitable[dict[str, Any]]]
103
+ Send = Callable[[dict[str, Any]], Awaitable[None]]
104
+ ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
105
+
106
+
107
+ class QuantaWatchASGIMiddleware:
108
+ """ASGI middleware that routes outbound AI API calls through the QuantaWatch gateway.
109
+
110
+ Wrap any ASGI application (FastAPI, Starlette, etc.) to ensure that all
111
+ outbound HTTP requests made by the application to AI providers are
112
+ automatically proxied through the gateway for auditing and threat
113
+ detection.
114
+
115
+ Parameters
116
+ ----------
117
+ app:
118
+ The ASGI application to wrap.
119
+ gateway_url:
120
+ Base URL of the QuantaWatch gateway.
121
+ admin_url:
122
+ Base URL of the QuantaWatch admin API (used for health checks).
123
+
124
+ Example
125
+ -------
126
+ ::
127
+
128
+ from fastapi import FastAPI
129
+ from quantawatch.middleware import quantawatch_middleware
130
+
131
+ app = FastAPI()
132
+ app = quantawatch_middleware(app, gateway_url="http://localhost:9090")
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ app: ASGIApp,
138
+ gateway_url: str = "http://localhost:9090",
139
+ admin_url: str = "http://localhost:9091",
140
+ ) -> None:
141
+ self.app = app
142
+ self.gateway_url = gateway_url.rstrip("/")
143
+ self.admin_url = admin_url.rstrip("/")
144
+
145
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
146
+ """ASGI entry point.
147
+
148
+ Currently passes requests through unchanged. A future version
149
+ will inject gateway-aware HTTP clients into the request state so
150
+ that downstream route handlers automatically proxy AI calls.
151
+ """
152
+ # Store gateway config in scope for downstream access
153
+ if scope["type"] in ("http", "websocket"):
154
+ scope.setdefault("state", {})
155
+ scope["state"]["quantawatch_gateway_url"] = self.gateway_url
156
+ scope["state"]["quantawatch_admin_url"] = self.admin_url
157
+
158
+ await self.app(scope, receive, send)
159
+
160
+
161
+ def quantawatch_middleware(
162
+ app: ASGIApp,
163
+ *,
164
+ gateway_url: str = "http://localhost:9090",
165
+ admin_url: str = "http://localhost:9091",
166
+ ) -> QuantaWatchASGIMiddleware:
167
+ """Wrap an ASGI application with QuantaWatch middleware.
168
+
169
+ This is a convenience factory; it returns a
170
+ :class:`QuantaWatchASGIMiddleware` instance.
171
+
172
+ Parameters
173
+ ----------
174
+ app:
175
+ The ASGI application to wrap.
176
+ gateway_url:
177
+ Base URL of the QuantaWatch gateway.
178
+ admin_url:
179
+ Base URL of the QuantaWatch admin API.
180
+
181
+ Returns
182
+ -------
183
+ QuantaWatchASGIMiddleware
184
+ """
185
+ return QuantaWatchASGIMiddleware(app, gateway_url=gateway_url, admin_url=admin_url)
quantawatch/protect.py ADDED
@@ -0,0 +1,174 @@
1
+ """Convenience wrapper that routes AI client HTTP traffic through the QuantaWatch gateway.
2
+
3
+ Usage::
4
+
5
+ from anthropic import Anthropic
6
+ from quantawatch import protect
7
+
8
+ # All API calls now go through the QuantaWatch gateway
9
+ client = protect(Anthropic(), gateway_url="http://localhost:9090")
10
+ response = client.messages.create(...)
11
+
12
+ The wrapper is transparent: it preserves the original client's interface
13
+ so that existing code requires no changes beyond the ``protect()`` call.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ from typing import Any
20
+ from urllib.parse import urlparse
21
+
22
+ import httpx
23
+
24
+
25
+ _DEFAULT_GATEWAY_URL = "http://localhost:9090"
26
+
27
+
28
+ class _ProtectedTransport(httpx.BaseTransport):
29
+ """Synchronous httpx transport that rewrites requests to the gateway."""
30
+
31
+ def __init__(self, gateway_url: str, inner: httpx.BaseTransport) -> None:
32
+ self._gateway_url = gateway_url.rstrip("/")
33
+ self._inner = inner
34
+ parsed = urlparse(self._gateway_url)
35
+ self._gateway_host = parsed.hostname or "localhost"
36
+ self._gateway_port = parsed.port
37
+ self._gateway_scheme = parsed.scheme or "http"
38
+
39
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
40
+ # Rewrite the URL to point at the gateway, preserving path and query
41
+ original_url = request.url
42
+ new_url = original_url.copy_with(
43
+ scheme=self._gateway_scheme,
44
+ host=self._gateway_host,
45
+ port=self._gateway_port,
46
+ )
47
+ request.url = new_url
48
+ # Attach original host so the gateway knows which upstream to use
49
+ request.headers["X-Original-Host"] = str(original_url.host)
50
+ return self._inner.handle_request(request)
51
+
52
+
53
+ class _ProtectedAsyncTransport(httpx.AsyncBaseTransport):
54
+ """Asynchronous httpx transport that rewrites requests to the gateway."""
55
+
56
+ def __init__(self, gateway_url: str, inner: httpx.AsyncBaseTransport) -> None:
57
+ self._gateway_url = gateway_url.rstrip("/")
58
+ self._inner = inner
59
+ parsed = urlparse(self._gateway_url)
60
+ self._gateway_host = parsed.hostname or "localhost"
61
+ self._gateway_port = parsed.port
62
+ self._gateway_scheme = parsed.scheme or "http"
63
+
64
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
65
+ original_url = request.url
66
+ new_url = original_url.copy_with(
67
+ scheme=self._gateway_scheme,
68
+ host=self._gateway_host,
69
+ port=self._gateway_port,
70
+ )
71
+ request.url = new_url
72
+ request.headers["X-Original-Host"] = str(original_url.host)
73
+ return await self._inner.handle_async_request(request)
74
+
75
+
76
+ class _ProtectedClientProxy:
77
+ """Transparent proxy that wraps an AI SDK client.
78
+
79
+ Intercepts attribute access so that the wrapped client behaves identically
80
+ to the original, but all HTTP traffic is routed through the gateway.
81
+ """
82
+
83
+ def __init__(self, wrapped: Any, gateway_url: str) -> None:
84
+ # Store on the instance dict directly to avoid __getattr__ recursion
85
+ object.__setattr__(self, "_wrapped", wrapped)
86
+ object.__setattr__(self, "_gateway_url", gateway_url)
87
+ object.__setattr__(self, "_patched", False)
88
+ self._patch_http_client()
89
+
90
+ def _patch_http_client(self) -> None:
91
+ """Attempt to patch the underlying httpx client used by the AI SDK."""
92
+ wrapped = object.__getattribute__(self, "_wrapped")
93
+ gateway_url = object.__getattribute__(self, "_gateway_url")
94
+
95
+ # Anthropic SDK exposes _client (an httpx.Client or httpx.AsyncClient)
96
+ # OpenAI SDK similarly uses _client
97
+ for attr_name in ("_client", "http_client", "_http_client"):
98
+ http_client = getattr(wrapped, attr_name, None)
99
+ if http_client is None:
100
+ continue
101
+
102
+ if isinstance(http_client, httpx.Client):
103
+ original_transport = http_client._transport
104
+ http_client._transport = _ProtectedTransport(gateway_url, original_transport)
105
+ object.__setattr__(self, "_patched", True)
106
+ return
107
+
108
+ if isinstance(http_client, httpx.AsyncClient):
109
+ original_transport = http_client._transport
110
+ http_client._transport = _ProtectedAsyncTransport(gateway_url, original_transport)
111
+ object.__setattr__(self, "_patched", True)
112
+ return
113
+
114
+ # If we could not find an httpx client, the proxy still works --
115
+ # attribute access is forwarded unchanged. The user can manually
116
+ # configure their HTTP client to use the gateway.
117
+
118
+ def __getattr__(self, name: str) -> Any:
119
+ wrapped = object.__getattribute__(self, "_wrapped")
120
+ return getattr(wrapped, name)
121
+
122
+ def __setattr__(self, name: str, value: Any) -> None:
123
+ if name.startswith("_"):
124
+ object.__setattr__(self, name, value)
125
+ else:
126
+ setattr(object.__getattribute__(self, "_wrapped"), name, value)
127
+
128
+ def __repr__(self) -> str:
129
+ wrapped = object.__getattribute__(self, "_wrapped")
130
+ gateway_url = object.__getattribute__(self, "_gateway_url")
131
+ patched = object.__getattribute__(self, "_patched")
132
+ status = "active" if patched else "passthrough"
133
+ return f"<QuantaWatch-protected {type(wrapped).__name__} via {gateway_url} [{status}]>"
134
+
135
+
136
+ def protect(
137
+ client: Any,
138
+ *,
139
+ gateway_url: str = _DEFAULT_GATEWAY_URL,
140
+ ) -> Any:
141
+ """Wrap an AI SDK client so its HTTP traffic flows through the QuantaWatch gateway.
142
+
143
+ This is the simplest integration path: wrap your existing Anthropic, OpenAI,
144
+ or other httpx-based client and all requests are automatically proxied
145
+ through the gateway for threat detection and audit logging.
146
+
147
+ Parameters
148
+ ----------
149
+ client:
150
+ An AI SDK client instance (e.g. ``anthropic.Anthropic()``,
151
+ ``openai.OpenAI()``, or any object whose HTTP calls should be proxied).
152
+ gateway_url:
153
+ URL of the QuantaWatch gateway (default ``http://localhost:9090``).
154
+
155
+ Returns
156
+ -------
157
+ A proxy object that behaves identically to *client* but routes HTTP
158
+ traffic through the gateway.
159
+
160
+ Examples
161
+ --------
162
+ ::
163
+
164
+ from anthropic import Anthropic
165
+ from quantawatch import protect
166
+
167
+ client = protect(Anthropic(), gateway_url="http://localhost:9090")
168
+ response = client.messages.create(
169
+ model="claude-sonnet-4-20250514",
170
+ max_tokens=1024,
171
+ messages=[{"role": "user", "content": "Hello!"}],
172
+ )
173
+ """
174
+ return _ProtectedClientProxy(client, gateway_url)
quantawatch/types.py ADDED
@@ -0,0 +1,84 @@
1
+ """Pydantic models for the QuantaWatch SDK.
2
+
3
+ These models correspond to the JSON schemas returned by the QuantaWatch
4
+ gateway and admin APIs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel, Field
13
+
14
+
15
+ class SessionInfo(BaseModel):
16
+ """Represents an active or historical gateway session."""
17
+
18
+ session_id: str = Field(description="Unique identifier for the session")
19
+ agent_name: str = Field(description="Name of the AI agent that owns the session")
20
+ created_at: datetime = Field(description="When the session was created")
21
+ expires_at: datetime = Field(description="When the session expires")
22
+ request_count: int = Field(
23
+ default=0, description="Number of requests made in this session"
24
+ )
25
+ total_tokens: int = Field(
26
+ default=0, description="Total tokens consumed in this session"
27
+ )
28
+ public_key_fingerprint: str = Field(
29
+ default="", description="Fingerprint of the public key used to create the session"
30
+ )
31
+
32
+
33
+ class DetectedThreat(BaseModel):
34
+ """A single threat detected by the gateway's threat analysis engine."""
35
+
36
+ category: str = Field(description="Threat category (e.g. prompt_injection, data_exfil)")
37
+ severity: str = Field(description="Severity level: low, medium, high, critical")
38
+ pattern_name: str = Field(description="Name of the detection pattern that matched")
39
+ confidence: float = Field(
40
+ ge=0.0, le=1.0, description="Confidence score between 0 and 1"
41
+ )
42
+ description: str = Field(description="Human-readable description of the threat")
43
+
44
+
45
+ class ThreatAssessment(BaseModel):
46
+ """Result of running threat analysis on a request or response."""
47
+
48
+ threats: list[DetectedThreat] = Field(
49
+ default_factory=list, description="List of detected threats"
50
+ )
51
+ overall_severity: str = Field(
52
+ default="none",
53
+ description="Highest severity among all detected threats, or 'none'",
54
+ )
55
+ blocked: bool = Field(
56
+ default=False, description="Whether the request was blocked by the gateway"
57
+ )
58
+
59
+
60
+ class AuditEntry(BaseModel):
61
+ """A single entry in the cryptographic audit log."""
62
+
63
+ sequence: int = Field(description="Monotonically increasing sequence number")
64
+ timestamp: datetime = Field(description="When the event occurred")
65
+ event_type: str = Field(
66
+ description="Type of event (e.g. session_created, request_proxied, threat_detected)"
67
+ )
68
+ session_id: str = Field(description="Session this event belongs to")
69
+ details: dict[str, Any] = Field(
70
+ default_factory=dict, description="Arbitrary event-specific metadata"
71
+ )
72
+ signature: str = Field(
73
+ default="", description="Cryptographic signature chaining this entry to the previous one"
74
+ )
75
+
76
+
77
+ class GatewayStats(BaseModel):
78
+ """Aggregate statistics from the QuantaWatch gateway."""
79
+
80
+ total_sessions: int = Field(default=0, description="Total sessions created since startup")
81
+ active_sessions: int = Field(default=0, description="Currently active sessions")
82
+ total_requests: int = Field(default=0, description="Total requests proxied")
83
+ total_audit_entries: int = Field(default=0, description="Total audit log entries")
84
+ active_threats: int = Field(default=0, description="Currently active/unresolved threats")
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantawatch
3
+ Version: 0.1.0
4
+ Summary: Python SDK for QuantaWatch — AI agent security gateway
5
+ Project-URL: Homepage, https://github.com/dyber-pqc/QuantaWatch
6
+ Project-URL: Documentation, https://github.com/dyber-pqc/QuantaWatch#readme
7
+ Project-URL: Repository, https://github.com/dyber-pqc/QuantaWatch.git
8
+ Project-URL: Issues, https://github.com/dyber-pqc/QuantaWatch/issues
9
+ Author: QuantaWatch Team
10
+ License-Expression: MIT
11
+ Keywords: agent,ai,audit,gateway,llm,security
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx>=0.25
25
+ Requires-Dist: pydantic>=2
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
28
+ Requires-Dist: pytest>=7; extra == 'dev'
29
+ Provides-Extra: langchain
30
+ Requires-Dist: langchain-core>=0.1; extra == 'langchain'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # QuantaWatch Python SDK
34
+
35
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](../../LICENSE)
36
+
37
+ Python SDK for [QuantaWatch](https://github.com/dyber-pqc/QuantaWatch) — the post-quantum security layer for AI agents.
38
+
39
+ Route your AI SDK traffic through the QuantaWatch gateway for threat detection, policy enforcement, and tamper-evident audit logging — all signed with post-quantum cryptography (ML-DSA-65).
40
+
41
+ ## Installation
42
+
43
+ > Not yet published to PyPI. Install from source until the first release.
44
+
45
+ ```bash
46
+ git clone https://github.com/dyber-pqc/QuantaWatch.git
47
+ pip install -e QuantaWatch/sdk/python
48
+ ```
49
+
50
+ **Requirements:** Python 3.10+
51
+
52
+ ## Quick Start
53
+
54
+ ### Option 1: Protect an existing AI client (recommended)
55
+
56
+ The `protect()` wrapper transparently routes your existing SDK's HTTP traffic through the gateway. No code changes needed beyond the wrap call.
57
+
58
+ ```python
59
+ from anthropic import Anthropic
60
+ from quantawatch import protect
61
+
62
+ # One line — all API calls now flow through QuantaWatch
63
+ client = protect(Anthropic(), gateway_url="http://localhost:9090")
64
+
65
+ # Use the client exactly as before
66
+ response = client.messages.create(
67
+ model="claude-sonnet-4-20250514",
68
+ max_tokens=1024,
69
+ messages=[{"role": "user", "content": "Hello!"}],
70
+ )
71
+ ```
72
+
73
+ Works with any httpx-based SDK, including OpenAI:
74
+
75
+ ```python
76
+ from openai import OpenAI
77
+ from quantawatch import protect
78
+
79
+ client = protect(OpenAI(), gateway_url="http://localhost:9090")
80
+ response = client.chat.completions.create(
81
+ model="gpt-4o",
82
+ messages=[{"role": "user", "content": "Hello!"}],
83
+ )
84
+ ```
85
+
86
+ ### Option 2: Use the gateway client directly
87
+
88
+ The `QuantaWatchClient` gives you direct access to the gateway proxy and admin API.
89
+
90
+ ```python
91
+ import asyncio
92
+ from quantawatch import QuantaWatchClient
93
+
94
+ async def main():
95
+ async with QuantaWatchClient() as qw:
96
+ # Proxy a raw request through the gateway
97
+ response = await qw.proxy_request(
98
+ "POST",
99
+ "/v1/messages",
100
+ headers={
101
+ "x-api-key": "sk-ant-...",
102
+ "anthropic-version": "2023-06-01",
103
+ "Content-Type": "application/json",
104
+ },
105
+ body=b'{"model":"claude-sonnet-4-20250514","max_tokens":1024,"messages":[{"role":"user","content":"Hello!"}]}',
106
+ )
107
+ print(response.status_code, response.text)
108
+
109
+ # Query the admin API
110
+ sessions = await qw.get_sessions()
111
+ stats = await qw.get_stats()
112
+ audit = await qw.get_audit_entries(limit=10)
113
+
114
+ # Verify audit chain integrity
115
+ result = await qw.verify_audit_chain()
116
+ print("Audit chain valid:", result.get("valid"))
117
+
118
+ asyncio.run(main())
119
+ ```
120
+
121
+ ## API Reference
122
+
123
+ ### `protect(client, *, gateway_url="http://localhost:9090")`
124
+
125
+ Wraps an AI SDK client so its HTTP traffic flows through the QuantaWatch gateway.
126
+
127
+ | Parameter | Type | Default | Description |
128
+ |-----------|------|---------|-------------|
129
+ | `client` | `Any` | — | An AI SDK client (Anthropic, OpenAI, or any httpx-based client) |
130
+ | `gateway_url` | `str` | `http://localhost:9090` | URL of the QuantaWatch gateway |
131
+
132
+ Returns a proxy object that behaves identically to the original client.
133
+
134
+ ### `QuantaWatchClient`
135
+
136
+ Async client for the QuantaWatch gateway and admin APIs.
137
+
138
+ ```python
139
+ QuantaWatchClient(
140
+ gateway_url="http://localhost:9090",
141
+ admin_url="http://localhost:9091",
142
+ timeout=30.0,
143
+ )
144
+ ```
145
+
146
+ | Method | Description |
147
+ |--------|-------------|
148
+ | `proxy_request(method, path, headers, body)` | Proxy an HTTP request through the gateway |
149
+ | `get_sessions()` | List all gateway sessions |
150
+ | `get_audit_entries(limit=100)` | Fetch recent audit log entries |
151
+ | `get_stats()` | Fetch aggregate gateway statistics |
152
+ | `verify_audit_chain()` | Verify cryptographic audit chain integrity |
153
+ | `close()` | Close the underlying HTTP client |
154
+
155
+ ### Types
156
+
157
+ All response types are [Pydantic](https://docs.pydantic.dev/) models:
158
+
159
+ - `SessionInfo` — Gateway session with agent name, token count, PQC key fingerprint
160
+ - `AuditEntry` — Signed audit log entry with sequence number and hash chain
161
+ - `GatewayStats` — Aggregate stats (sessions, requests, threats, audit entries)
162
+ - `ThreatAssessment` — Threat analysis result with severity and blocked status
163
+ - `DetectedThreat` — Individual threat with category, severity, confidence, and pattern name
164
+
165
+ ## Prerequisites
166
+
167
+ The SDK requires a running QuantaWatch gateway. Start one with Docker:
168
+
169
+ ```bash
170
+ git clone https://github.com/dyber-pqc/QuantaWatch.git
171
+ cd QuantaWatch
172
+ cp quantawatch.yaml.example quantawatch.yaml
173
+ export ANTHROPIC_API_KEY=sk-ant-...
174
+ docker compose up -d
175
+ ```
176
+
177
+ Or build from source:
178
+
179
+ ```bash
180
+ cargo run -p qw-gateway -- quantawatch.yaml
181
+ ```
182
+
183
+ ## Development
184
+
185
+ ```bash
186
+ # Install with dev dependencies
187
+ pip install -e ".[dev]"
188
+
189
+ # Run tests
190
+ pytest
191
+
192
+ # Type checking (if mypy installed)
193
+ mypy quantawatch/
194
+ ```
195
+
196
+ ## License
197
+
198
+ [Apache License 2.0](../../LICENSE)
199
+
200
+ ## Links
201
+
202
+ - [QuantaWatch repository](https://github.com/dyber-pqc/QuantaWatch)
203
+ - [OpenAPI spec](https://github.com/dyber-pqc/QuantaWatch/blob/main/docs/openapi.yaml)
204
+ - [Examples](https://github.com/dyber-pqc/QuantaWatch/tree/main/examples)
@@ -0,0 +1,8 @@
1
+ quantawatch/__init__.py,sha256=Zl1yOG6bQt1h3BiRmG2rbu_0CxSRB91ldn40JdSrxk8,847
2
+ quantawatch/client.py,sha256=3agDtY6WiWnqUJ7IyAJtYVuMZ2LCQ_n8GzJTSHCiusI,5103
3
+ quantawatch/middleware.py,sha256=tqOPj1rk-9YV4IasgM-GWHsHwqDO8FE-5Rag-7VfvYs,6283
4
+ quantawatch/protect.py,sha256=xlHWzrcV3OUKhWoQ-_iDC2jsuk-xshg6q8WdgKh9vhc,6638
5
+ quantawatch/types.py,sha256=nrHvP9UITAPxTCcvG4wgUVrxMOXQS6ThEG5yKYPknew,3329
6
+ quantawatch-0.1.0.dist-info/METADATA,sha256=ow_DvZIu2hf68GoPETX-cvPZDze4p8z2FD0BqX3ss84,6483
7
+ quantawatch-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
8
+ quantawatch-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any