agentcredia 0.0.1a1__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.
Potentially problematic release.
This version of agentcredia might be problematic. Click here for more details.
- agentcredia/__init__.py +57 -0
- agentcredia/_client.py +216 -0
- agentcredia/_errors.py +97 -0
- agentcredia/_version.py +8 -0
- agentcredia/resources/__init__.py +1 -0
- agentcredia/resources/agents.py +65 -0
- agentcredia/resources/api_keys.py +131 -0
- agentcredia/resources/payment_requests.py +86 -0
- agentcredia/resources/payments.py +91 -0
- agentcredia/resources/transactions.py +35 -0
- agentcredia/webhooks.py +229 -0
- agentcredia-0.0.1a1.dist-info/METADATA +188 -0
- agentcredia-0.0.1a1.dist-info/RECORD +15 -0
- agentcredia-0.0.1a1.dist-info/WHEEL +4 -0
- agentcredia-0.0.1a1.dist-info/licenses/LICENSE +201 -0
agentcredia/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AgentCredia Python SDK.
|
|
3
|
+
|
|
4
|
+
Public exports:
|
|
5
|
+
Client main HTTP client (`client.api_keys.*`, etc.)
|
|
6
|
+
webhooks webhook signature verifier module
|
|
7
|
+
AgentCrediaError base exception class
|
|
8
|
+
ApiKeyError 401/403 apikey.* envelope subclass
|
|
9
|
+
ApiKeyCodes 13 stable apikey.* failure codes (sub-plan 21.3 C-8)
|
|
10
|
+
WebhookSignatureError raised by webhooks.verify(raise_on_fail=True)
|
|
11
|
+
WalletAssignment typed entry for create_workspace_key(walletAssignments=...)
|
|
12
|
+
|
|
13
|
+
Example:
|
|
14
|
+
from agentcredia import Client, webhooks
|
|
15
|
+
client = Client(api_key="sk_test_...")
|
|
16
|
+
keys = client.api_keys.list()
|
|
17
|
+
|
|
18
|
+
# In your webhook handler:
|
|
19
|
+
result = webhooks.verify(headers=req.headers, raw_body=req.body, secret=secret)
|
|
20
|
+
if not result.ok:
|
|
21
|
+
return JSONResponse({"code": result.code}, status_code=400)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from . import webhooks
|
|
25
|
+
from ._errors import ApiKeyCodes, ApiKeyError, AgentCrediaError, WebhookSignatureError
|
|
26
|
+
from .resources.api_keys import WalletAssignment
|
|
27
|
+
from .resources.payment_requests import PaymentRequestSettleBody
|
|
28
|
+
from .resources.payments import PaymentCreateBody
|
|
29
|
+
from ._version import __version__
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"ApiKeyCodes",
|
|
33
|
+
"ApiKeyError",
|
|
34
|
+
"AgentCrediaError",
|
|
35
|
+
"Client",
|
|
36
|
+
"PaymentCreateBody",
|
|
37
|
+
"PaymentRequestSettleBody",
|
|
38
|
+
"WalletAssignment",
|
|
39
|
+
"WebhookSignatureError",
|
|
40
|
+
"__version__",
|
|
41
|
+
"webhooks",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def __getattr__(name: str):
|
|
46
|
+
"""Lazy-load the HTTP client.
|
|
47
|
+
|
|
48
|
+
`Client` depends on httpx; consumers who only use `webhooks.verify`
|
|
49
|
+
do not pay the import cost. PEP 562 module-level __getattr__ runs
|
|
50
|
+
on first attribute access, so `from agentcredia import Client`
|
|
51
|
+
still works exactly like a top-level import would.
|
|
52
|
+
"""
|
|
53
|
+
if name == "Client":
|
|
54
|
+
from ._client import Client as _Client # noqa: WPS433 (lazy import)
|
|
55
|
+
|
|
56
|
+
return _Client
|
|
57
|
+
raise AttributeError(f"module 'agentcredia' has no attribute {name!r}")
|
agentcredia/_client.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core HTTP client.
|
|
3
|
+
|
|
4
|
+
Sub-plan 21.3 row C-2. Thin wrapper over httpx that:
|
|
5
|
+
|
|
6
|
+
- injects the Bearer + X-Network headers on every request,
|
|
7
|
+
- mints an Idempotency-Key on POST / PATCH / DELETE unless caller
|
|
8
|
+
supplies one (matches the @agentcredia/node behaviour),
|
|
9
|
+
- retries 5xx + 429 with exponential backoff (Retry-After honoured),
|
|
10
|
+
- converts the canonical error envelope into AgentCrediaError /
|
|
11
|
+
ApiKeyError instances.
|
|
12
|
+
|
|
13
|
+
Network selection:
|
|
14
|
+
- `sk_test_*` keys force testnet,
|
|
15
|
+
- `sk_live_*` keys force mainnet,
|
|
16
|
+
- explicit `network=` kwarg overrides the key prefix when the SDK
|
|
17
|
+
is used in mixed-mode tests.
|
|
18
|
+
|
|
19
|
+
Idempotency:
|
|
20
|
+
- The body of POST / PATCH / DELETE is deduped server-side by
|
|
21
|
+
Idempotency-Key. The SDK mints a uuid4 if the caller did not
|
|
22
|
+
supply one. Pass `idempotency_key=...` to thread a stable key
|
|
23
|
+
across retries.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import time
|
|
29
|
+
import uuid
|
|
30
|
+
from typing import Any, Mapping, Optional
|
|
31
|
+
|
|
32
|
+
import httpx
|
|
33
|
+
|
|
34
|
+
from ._errors import ApiKeyError, AgentCrediaError
|
|
35
|
+
from ._version import __version__
|
|
36
|
+
|
|
37
|
+
DEFAULT_BASE_URL = "https://api.agentcredia.com"
|
|
38
|
+
DEFAULT_TIMEOUT = 30.0
|
|
39
|
+
DEFAULT_MAX_RETRIES = 3
|
|
40
|
+
USER_AGENT = f"agentcredia-python/{__version__}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _network_from_key(api_key: str) -> str:
|
|
44
|
+
if api_key.startswith("sk_live_"):
|
|
45
|
+
return "mainnet"
|
|
46
|
+
return "testnet"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_apikey_code(code: str) -> bool:
|
|
50
|
+
return isinstance(code, str) and code.startswith("apikey.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Client:
|
|
54
|
+
"""Synchronous AgentCredia HTTP client.
|
|
55
|
+
|
|
56
|
+
Example:
|
|
57
|
+
from agentcredia import Client
|
|
58
|
+
client = Client(api_key="sk_test_...")
|
|
59
|
+
keys = client.api_keys.list()
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
api_key: str,
|
|
66
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
67
|
+
network: Optional[str] = None,
|
|
68
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
69
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
70
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
71
|
+
) -> None:
|
|
72
|
+
if not api_key:
|
|
73
|
+
raise ValueError("api_key is required")
|
|
74
|
+
self._api_key = api_key
|
|
75
|
+
self._network = network or _network_from_key(api_key)
|
|
76
|
+
self._max_retries = max_retries
|
|
77
|
+
self._httpx = httpx.Client(
|
|
78
|
+
base_url=base_url,
|
|
79
|
+
timeout=timeout,
|
|
80
|
+
transport=transport,
|
|
81
|
+
headers={
|
|
82
|
+
"Authorization": f"Bearer {api_key}",
|
|
83
|
+
"X-Network": self._network,
|
|
84
|
+
"User-Agent": USER_AGENT,
|
|
85
|
+
"Accept": "application/json",
|
|
86
|
+
},
|
|
87
|
+
)
|
|
88
|
+
# Lazy-imported to avoid an import cycle at module load.
|
|
89
|
+
from .resources.agents import AgentsResource
|
|
90
|
+
from .resources.api_keys import ApiKeysResource
|
|
91
|
+
from .resources.payment_requests import PaymentRequestsResource
|
|
92
|
+
from .resources.payments import PaymentsResource
|
|
93
|
+
from .resources.transactions import TransactionsResource
|
|
94
|
+
|
|
95
|
+
self.agents = AgentsResource(self)
|
|
96
|
+
self.api_keys = ApiKeysResource(self)
|
|
97
|
+
self.payment_requests = PaymentRequestsResource(self)
|
|
98
|
+
self.payments = PaymentsResource(self)
|
|
99
|
+
self.transactions = TransactionsResource(self)
|
|
100
|
+
|
|
101
|
+
# -------------------- low-level request helpers --------------------
|
|
102
|
+
def _request(
|
|
103
|
+
self,
|
|
104
|
+
method: str,
|
|
105
|
+
path: str,
|
|
106
|
+
*,
|
|
107
|
+
json: Optional[Mapping[str, Any]] = None,
|
|
108
|
+
params: Optional[Mapping[str, Any]] = None,
|
|
109
|
+
idempotency_key: Optional[str] = None,
|
|
110
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
111
|
+
) -> Any:
|
|
112
|
+
request_headers: dict[str, str] = dict(headers or {})
|
|
113
|
+
upper = method.upper()
|
|
114
|
+
if upper in ("POST", "PATCH", "DELETE") and "Idempotency-Key" not in request_headers:
|
|
115
|
+
request_headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
|
|
116
|
+
|
|
117
|
+
attempt = 0
|
|
118
|
+
last_err: Optional[Exception] = None
|
|
119
|
+
while attempt <= self._max_retries:
|
|
120
|
+
attempt += 1
|
|
121
|
+
try:
|
|
122
|
+
resp = self._httpx.request(
|
|
123
|
+
method=upper,
|
|
124
|
+
url=path,
|
|
125
|
+
json=json,
|
|
126
|
+
params=params,
|
|
127
|
+
headers=request_headers,
|
|
128
|
+
)
|
|
129
|
+
except (httpx.TimeoutException, httpx.NetworkError) as e:
|
|
130
|
+
last_err = e
|
|
131
|
+
if attempt > self._max_retries:
|
|
132
|
+
raise AgentCrediaError(
|
|
133
|
+
code="network.unavailable",
|
|
134
|
+
message=f"transport error: {e}",
|
|
135
|
+
) from e
|
|
136
|
+
time.sleep(_backoff_seconds(attempt))
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
if resp.status_code < 400:
|
|
140
|
+
if resp.status_code == 204 or not resp.content:
|
|
141
|
+
return None
|
|
142
|
+
return resp.json()
|
|
143
|
+
|
|
144
|
+
# Retryable: 429 + 5xx
|
|
145
|
+
if resp.status_code == 429 or resp.status_code >= 500:
|
|
146
|
+
if attempt > self._max_retries:
|
|
147
|
+
self._raise_for_envelope(resp)
|
|
148
|
+
retry_after = resp.headers.get("Retry-After")
|
|
149
|
+
wait = float(retry_after) if retry_after else _backoff_seconds(attempt)
|
|
150
|
+
time.sleep(wait)
|
|
151
|
+
continue
|
|
152
|
+
|
|
153
|
+
# Non-retryable error.
|
|
154
|
+
self._raise_for_envelope(resp)
|
|
155
|
+
|
|
156
|
+
# Unreachable in practice; keep the type checker happy.
|
|
157
|
+
if last_err:
|
|
158
|
+
raise AgentCrediaError(code="network.unavailable", message=str(last_err))
|
|
159
|
+
raise AgentCrediaError(code="network.unavailable", message="retry budget exhausted")
|
|
160
|
+
|
|
161
|
+
def _raise_for_envelope(self, resp: httpx.Response) -> None:
|
|
162
|
+
"""Convert the canonical error envelope into the right exception."""
|
|
163
|
+
request_id = resp.headers.get("x-request-id")
|
|
164
|
+
try:
|
|
165
|
+
payload = resp.json()
|
|
166
|
+
except Exception:
|
|
167
|
+
raise AgentCrediaError(
|
|
168
|
+
code="response.invalid_envelope",
|
|
169
|
+
message=f"non-JSON error body (status={resp.status_code})",
|
|
170
|
+
http_status=resp.status_code,
|
|
171
|
+
request_id=request_id,
|
|
172
|
+
)
|
|
173
|
+
err = payload.get("error") if isinstance(payload, dict) else None
|
|
174
|
+
if not isinstance(err, dict):
|
|
175
|
+
raise AgentCrediaError(
|
|
176
|
+
code="response.invalid_envelope",
|
|
177
|
+
message=f"error envelope missing `error` (status={resp.status_code})",
|
|
178
|
+
http_status=resp.status_code,
|
|
179
|
+
request_id=request_id,
|
|
180
|
+
)
|
|
181
|
+
code = str(err.get("code", "error.unknown"))
|
|
182
|
+
message = str(err.get("message", "(no message)"))
|
|
183
|
+
cls = ApiKeyError if _is_apikey_code(code) else AgentCrediaError
|
|
184
|
+
raise cls(
|
|
185
|
+
code=code,
|
|
186
|
+
message=message,
|
|
187
|
+
http_status=resp.status_code,
|
|
188
|
+
request_id=request_id,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# -------------------- public verb shortcuts --------------------
|
|
192
|
+
def get(self, path: str, **kwargs: Any) -> Any:
|
|
193
|
+
return self._request("GET", path, **kwargs)
|
|
194
|
+
|
|
195
|
+
def post(self, path: str, **kwargs: Any) -> Any:
|
|
196
|
+
return self._request("POST", path, **kwargs)
|
|
197
|
+
|
|
198
|
+
def patch(self, path: str, **kwargs: Any) -> Any:
|
|
199
|
+
return self._request("PATCH", path, **kwargs)
|
|
200
|
+
|
|
201
|
+
def delete(self, path: str, **kwargs: Any) -> Any:
|
|
202
|
+
return self._request("DELETE", path, **kwargs)
|
|
203
|
+
|
|
204
|
+
def close(self) -> None:
|
|
205
|
+
self._httpx.close()
|
|
206
|
+
|
|
207
|
+
def __enter__(self) -> "Client":
|
|
208
|
+
return self
|
|
209
|
+
|
|
210
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
211
|
+
self.close()
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _backoff_seconds(attempt: int) -> float:
|
|
215
|
+
"""Exponential backoff with a 30s cap. attempt is 1-indexed."""
|
|
216
|
+
return min(30.0, 0.5 * (2 ** (attempt - 1)))
|
agentcredia/_errors.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Error classes for the AgentCredia Python SDK.
|
|
3
|
+
|
|
4
|
+
Sub-plan 21.3 row C-2 + C-6. Mirrors the @agentcredia/node error
|
|
5
|
+
hierarchy (packages/sdk-node/src/errors.ts) so a Python consumer can
|
|
6
|
+
branch on `code` strings exactly like a Node consumer would.
|
|
7
|
+
|
|
8
|
+
Hierarchy:
|
|
9
|
+
|
|
10
|
+
AgentCrediaError (every SDK error)
|
|
11
|
+
ApiKeyError (HTTP 401/403 with apikey.*)
|
|
12
|
+
WebhookSignatureError (raised only by webhooks.verify
|
|
13
|
+
when called via the `raise_on_fail`
|
|
14
|
+
flag - the default is a
|
|
15
|
+
discriminated-union return).
|
|
16
|
+
|
|
17
|
+
Every error carries:
|
|
18
|
+
code stable wire-level code from the openapi catalog
|
|
19
|
+
message human-readable description
|
|
20
|
+
http_status the HTTP status that produced this error (None for
|
|
21
|
+
client-side raises like WebhookSignatureError)
|
|
22
|
+
request_id server-issued request id (None on local-only errors)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from typing import Optional
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AgentCrediaError(Exception):
|
|
31
|
+
"""Base class for every SDK-raised error.
|
|
32
|
+
|
|
33
|
+
Catch this to handle any failure from the SDK. Branch on `code`
|
|
34
|
+
(a string from the wire-level catalog) for fine-grained handling -
|
|
35
|
+
NEVER regex-match `message`, which is marketing copy.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
code: str,
|
|
41
|
+
message: str,
|
|
42
|
+
*,
|
|
43
|
+
http_status: Optional[int] = None,
|
|
44
|
+
request_id: Optional[str] = None,
|
|
45
|
+
):
|
|
46
|
+
super().__init__(f"{code}: {message}")
|
|
47
|
+
self.code = code
|
|
48
|
+
self.message = message
|
|
49
|
+
self.http_status = http_status
|
|
50
|
+
self.request_id = request_id
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ApiKeyError(AgentCrediaError):
|
|
54
|
+
"""Subclass for HTTP 401 / 403 with an `apikey.*` code.
|
|
55
|
+
|
|
56
|
+
Lets call sites do:
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
client.payments.create(...)
|
|
60
|
+
except ApiKeyError as e:
|
|
61
|
+
if e.code == ApiKeyCodes.SCOPE_INSUFFICIENT:
|
|
62
|
+
...
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# Stable apikey.* failure-mode catalog (sub-plan 21.3 row C-8). The
|
|
67
|
+
# backend emits these codes verbatim in the wire envelope; SDK
|
|
68
|
+
# consumers branch on them via ApiKeyError.code. The 13 codes split
|
|
69
|
+
# into four groups: identity-bound, agent-flavor binding, surface-
|
|
70
|
+
# restriction, and the four 21.3-introduced workspace-flavor codes.
|
|
71
|
+
class ApiKeyCodes:
|
|
72
|
+
# Identity-bound (the key itself is invalid).
|
|
73
|
+
INVALID = "apikey.invalid"
|
|
74
|
+
REVOKED = "apikey.revoked"
|
|
75
|
+
EXPIRED = "apikey.expired"
|
|
76
|
+
# Agent-flavor binding errors (sub-plan 21.1).
|
|
77
|
+
AGENT_REVOKED = "apikey.agent_revoked"
|
|
78
|
+
AGENT_MISMATCH = "apikey.agent_mismatch"
|
|
79
|
+
# Surface-restriction errors.
|
|
80
|
+
WORKSPACE_ENDPOINT_BLOCKED = "apikey.workspace_endpoint_blocked"
|
|
81
|
+
UNSUPPORTED_ENDPOINT = "apikey.unsupported_endpoint"
|
|
82
|
+
# Network + scope.
|
|
83
|
+
NETWORK_MISMATCH = "apikey.network_mismatch"
|
|
84
|
+
SCOPE_INSUFFICIENT = "apikey.scope_insufficient"
|
|
85
|
+
# Workspace-flavor errors (sub-plan 21.3).
|
|
86
|
+
WALLET_NOT_ASSIGNED = "apikey.wallet_not_assigned"
|
|
87
|
+
WORKSPACE_SCOPE_INSUFFICIENT = "apikey.workspace_scope_insufficient"
|
|
88
|
+
ROLE_INSUFFICIENT_FOR_GRANTS = "apikey.role_insufficient_for_grants"
|
|
89
|
+
NO_GRANTS_REMAINING = "apikey.no_grants_remaining"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class WebhookSignatureError(AgentCrediaError):
|
|
93
|
+
"""Raised by webhooks.verify(..., raise_on_fail=True).
|
|
94
|
+
|
|
95
|
+
The default verify() returns a discriminated-union result; raise
|
|
96
|
+
this when the integration prefers exceptions over branching.
|
|
97
|
+
"""
|
agentcredia/_version.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""The published distribution version, sent in the User-Agent header.
|
|
2
|
+
|
|
3
|
+
Kept as a literal so it works from a source checkout (no installed
|
|
4
|
+
metadata). Bump it together with `[project].version` in pyproject.toml;
|
|
5
|
+
`tests/test_version.py` fails if the two drift.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.0.1a1"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Resource namespace package for the AgentCredia Python SDK."""
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""
|
|
2
|
+
agents resource (sub-plan 21.1 row B-2 - Python port).
|
|
3
|
+
|
|
4
|
+
The §4.5 matrix says an agent-scoped key can only GET its own
|
|
5
|
+
agent (`apikey.agent_mismatch` on any other id). The SDK does NOT
|
|
6
|
+
enforce that client-side - the server does, and the SDK surfaces
|
|
7
|
+
the resulting `ApiKeyError` so the caller can branch on `code`.
|
|
8
|
+
Workspace-flavor keys may also call `create` once they exist; the
|
|
9
|
+
SDK forwards the body verbatim so a server-side schema bump does
|
|
10
|
+
not force an SDK release.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any, Mapping, Optional, TYPE_CHECKING
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .._client import Client
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AgentsResource:
|
|
22
|
+
"""`client.agents.*` resource."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, client: "Client") -> None:
|
|
25
|
+
self._client = client
|
|
26
|
+
|
|
27
|
+
def get(self, agent_id: str) -> Any:
|
|
28
|
+
"""Fetch one agent by id.
|
|
29
|
+
|
|
30
|
+
:raises ValueError: when agent_id is empty.
|
|
31
|
+
:raises AgentCrediaError / ApiKeyError: on a non-2xx envelope.
|
|
32
|
+
"""
|
|
33
|
+
if not agent_id:
|
|
34
|
+
raise ValueError("agent_id is required")
|
|
35
|
+
return self._client.get(f"/v1/agents/{agent_id}")
|
|
36
|
+
|
|
37
|
+
def list(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
cursor: Optional[str] = None,
|
|
41
|
+
limit: Optional[int] = None,
|
|
42
|
+
) -> Any:
|
|
43
|
+
"""List agents the bearer has access to.
|
|
44
|
+
|
|
45
|
+
Returns the cursor-paginated envelope `{ data: [...],
|
|
46
|
+
page: { next, prev } }`. Workspace-flavor keys see every
|
|
47
|
+
agent in the workspace; agent-scoped keys see only the
|
|
48
|
+
single bound agent (the server filter).
|
|
49
|
+
"""
|
|
50
|
+
params: dict[str, Any] = {}
|
|
51
|
+
if cursor is not None:
|
|
52
|
+
params["cursor"] = cursor
|
|
53
|
+
if limit is not None:
|
|
54
|
+
params["limit"] = limit
|
|
55
|
+
return self._client.get("/v1/agents", params=params if params else None)
|
|
56
|
+
|
|
57
|
+
def create(self, body: Mapping[str, Any]) -> Any:
|
|
58
|
+
"""Create an agent. Workspace-flavor keys + dashboard
|
|
59
|
+
bearers only; agent-scoped keys reject with
|
|
60
|
+
`apikey.unsupported_endpoint`.
|
|
61
|
+
|
|
62
|
+
Body is forwarded verbatim - a server-side schema bump
|
|
63
|
+
does not require an SDK release.
|
|
64
|
+
"""
|
|
65
|
+
return self._client.post("/v1/agents", json=dict(body))
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""
|
|
2
|
+
api_keys resource (sub-plan 21.3 row C-2).
|
|
3
|
+
|
|
4
|
+
Initial resource scaffold + follow-up tightening that adds a typed
|
|
5
|
+
workspace-flavor `create()` (closes the matrix doc's "Workspace-
|
|
6
|
+
flavor `create` body" 🟡 (raw call) drift).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Iterable, Literal, Optional, Sequence, TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from .._client import Client
|
|
16
|
+
|
|
17
|
+
WorkspaceApiKeyScope = Literal["read_workspace", "manage_workspace_metadata"]
|
|
18
|
+
ApiKeyScope = Literal[
|
|
19
|
+
"read_wallet_metadata",
|
|
20
|
+
"manage_wallet_metadata",
|
|
21
|
+
"pay_bills",
|
|
22
|
+
"receive_money",
|
|
23
|
+
]
|
|
24
|
+
ExpiresInDays = Literal[7, 30, 60, 90]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class WalletAssignment:
|
|
29
|
+
"""One entry in `walletAssignments[]` on a workspace-flavor create."""
|
|
30
|
+
|
|
31
|
+
agent_id: str
|
|
32
|
+
scopes: Sequence[ApiKeyScope]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ApiKeysResource:
|
|
36
|
+
"""`client.api_keys.*`"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, client: "Client") -> None:
|
|
39
|
+
self._client = client
|
|
40
|
+
|
|
41
|
+
def list(self) -> Any:
|
|
42
|
+
"""List active API keys in the workspace.
|
|
43
|
+
|
|
44
|
+
Returns the raw page envelope `{ data: [...], page: {...} }`
|
|
45
|
+
until the typed model layer lands in C-1's codegen pass.
|
|
46
|
+
"""
|
|
47
|
+
return self._client.get("/v1/api-keys")
|
|
48
|
+
|
|
49
|
+
def get(self, api_key_id: str) -> Any:
|
|
50
|
+
"""Fetch one API key by id."""
|
|
51
|
+
return self._client.get(f"/v1/api-keys/{api_key_id}")
|
|
52
|
+
|
|
53
|
+
def revoke(self, api_key_id: str) -> None:
|
|
54
|
+
"""Revoke an API key. Returns None (204)."""
|
|
55
|
+
self._client.delete(f"/v1/api-keys/{api_key_id}")
|
|
56
|
+
|
|
57
|
+
def create_workspace_key(
|
|
58
|
+
self,
|
|
59
|
+
*,
|
|
60
|
+
label: str,
|
|
61
|
+
workspace_scopes: Optional[Iterable[WorkspaceApiKeyScope]] = None,
|
|
62
|
+
wallet_assignments: Optional[Iterable[WalletAssignment]] = None,
|
|
63
|
+
expires_in_days: Optional[ExpiresInDays] = None,
|
|
64
|
+
idempotency_key: Optional[str] = None,
|
|
65
|
+
) -> Any:
|
|
66
|
+
"""Mint a workspace-flavor API key.
|
|
67
|
+
|
|
68
|
+
Sub-plan 21.3 §3.1: a workspace-flavor key carries
|
|
69
|
+
`workspaceScopes` (cross-workspace permissions) and / or
|
|
70
|
+
`walletAssignments` (per-wallet scope grants). At least one
|
|
71
|
+
of the two MUST be non-empty - the server rejects with
|
|
72
|
+
`apikey.role_insufficient_for_grants` / `request.invalid`
|
|
73
|
+
otherwise.
|
|
74
|
+
|
|
75
|
+
:param label: human-readable label shown in the dashboard.
|
|
76
|
+
:param workspace_scopes: zero or more workspace-level scopes.
|
|
77
|
+
:param wallet_assignments: zero or more per-wallet grants.
|
|
78
|
+
:param expires_in_days: optional rotation hint (7/30/60/90).
|
|
79
|
+
:param idempotency_key: explicit idempotency key; otherwise
|
|
80
|
+
the client mints a fresh uuid4.
|
|
81
|
+
:return: the raw envelope `{ id, secret, prefix, ... }` -
|
|
82
|
+
the `secret` field is shown ONCE; persist it now.
|
|
83
|
+
|
|
84
|
+
:raises ApiKeyError: if the RBAC ceiling rejects the grant.
|
|
85
|
+
"""
|
|
86
|
+
body: dict[str, Any] = {"label": label}
|
|
87
|
+
ws_list = list(workspace_scopes or [])
|
|
88
|
+
if ws_list:
|
|
89
|
+
body["workspaceScopes"] = ws_list
|
|
90
|
+
wa_list = list(wallet_assignments or [])
|
|
91
|
+
if wa_list:
|
|
92
|
+
body["walletAssignments"] = [
|
|
93
|
+
{"agentId": a.agent_id, "scopes": list(a.scopes)} for a in wa_list
|
|
94
|
+
]
|
|
95
|
+
if expires_in_days is not None:
|
|
96
|
+
body["expiresInDays"] = expires_in_days
|
|
97
|
+
return self._client.post(
|
|
98
|
+
"/v1/api-keys",
|
|
99
|
+
json=body,
|
|
100
|
+
idempotency_key=idempotency_key,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def create_agent_key(
|
|
104
|
+
self,
|
|
105
|
+
*,
|
|
106
|
+
agent_id: str,
|
|
107
|
+
label: str,
|
|
108
|
+
scopes: Iterable[ApiKeyScope],
|
|
109
|
+
expires_in_days: Optional[ExpiresInDays] = None,
|
|
110
|
+
idempotency_key: Optional[str] = None,
|
|
111
|
+
) -> Any:
|
|
112
|
+
"""Mint an agent-bound (legacy 21.1) API key.
|
|
113
|
+
|
|
114
|
+
:param agent_id: the agent the key is bound to (returned as
|
|
115
|
+
`wallet.id` from `/v1/agents`).
|
|
116
|
+
:param label: human-readable label shown in the dashboard.
|
|
117
|
+
:param scopes: one or more wallet-scoped permissions.
|
|
118
|
+
:param expires_in_days: optional rotation hint (7/30/60/90).
|
|
119
|
+
"""
|
|
120
|
+
body: dict[str, Any] = {
|
|
121
|
+
"agentId": agent_id,
|
|
122
|
+
"label": label,
|
|
123
|
+
"scopes": list(scopes),
|
|
124
|
+
}
|
|
125
|
+
if expires_in_days is not None:
|
|
126
|
+
body["expiresInDays"] = expires_in_days
|
|
127
|
+
return self._client.post(
|
|
128
|
+
"/v1/api-keys",
|
|
129
|
+
json=body,
|
|
130
|
+
idempotency_key=idempotency_key,
|
|
131
|
+
)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
payment_requests resource (sub-plan 21.2 row A-3 / B-3 - Python port).
|
|
3
|
+
|
|
4
|
+
Exposes the settle path the x402 server adapter calls after verifying
|
|
5
|
+
an `X-Payment` header. The request body carries the on-chain proof
|
|
6
|
+
tuple (txHash + payerAddress + amountUsdcVerified); the backend
|
|
7
|
+
re-verifies it against the canonical `transactions` table before
|
|
8
|
+
flipping the invoice to `settled`. Trust model: the SDK is a thin
|
|
9
|
+
wrapper, the server is the trust anchor.
|
|
10
|
+
|
|
11
|
+
No idempotency-key mint here - settle is naturally idempotent
|
|
12
|
+
server-side (an invoice already in `settled` state returns 409
|
|
13
|
+
`payment_request.not_settleable`, never a duplicate event).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any, TYPE_CHECKING
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from .._client import Client
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class PaymentRequestSettleBody:
|
|
27
|
+
"""Body for POST /v1/payment-requests/{id}/settle."""
|
|
28
|
+
|
|
29
|
+
# Hash of the on-chain transfer that paid the invoice (0x + 64 hex).
|
|
30
|
+
tx_hash: str
|
|
31
|
+
# Address that sent the funds (0x + 40 hex).
|
|
32
|
+
payer_address: str
|
|
33
|
+
# Human USDC decimal the payer claims they sent (e.g. "0.10").
|
|
34
|
+
amount_usdc_verified: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class PaymentRequestsResource:
|
|
38
|
+
"""`client.payment_requests.*`
|
|
39
|
+
|
|
40
|
+
Compatible with the x402 server adapter's `ServerSdkLike` duck
|
|
41
|
+
interface (see `agentcredia_x402.server.shared`): this resource
|
|
42
|
+
exposes `settle(payment_request_id=..., body=...)` with the
|
|
43
|
+
canonical wire body shape.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, client: "Client") -> None:
|
|
47
|
+
self._client = client
|
|
48
|
+
|
|
49
|
+
def settle(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
payment_request_id: str,
|
|
53
|
+
body: "PaymentRequestSettleBody | dict[str, Any]",
|
|
54
|
+
) -> Any:
|
|
55
|
+
"""Settle a payment request with the on-chain proof tuple.
|
|
56
|
+
|
|
57
|
+
Returns the raw JSON envelope `{ id, status='settled',
|
|
58
|
+
settledTxHash, settledAt }`. Server validates the proof against
|
|
59
|
+
the canonical `transactions` table; a tampered tuple rejects
|
|
60
|
+
with `payment_request.settle_proof_invalid`.
|
|
61
|
+
|
|
62
|
+
:param payment_request_id: the `pr_*` id from the 402
|
|
63
|
+
`accepts[].paymentRequestId` field.
|
|
64
|
+
:param body: a `PaymentRequestSettleBody` instance OR a plain
|
|
65
|
+
dict with the same shape (the adapter accepts both because
|
|
66
|
+
the x402 server adapter passes a dict directly).
|
|
67
|
+
:raises AgentCrediaError: on any non-2xx envelope.
|
|
68
|
+
"""
|
|
69
|
+
if not payment_request_id:
|
|
70
|
+
raise ValueError("payment_request_id is required")
|
|
71
|
+
|
|
72
|
+
if isinstance(body, PaymentRequestSettleBody):
|
|
73
|
+
wire_body = {
|
|
74
|
+
"txHash": body.tx_hash,
|
|
75
|
+
"payerAddress": body.payer_address,
|
|
76
|
+
"amountUsdcVerified": body.amount_usdc_verified,
|
|
77
|
+
}
|
|
78
|
+
else:
|
|
79
|
+
# Accept the canonical camelCase shape verbatim - the x402
|
|
80
|
+
# server adapter already passes this exact shape.
|
|
81
|
+
wire_body = dict(body)
|
|
82
|
+
|
|
83
|
+
return self._client.post(
|
|
84
|
+
f"/v1/payment-requests/{payment_request_id}/settle",
|
|
85
|
+
json=wire_body,
|
|
86
|
+
)
|