getstack 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.
getstack/__init__.py ADDED
@@ -0,0 +1,233 @@
1
+ """STACK Python SDK — trust infrastructure for AI agents.
2
+
3
+ Usage::
4
+
5
+ from getstack import Stack
6
+
7
+ stack = Stack(api_key="sk_live_...")
8
+ agent = stack.agents.register("my-agent")
9
+
10
+ with stack.passports.mission(
11
+ agent_id=agent.id,
12
+ intent="Process invoices",
13
+ services=["slack", "stripe"],
14
+ ) as mission:
15
+ mission.log("slack", "read_channel", "#invoices")
16
+ mission.log("stripe", "create_invoice")
17
+
18
+ For OAuth auth::
19
+
20
+ stack = Stack.from_oauth(
21
+ client_id="...",
22
+ client_secret="...",
23
+ access_token="...",
24
+ refresh_token="...",
25
+ )
26
+
27
+ For async usage::
28
+
29
+ from getstack import AsyncStack
30
+
31
+ stack = AsyncStack(api_key="sk_live_...")
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from .auth import ApiKeyAuth, SessionAuth, OAuthAuth
37
+ from .client import HttpClient, AsyncHttpClient, DEFAULT_BASE_URL
38
+ from .agents import AgentService
39
+ from .passports import PassportService, Mission
40
+ from .credentials import CredentialService
41
+ from .services import ServiceService
42
+ from .dropoffs import DropoffService
43
+ from .reviews import ReviewService
44
+ from .notifications import NotificationService
45
+ from .audit import AuditService
46
+ from .types import (
47
+ Agent,
48
+ Passport,
49
+ CheckpointResult,
50
+ CheckoutResult,
51
+ ReviewFlag,
52
+ PassportReport,
53
+ ReviewQueue,
54
+ ReviewQueueItem,
55
+ ReviewDecisionResult,
56
+ Credential,
57
+ NotificationChannel,
58
+ ToolCall,
59
+ )
60
+ from .errors import (
61
+ StackError,
62
+ NotFoundError,
63
+ UnauthorizedError,
64
+ ForbiddenError,
65
+ ValidationError,
66
+ PassportBlockedError,
67
+ )
68
+
69
+ __version__ = "0.1.0"
70
+
71
+ __all__ = [
72
+ "Stack",
73
+ "AsyncStack",
74
+ "__version__",
75
+ # Types
76
+ "Agent",
77
+ "Passport",
78
+ "CheckpointResult",
79
+ "CheckoutResult",
80
+ "ReviewFlag",
81
+ "PassportReport",
82
+ "ReviewQueue",
83
+ "ReviewQueueItem",
84
+ "ReviewDecisionResult",
85
+ "Credential",
86
+ "NotificationChannel",
87
+ "Mission",
88
+ "ToolCall",
89
+ # Errors
90
+ "StackError",
91
+ "NotFoundError",
92
+ "UnauthorizedError",
93
+ "ForbiddenError",
94
+ "ValidationError",
95
+ "PassportBlockedError",
96
+ ]
97
+
98
+
99
+ class Stack:
100
+ """Synchronous STACK client.
101
+
102
+ Args:
103
+ api_key: A STACK API key (``sk_live_...``).
104
+ base_url: Override the API base URL.
105
+ timeout: HTTP timeout in seconds.
106
+ """
107
+
108
+ def __init__(
109
+ self,
110
+ api_key: str | None = None,
111
+ *,
112
+ base_url: str = DEFAULT_BASE_URL,
113
+ timeout: float = 30.0,
114
+ _auth: ApiKeyAuth | SessionAuth | OAuthAuth | None = None,
115
+ ):
116
+ if _auth:
117
+ auth = _auth
118
+ elif api_key:
119
+ auth = ApiKeyAuth(api_key)
120
+ else:
121
+ raise ValueError("Either api_key or _auth must be provided")
122
+
123
+ self._client = HttpClient(auth, base_url=base_url, timeout=timeout)
124
+ self.agents = AgentService(self._client)
125
+ self.passports = PassportService(self._client)
126
+ self.credentials = CredentialService(self._client)
127
+ self.services = ServiceService(self._client)
128
+ self.dropoffs = DropoffService(self._client)
129
+ self.reviews = ReviewService(self._client)
130
+ self.notifications = NotificationService(self._client)
131
+ self.audit = AuditService(self._client)
132
+
133
+ @classmethod
134
+ def from_session(cls, session_token: str, **kwargs) -> Stack:
135
+ """Create a client authenticated with a session JWT."""
136
+ return cls(_auth=SessionAuth(session_token), **kwargs)
137
+
138
+ @classmethod
139
+ def from_oauth(
140
+ cls,
141
+ client_id: str,
142
+ client_secret: str,
143
+ access_token: str,
144
+ refresh_token: str,
145
+ token_endpoint: str = "https://api.getstack.run/v1/oauth/token",
146
+ **kwargs,
147
+ ) -> Stack:
148
+ """Create a client with OAuth tokens. Auto-refreshes when expired."""
149
+ auth = OAuthAuth(
150
+ client_id=client_id,
151
+ client_secret=client_secret,
152
+ access_token=access_token,
153
+ refresh_token=refresh_token,
154
+ token_endpoint=token_endpoint,
155
+ )
156
+ return cls(_auth=auth, **kwargs)
157
+
158
+ def close(self) -> None:
159
+ """Close the underlying HTTP client."""
160
+ self._client.close()
161
+
162
+ def __enter__(self) -> Stack:
163
+ return self
164
+
165
+ def __exit__(self, *args) -> None:
166
+ self.close()
167
+
168
+
169
+ class AsyncStack:
170
+ """Asynchronous STACK client.
171
+
172
+ Uses httpx.AsyncClient under the hood. All service methods are sync
173
+ (they use the sync HttpClient wrapper) — for true async, the async
174
+ client needs async service modules. This provides the async HTTP
175
+ transport layer for future async service implementations.
176
+
177
+ Args:
178
+ api_key: A STACK API key (``sk_live_...``).
179
+ base_url: Override the API base URL.
180
+ timeout: HTTP timeout in seconds.
181
+ """
182
+
183
+ def __init__(
184
+ self,
185
+ api_key: str | None = None,
186
+ *,
187
+ base_url: str = DEFAULT_BASE_URL,
188
+ timeout: float = 30.0,
189
+ _auth: ApiKeyAuth | SessionAuth | OAuthAuth | None = None,
190
+ ):
191
+ if _auth:
192
+ auth = _auth
193
+ elif api_key:
194
+ auth = ApiKeyAuth(api_key)
195
+ else:
196
+ raise ValueError("Either api_key or _auth must be provided")
197
+
198
+ self._client = AsyncHttpClient(auth, base_url=base_url, timeout=timeout)
199
+
200
+ @classmethod
201
+ def from_session(cls, session_token: str, **kwargs) -> AsyncStack:
202
+ """Create an async client authenticated with a session JWT."""
203
+ return cls(_auth=SessionAuth(session_token), **kwargs)
204
+
205
+ @classmethod
206
+ def from_oauth(
207
+ cls,
208
+ client_id: str,
209
+ client_secret: str,
210
+ access_token: str,
211
+ refresh_token: str,
212
+ token_endpoint: str = "https://api.getstack.run/v1/oauth/token",
213
+ **kwargs,
214
+ ) -> AsyncStack:
215
+ """Create an async client with OAuth tokens. Auto-refreshes when expired."""
216
+ auth = OAuthAuth(
217
+ client_id=client_id,
218
+ client_secret=client_secret,
219
+ access_token=access_token,
220
+ refresh_token=refresh_token,
221
+ token_endpoint=token_endpoint,
222
+ )
223
+ return cls(_auth=auth, **kwargs)
224
+
225
+ async def close(self) -> None:
226
+ """Close the underlying HTTP client."""
227
+ await self._client.close()
228
+
229
+ async def __aenter__(self) -> AsyncStack:
230
+ return self
231
+
232
+ async def __aexit__(self, *args) -> None:
233
+ await self.close()
getstack/agents.py ADDED
@@ -0,0 +1,70 @@
1
+ """Agent management."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from .client import HttpClient
8
+ from .types import Agent
9
+
10
+
11
+ def _to_agent(data: dict[str, Any]) -> Agent:
12
+ return Agent(
13
+ id=data["id"],
14
+ operator_id=data["operator_id"],
15
+ name=data["name"],
16
+ description=data.get("description"),
17
+ status=data["status"],
18
+ accountability_mode=data.get("accountability_mode", "standard"),
19
+ on_warning=data.get("on_warning", "notify"),
20
+ on_critical=data.get("on_critical", "notify"),
21
+ passport_blocked=data.get("passport_blocked", False),
22
+ passport_blocked_reason=data.get("passport_blocked_reason"),
23
+ passport_blocked_at=data.get("passport_blocked_at"),
24
+ created_at=data["created_at"],
25
+ updated_at=data["updated_at"],
26
+ )
27
+
28
+
29
+ class AgentService:
30
+ def __init__(self, client: HttpClient):
31
+ self._client = client
32
+
33
+ def register(
34
+ self,
35
+ name: str,
36
+ description: str | None = None,
37
+ accountability_mode: str = "enforced",
38
+ on_warning: str = "notify",
39
+ on_critical: str = "notify",
40
+ ) -> Agent:
41
+ body: dict[str, Any] = {"name": name, "accountability_mode": accountability_mode}
42
+ if description:
43
+ body["description"] = description
44
+ if on_warning != "notify":
45
+ body["on_warning"] = on_warning
46
+ if on_critical != "notify":
47
+ body["on_critical"] = on_critical
48
+ return _to_agent(self._client.post("/v1/agents/register", json=body))
49
+
50
+ def get(self, agent_id: str) -> Agent:
51
+ return _to_agent(self._client.get(f"/v1/agents/{agent_id}"))
52
+
53
+ def list(self) -> list[Agent]:
54
+ data = self._client.get("/v1/agents")
55
+ return [_to_agent(a) for a in data]
56
+
57
+ def update(self, agent_id: str, **kwargs: Any) -> Agent:
58
+ return _to_agent(self._client.patch(f"/v1/agents/{agent_id}", json=kwargs))
59
+
60
+ def suspend(self, agent_id: str) -> Agent:
61
+ return self.update(agent_id, status="suspended")
62
+
63
+ def activate(self, agent_id: str) -> Agent:
64
+ return self.update(agent_id, status="active")
65
+
66
+ def delete(self, agent_id: str) -> dict[str, Any]:
67
+ return self._client.delete(f"/v1/agents/{agent_id}")
68
+
69
+ def unblock(self, agent_id: str) -> dict[str, Any]:
70
+ return self._client.post(f"/v1/agents/{agent_id}/unblock")
getstack/audit.py ADDED
@@ -0,0 +1,26 @@
1
+ """Audit log access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from .client import HttpClient
8
+
9
+
10
+ class AuditService:
11
+ def __init__(self, client: HttpClient):
12
+ self._client = client
13
+
14
+ def list(
15
+ self,
16
+ page: int = 1,
17
+ limit: int = 50,
18
+ action: str | None = None,
19
+ agent_id: str | None = None,
20
+ ) -> list[dict[str, Any]]:
21
+ params: dict[str, str] = {"page": str(page), "limit": str(limit)}
22
+ if action:
23
+ params["action"] = action
24
+ if agent_id:
25
+ params["agent_id"] = agent_id
26
+ return self._client.get("/v1/audit", params=params)
getstack/auth.py ADDED
@@ -0,0 +1,78 @@
1
+ """Authentication strategies for the STACK SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from abc import ABC, abstractmethod
7
+
8
+ import httpx
9
+
10
+
11
+ class AuthStrategy(ABC):
12
+ """Base class for auth strategies."""
13
+
14
+ @abstractmethod
15
+ def get_headers(self) -> dict[str, str]:
16
+ """Return auth headers for API requests."""
17
+ ...
18
+
19
+
20
+ class ApiKeyAuth(AuthStrategy):
21
+ """Authenticate with a STACK API key (sk_live_...)."""
22
+
23
+ def __init__(self, api_key: str):
24
+ self.api_key = api_key
25
+
26
+ def get_headers(self) -> dict[str, str]:
27
+ return {"Authorization": f"Bearer {self.api_key}"}
28
+
29
+
30
+ class SessionAuth(AuthStrategy):
31
+ """Authenticate with a session JWT (dashboard integrations)."""
32
+
33
+ def __init__(self, session_token: str):
34
+ self.session_token = session_token
35
+
36
+ def get_headers(self) -> dict[str, str]:
37
+ return {"Authorization": f"Bearer {self.session_token}"}
38
+
39
+
40
+ class OAuthAuth(AuthStrategy):
41
+ """Authenticate with OAuth tokens. Auto-refreshes when expired."""
42
+
43
+ def __init__(
44
+ self,
45
+ client_id: str,
46
+ client_secret: str,
47
+ access_token: str,
48
+ refresh_token: str,
49
+ token_endpoint: str = "https://api.getstack.run/v1/oauth/token",
50
+ ):
51
+ self.client_id = client_id
52
+ self.client_secret = client_secret
53
+ self.access_token = access_token
54
+ self.refresh_token = refresh_token
55
+ self.token_endpoint = token_endpoint
56
+ self.expires_at: float | None = None
57
+
58
+ def get_headers(self) -> dict[str, str]:
59
+ if self.expires_at and time.time() > self.expires_at - 30:
60
+ self._refresh()
61
+ return {"Authorization": f"Bearer {self.access_token}"}
62
+
63
+ def _refresh(self) -> None:
64
+ """Exchange refresh_token for a new access_token."""
65
+ resp = httpx.post(
66
+ self.token_endpoint,
67
+ data={
68
+ "grant_type": "refresh_token",
69
+ "refresh_token": self.refresh_token,
70
+ "client_id": self.client_id,
71
+ "client_secret": self.client_secret,
72
+ },
73
+ )
74
+ resp.raise_for_status()
75
+ data = resp.json()
76
+ self.access_token = data["access_token"]
77
+ self.refresh_token = data.get("refresh_token", self.refresh_token)
78
+ self.expires_at = time.time() + data.get("expires_in", 3600)
getstack/client.py ADDED
@@ -0,0 +1,102 @@
1
+ """HTTP client for the STACK API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from .auth import AuthStrategy
10
+ from .errors import raise_for_status
11
+
12
+ DEFAULT_BASE_URL = "https://api.getstack.run"
13
+
14
+
15
+ class HttpClient:
16
+ """Synchronous HTTP client wrapping httpx."""
17
+
18
+ def __init__(self, auth: AuthStrategy, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
19
+ self.auth = auth
20
+ self.base_url = base_url.rstrip("/")
21
+ self._client = httpx.Client(timeout=timeout)
22
+
23
+ def request(self, method: str, path: str, json: Any = None, params: dict[str, Any] | None = None) -> Any:
24
+ headers = {
25
+ "Content-Type": "application/json",
26
+ **self.auth.get_headers(),
27
+ }
28
+
29
+ url = f"{self.base_url}{path}"
30
+ resp = self._client.request(method, url, json=json, params=params, headers=headers)
31
+
32
+ if resp.status_code >= 400:
33
+ try:
34
+ body = resp.json()
35
+ except Exception:
36
+ body = {"error": {"message": resp.text}}
37
+ raise_for_status(resp.status_code, body)
38
+
39
+ if resp.status_code == 204:
40
+ return None
41
+
42
+ return resp.json()
43
+
44
+ def get(self, path: str, params: dict[str, Any] | None = None) -> Any:
45
+ return self.request("GET", path, params=params)
46
+
47
+ def post(self, path: str, json: Any = None) -> Any:
48
+ return self.request("POST", path, json=json)
49
+
50
+ def patch(self, path: str, json: Any = None) -> Any:
51
+ return self.request("PATCH", path, json=json)
52
+
53
+ def delete(self, path: str) -> Any:
54
+ return self.request("DELETE", path)
55
+
56
+ def close(self) -> None:
57
+ self._client.close()
58
+
59
+
60
+ class AsyncHttpClient:
61
+ """Asynchronous HTTP client wrapping httpx."""
62
+
63
+ def __init__(self, auth: AuthStrategy, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
64
+ self.auth = auth
65
+ self.base_url = base_url.rstrip("/")
66
+ self._client = httpx.AsyncClient(timeout=timeout)
67
+
68
+ async def request(self, method: str, path: str, json: Any = None, params: dict[str, Any] | None = None) -> Any:
69
+ headers = {
70
+ "Content-Type": "application/json",
71
+ **self.auth.get_headers(),
72
+ }
73
+
74
+ url = f"{self.base_url}{path}"
75
+ resp = await self._client.request(method, url, json=json, params=params, headers=headers)
76
+
77
+ if resp.status_code >= 400:
78
+ try:
79
+ body = resp.json()
80
+ except Exception:
81
+ body = {"error": {"message": resp.text}}
82
+ raise_for_status(resp.status_code, body)
83
+
84
+ if resp.status_code == 204:
85
+ return None
86
+
87
+ return resp.json()
88
+
89
+ async def get(self, path: str, params: dict[str, Any] | None = None) -> Any:
90
+ return await self.request("GET", path, params=params)
91
+
92
+ async def post(self, path: str, json: Any = None) -> Any:
93
+ return await self.request("POST", path, json=json)
94
+
95
+ async def patch(self, path: str, json: Any = None) -> Any:
96
+ return await self.request("PATCH", path, json=json)
97
+
98
+ async def delete(self, path: str) -> Any:
99
+ return await self.request("DELETE", path)
100
+
101
+ async def close(self) -> None:
102
+ await self._client.aclose()
@@ -0,0 +1,33 @@
1
+ """Credential retrieval."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from urllib.parse import quote
7
+
8
+ from .client import HttpClient
9
+ from .types import Credential
10
+
11
+
12
+ class CredentialService:
13
+ def __init__(self, client: HttpClient):
14
+ self._client = client
15
+
16
+ def get(self, provider: str, passport: Any | None = None) -> Credential:
17
+ headers_extra = {}
18
+ if passport and hasattr(passport, "token"):
19
+ headers_extra["X-Passport-Token"] = passport.token
20
+ data = self._client.get(f"/v1/credentials/{quote(provider)}")
21
+ return Credential(
22
+ provider=data["provider"],
23
+ credential=data.get("credential"),
24
+ credentials=data.get("credentials"),
25
+ )
26
+
27
+ def get_by_connection(self, connection_id: str) -> Credential:
28
+ data = self._client.get(f"/v1/credentials/by-connection/{connection_id}")
29
+ return Credential(
30
+ provider=data["provider"],
31
+ credential=data.get("credential"),
32
+ credentials=data.get("credentials"),
33
+ )
getstack/dropoffs.py ADDED
@@ -0,0 +1,43 @@
1
+ """Drop-off management."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from .client import HttpClient
8
+
9
+
10
+ class DropoffService:
11
+ def __init__(self, client: HttpClient):
12
+ self._client = client
13
+
14
+ def create(
15
+ self,
16
+ from_agent_id: str,
17
+ to_agent_id: str,
18
+ schema: dict[str, Any],
19
+ ttl_seconds: int | None = None,
20
+ on_expire: str | None = None,
21
+ ) -> dict[str, Any]:
22
+ body: dict[str, Any] = {
23
+ "from_agent": from_agent_id,
24
+ "to_agent": to_agent_id,
25
+ "schema": schema,
26
+ }
27
+ if ttl_seconds:
28
+ body["ttl_seconds"] = ttl_seconds
29
+ if on_expire:
30
+ body["on_expire"] = on_expire
31
+ return self._client.post("/v1/dropoffs", json=body)
32
+
33
+ def deposit(self, dropoff_id: str, data: dict[str, Any], agent_id: str) -> dict[str, Any]:
34
+ return self._client.post(f"/v1/dropoffs/{dropoff_id}/deposit", json={"agent_id": agent_id, "payload": data})
35
+
36
+ def collect(self, dropoff_id: str, agent_id: str) -> dict[str, Any]:
37
+ return self._client.post(f"/v1/dropoffs/{dropoff_id}/collect", json={"agent_id": agent_id})
38
+
39
+ def get(self, dropoff_id: str) -> dict[str, Any]:
40
+ return self._client.get(f"/v1/dropoffs/{dropoff_id}")
41
+
42
+ def list(self) -> list[dict[str, Any]]:
43
+ return self._client.get("/v1/dropoffs")
getstack/errors.py ADDED
@@ -0,0 +1,56 @@
1
+ """STACK SDK error classes."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class StackError(Exception):
7
+ """Base error for all STACK API errors."""
8
+
9
+ def __init__(self, message: str, code: str = "UNKNOWN", status_code: int = 500, details: dict | None = None):
10
+ super().__init__(message)
11
+ self.code = code
12
+ self.status_code = status_code
13
+ self.details = details or {}
14
+
15
+
16
+ class NotFoundError(StackError):
17
+ def __init__(self, message: str = "Resource not found"):
18
+ super().__init__(message, "NOT_FOUND", 404)
19
+
20
+
21
+ class UnauthorizedError(StackError):
22
+ def __init__(self, message: str = "Unauthorized"):
23
+ super().__init__(message, "UNAUTHORIZED", 401)
24
+
25
+
26
+ class ForbiddenError(StackError):
27
+ def __init__(self, message: str = "Forbidden"):
28
+ super().__init__(message, "FORBIDDEN", 403)
29
+
30
+
31
+ class ValidationError(StackError):
32
+ def __init__(self, message: str = "Validation failed", details: dict | None = None):
33
+ super().__init__(message, "VALIDATION_ERROR", 400, details)
34
+
35
+
36
+ class PassportBlockedError(StackError):
37
+ def __init__(self, message: str = "Agent is blocked from passport issuance"):
38
+ super().__init__(message, "PASSPORT_BLOCKED", 403)
39
+
40
+
41
+ # Map HTTP status codes to error classes
42
+ _STATUS_MAP = {
43
+ 401: UnauthorizedError,
44
+ 403: ForbiddenError,
45
+ 404: NotFoundError,
46
+ }
47
+
48
+
49
+ def raise_for_status(status_code: int, body: dict) -> None:
50
+ """Raise an appropriate StackError from an API error response."""
51
+ error = body.get("error", {})
52
+ message = error.get("message", f"API error: {status_code}")
53
+ code = error.get("code", "UNKNOWN")
54
+
55
+ cls = _STATUS_MAP.get(status_code, StackError)
56
+ raise cls(message)