tinyfish 0.5.0__tar.gz → 0.6.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 (54) hide show
  1. {tinyfish-0.5.0 → tinyfish-0.6.1}/CHANGELOG.md +15 -0
  2. {tinyfish-0.5.0 → tinyfish-0.6.1}/PKG-INFO +2 -1
  3. {tinyfish-0.5.0 → tinyfish-0.6.1}/README.md +1 -0
  4. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/exceptions-and-errors-guide.md +1 -1
  5. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/internal/exceptions-and-errors-guide.md +1 -1
  6. {tinyfish-0.5.0 → tinyfish-0.6.1}/pyproject.toml +1 -1
  7. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/__init__.py +17 -0
  8. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/client/_base.py +8 -5
  9. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/exceptions.py +49 -18
  10. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/client.py +5 -0
  11. tinyfish-0.6.1/src/tinyfish/wallet/__init__.py +41 -0
  12. tinyfish-0.6.1/src/tinyfish/wallet/types.py +85 -0
  13. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_errors.py +20 -0
  14. tinyfish-0.6.1/tests/test_wallet.py +255 -0
  15. {tinyfish-0.5.0 → tinyfish-0.6.1}/.gitignore +0 -0
  16. {tinyfish-0.5.0 → tinyfish-0.6.1}/.pre-commit-config.yaml +0 -0
  17. {tinyfish-0.5.0 → tinyfish-0.6.1}/AGENTS.md +0 -0
  18. {tinyfish-0.5.0 → tinyfish-0.6.1}/CLAUDE.md +0 -0
  19. {tinyfish-0.5.0 → tinyfish-0.6.1}/RELEASE.md +0 -0
  20. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/internal/api-integration-header.md +0 -0
  21. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/internal/publishing-private-guide.md +0 -0
  22. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/pagination-guide.md +0 -0
  23. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/proxy-and-browser-profiles.md +0 -0
  24. {tinyfish-0.5.0 → tinyfish-0.6.1}/docs/streaming-guide.md +0 -0
  25. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/__init__.py +0 -0
  26. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/client/__init__.py +0 -0
  27. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/client/async_.py +0 -0
  28. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/client/sync.py +0 -0
  29. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/resource.py +0 -0
  30. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/_utils/sse_parser.py +0 -0
  31. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/agent/__init__.py +0 -0
  32. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/agent/types.py +0 -0
  33. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/browser/__init__.py +0 -0
  34. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/browser/types.py +0 -0
  35. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/fetch/__init__.py +0 -0
  36. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/fetch/types.py +0 -0
  37. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/py.typed +0 -0
  38. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/runs/__init__.py +0 -0
  39. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/runs/types.py +0 -0
  40. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/search/__init__.py +0 -0
  41. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/search/types.py +0 -0
  42. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/vault/__init__.py +0 -0
  43. {tinyfish-0.5.0 → tinyfish-0.6.1}/src/tinyfish/vault/types.py +0 -0
  44. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/__init__.py +0 -0
  45. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/conftest.py +0 -0
  46. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_agent.py +0 -0
  47. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_browser.py +0 -0
  48. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_client.py +0 -0
  49. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_fetch.py +0 -0
  50. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_runs.py +0 -0
  51. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_search.py +0 -0
  52. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/test_vault.py +0 -0
  53. {tinyfish-0.5.0 → tinyfish-0.6.1}/tests/testing_guide.md +0 -0
  54. {tinyfish-0.5.0 → tinyfish-0.6.1}/uv.lock +0 -0
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.6.1](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.6.0...sdk-py/v0.6.1) (2026-08-12)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **sdk:** emit wallet types without vendor-internal fields ([#4257](https://github.com/tinyfish-io/ux-labs/issues/4257)) ([dfefbab](https://github.com/tinyfish-io/ux-labs/commit/dfefbab17420cf617cc1acd0184d580c7b597cdc))
9
+ * **wallet:** gate unreleased wallet reads behind wallet_enabled with typed 404 (PF-3513) ([#4245](https://github.com/tinyfish-io/ux-labs/issues/4245)) ([6d9dc56](https://github.com/tinyfish-io/ux-labs/commit/6d9dc5603996659c8eec8828308fb053d82ed8dc))
10
+
11
+ ## [0.6.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.5.0...sdk-py/v0.6.0) (2026-08-11)
12
+
13
+
14
+ ### Features
15
+
16
+ * **sdk:** wallet resource — client.wallet.get() in TypeScript and Python SDKs (PF-3454) ([#4213](https://github.com/tinyfish-io/ux-labs/issues/4213)) ([1127f1d](https://github.com/tinyfish-io/ux-labs/commit/1127f1de8acf2eef27c22eec5cd08b9cabdfaf86))
17
+
3
18
  ## [0.5.0](https://github.com/tinyfish-io/ux-labs/compare/sdk-py/v0.4.0...sdk-py/v0.5.0) (2026-08-04)
4
19
 
5
20
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tinyfish
3
- Version: 0.5.0
3
+ Version: 0.6.1
4
4
  Summary: Official Python SDK for the TinyFish API
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: httpx>=0.27.0
@@ -57,6 +57,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
57
57
  | [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
58
58
  | [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
59
59
  | [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
60
+ | `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
60
61
 
61
62
  ---
62
63
 
@@ -47,6 +47,7 @@ Every method below is available on both `TinyFish` (sync) and `AsyncTinyFish` (a
47
47
  | [`runs.get()`](#runsget--retrieve-a-single-run) | Retrieve a single run by ID | `Run` | — |
48
48
  | [`runs.list()`](#runslist--list-and-filter-runs) | List runs with filtering, sorting, pagination | `RunListResponse` | — |
49
49
  | [`search.query()`](#searchquery--search-the-web) | Search the web for ranked results | `SearchQueryResponse` | Yes |
50
+ | `wallet.get()` | Get the caller's wallet balance, auto-reload, and rates | `WalletResponse` | — |
50
51
 
51
52
  ---
52
53
 
@@ -74,7 +74,7 @@ SDKError
74
74
  └─ APIError ← carries .request and .response
75
75
  ├─ APIConnectionError ← network failed
76
76
  │ └─ APITimeoutError ← specifically a timeout
77
- └─ APIStatusError ← carries .status_code too
77
+ └─ APIStatusError ← carries .status_code and .code (machine-readable, from error.code) too
78
78
  ├─ BadRequestError (400)
79
79
  ├─ AuthenticationError (401)
80
80
  ├─ PermissionDeniedError (403)
@@ -74,7 +74,7 @@ SDKError
74
74
  └─ APIError ← carries .request and .response
75
75
  ├─ APIConnectionError ← network failed
76
76
  │ └─ APITimeoutError ← specifically a timeout
77
- └─ APIStatusError ← carries .status_code too
77
+ └─ APIStatusError ← carries .status_code and .code (machine-readable, from error.code) too
78
78
  ├─ BadRequestError (400)
79
79
  ├─ AuthenticationError (401)
80
80
  ├─ PermissionDeniedError (403)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "tinyfish"
3
- version = "0.5.0"
3
+ version = "0.6.1"
4
4
  description = "Official Python SDK for the TinyFish API"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -80,6 +80,16 @@ from .vault.types import (
80
80
  VaultSyncItemsResponse,
81
81
  )
82
82
 
83
+ # Wallet types
84
+ from .wallet.types import (
85
+ WalletAutoReload,
86
+ WalletAutoReloadState,
87
+ WalletMeter,
88
+ WalletPendingTopUp,
89
+ WalletRates,
90
+ WalletResponse,
91
+ )
92
+
83
93
  __version__ = version("tinyfish")
84
94
 
85
95
  __all__ = [
@@ -149,4 +159,11 @@ __all__ = [
149
159
  "VaultDisconnectResponse",
150
160
  "VaultListItemsResponse",
151
161
  "VaultSyncItemsResponse",
162
+ # Wallet types
163
+ "WalletAutoReloadState",
164
+ "WalletAutoReload",
165
+ "WalletMeter",
166
+ "WalletRates",
167
+ "WalletPendingTopUp",
168
+ "WalletResponse",
152
169
  ]
@@ -151,17 +151,20 @@ class _BaseClient:
151
151
  else:
152
152
  error_class = error_map.get(response.status_code, APIStatusError)
153
153
 
154
- # Try to parse error message from JSON response
154
+ # Try to parse the message and machine-readable code from the JSON error body.
155
+ code: str | None = None
155
156
  try:
156
- error_data = response.json()
157
- message = error_data.get("error", {}).get("message", response.text)
157
+ error_data = response.json().get("error", {})
158
+ message = error_data.get("message", response.text)
159
+ raw_code = error_data.get("code")
160
+ code = raw_code if isinstance(raw_code, str) else None
158
161
  except Exception:
159
162
  message = response.text or f"HTTP {response.status_code}"
160
163
 
161
164
  if error_class is APIStatusError:
162
165
  # Fallback: no concrete subclass matched, so pass the raw status code.
163
- return error_class(message=message, response=response, status_code=response.status_code)
164
- return error_class(message=message, response=response)
166
+ return error_class(message=message, response=response, status_code=response.status_code, code=code)
167
+ return error_class(message=message, response=response, code=code)
165
168
 
166
169
  def _parse_response(
167
170
  self,
@@ -83,10 +83,13 @@ class APIStatusError(APIError):
83
83
  *,
84
84
  response: httpx.Response,
85
85
  status_code: int,
86
+ code: str | None = None,
86
87
  request: httpx.Request | None = None,
87
88
  ) -> None:
88
89
  super().__init__(message, request=request, response=response)
89
90
  self.status_code = status_code
91
+ #: Machine-readable error code from the response body's `error.code`, when the server sent one.
92
+ self.code = code
90
93
 
91
94
  def __repr__(self) -> str:
92
95
  return f"{self.__class__.__name__}(status_code={self.status_code}, message={self.message!r})"
@@ -95,57 +98,83 @@ class APIStatusError(APIError):
95
98
  class BadRequestError(APIStatusError):
96
99
  """400 Bad Request."""
97
100
 
98
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
99
- super().__init__(message, response=response, status_code=int(httpx.codes.BAD_REQUEST), request=request)
101
+ def __init__(
102
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
103
+ ) -> None:
104
+ super().__init__(
105
+ message, response=response, status_code=int(httpx.codes.BAD_REQUEST), code=code, request=request
106
+ )
100
107
 
101
108
 
102
109
  class AuthenticationError(APIStatusError):
103
110
  """401 Unauthorized."""
104
111
 
105
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
106
- super().__init__(message, response=response, status_code=int(httpx.codes.UNAUTHORIZED), request=request)
112
+ def __init__(
113
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
114
+ ) -> None:
115
+ super().__init__(
116
+ message, response=response, status_code=int(httpx.codes.UNAUTHORIZED), code=code, request=request
117
+ )
107
118
 
108
119
 
109
120
  class PermissionDeniedError(APIStatusError):
110
121
  """403 Forbidden."""
111
122
 
112
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
113
- super().__init__(message, response=response, status_code=int(httpx.codes.FORBIDDEN), request=request)
123
+ def __init__(
124
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
125
+ ) -> None:
126
+ super().__init__(message, response=response, status_code=int(httpx.codes.FORBIDDEN), code=code, request=request)
114
127
 
115
128
 
116
129
  class NotFoundError(APIStatusError):
117
130
  """404 Not Found."""
118
131
 
119
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
120
- super().__init__(message, response=response, status_code=int(httpx.codes.NOT_FOUND), request=request)
132
+ def __init__(
133
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
134
+ ) -> None:
135
+ super().__init__(message, response=response, status_code=int(httpx.codes.NOT_FOUND), code=code, request=request)
121
136
 
122
137
 
123
138
  class RequestTimeoutError(APIStatusError):
124
139
  """408 Request Timeout."""
125
140
 
126
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
127
- super().__init__(message, response=response, status_code=int(httpx.codes.REQUEST_TIMEOUT), request=request)
141
+ def __init__(
142
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
143
+ ) -> None:
144
+ super().__init__(
145
+ message, response=response, status_code=int(httpx.codes.REQUEST_TIMEOUT), code=code, request=request
146
+ )
128
147
 
129
148
 
130
149
  class ConflictError(APIStatusError):
131
150
  """409 Conflict."""
132
151
 
133
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
134
- super().__init__(message, response=response, status_code=int(httpx.codes.CONFLICT), request=request)
152
+ def __init__(
153
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
154
+ ) -> None:
155
+ super().__init__(message, response=response, status_code=int(httpx.codes.CONFLICT), code=code, request=request)
135
156
 
136
157
 
137
158
  class UnprocessableEntityError(APIStatusError):
138
159
  """422 Unprocessable Entity."""
139
160
 
140
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
141
- super().__init__(message, response=response, status_code=int(httpx.codes.UNPROCESSABLE_ENTITY), request=request)
161
+ def __init__(
162
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
163
+ ) -> None:
164
+ super().__init__(
165
+ message, response=response, status_code=int(httpx.codes.UNPROCESSABLE_ENTITY), code=code, request=request
166
+ )
142
167
 
143
168
 
144
169
  class RateLimitError(APIStatusError):
145
170
  """429 Too Many Requests."""
146
171
 
147
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
148
- super().__init__(message, response=response, status_code=int(httpx.codes.TOO_MANY_REQUESTS), request=request)
172
+ def __init__(
173
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
174
+ ) -> None:
175
+ super().__init__(
176
+ message, response=response, status_code=int(httpx.codes.TOO_MANY_REQUESTS), code=code, request=request
177
+ )
149
178
 
150
179
 
151
180
  class InternalServerError(APIStatusError):
@@ -155,5 +184,7 @@ class InternalServerError(APIStatusError):
155
184
  is preserved in the status_code attribute for accurate monitoring/alerting.
156
185
  """
157
186
 
158
- def __init__(self, message: str, *, response: httpx.Response, request: httpx.Request | None = None) -> None:
159
- super().__init__(message, response=response, status_code=response.status_code, request=request)
187
+ def __init__(
188
+ self, message: str, *, response: httpx.Response, code: str | None = None, request: httpx.Request | None = None
189
+ ) -> None:
190
+ super().__init__(message, response=response, status_code=response.status_code, code=code, request=request)
@@ -9,6 +9,7 @@ from .fetch import AsyncFetchResource, FetchResource
9
9
  from .runs import AsyncRunsResource, RunsResource
10
10
  from .search import AsyncSearchResource, SearchResource
11
11
  from .vault import AsyncVaultResource, VaultResource
12
+ from .wallet import AsyncWalletResource, WalletResource
12
13
 
13
14
  __all__ = ["TinyFish", "AsyncTinyFish"]
14
15
 
@@ -30,6 +31,7 @@ class TinyFish(BaseSyncAPIClient):
30
31
  runs: RunsResource
31
32
  search: SearchResource
32
33
  vault: VaultResource
34
+ wallet: WalletResource
33
35
 
34
36
  def __init__(
35
37
  self,
@@ -55,6 +57,7 @@ class TinyFish(BaseSyncAPIClient):
55
57
  self.runs = RunsResource(self)
56
58
  self.search = SearchResource(self)
57
59
  self.vault = VaultResource(self)
60
+ self.wallet = WalletResource(self)
58
61
 
59
62
 
60
63
  class AsyncTinyFish(BaseAsyncAPIClient):
@@ -69,6 +72,7 @@ class AsyncTinyFish(BaseAsyncAPIClient):
69
72
  runs: AsyncRunsResource
70
73
  search: AsyncSearchResource
71
74
  vault: AsyncVaultResource
75
+ wallet: AsyncWalletResource
72
76
 
73
77
  def __init__(
74
78
  self,
@@ -94,3 +98,4 @@ class AsyncTinyFish(BaseAsyncAPIClient):
94
98
  self.runs = AsyncRunsResource(self)
95
99
  self.search = AsyncSearchResource(self)
96
100
  self.vault = AsyncVaultResource(self)
101
+ self.wallet = AsyncWalletResource(self)
@@ -0,0 +1,41 @@
1
+ """Wallet resource for retrieving wallet balance, auto-reload, and rates."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from tinyfish._utils.resource import BaseAsyncAPIResource, BaseSyncAPIResource
6
+
7
+ from .types import WalletResponse
8
+
9
+
10
+ class WalletResource(BaseSyncAPIResource):
11
+ """Retrieve the caller's wallet (sync)."""
12
+
13
+ def get(self) -> WalletResponse:
14
+ """Get the caller's wallet: balance, auto-reload state, per-contract rates,
15
+ and any in-flight top-up.
16
+
17
+ Returns:
18
+ WalletResponse with the full wallet shape.
19
+
20
+ Raises:
21
+ AuthenticationError: Invalid API key.
22
+ """
23
+ return self._get("/v1/wallet", cast_to=WalletResponse)
24
+
25
+
26
+ class AsyncWalletResource(BaseAsyncAPIResource):
27
+ """Retrieve the caller's wallet (async)."""
28
+
29
+ async def get(self) -> WalletResponse:
30
+ """Get the caller's wallet: balance, auto-reload state, per-contract rates,
31
+ and any in-flight top-up.
32
+
33
+ Async version of `WalletResource.get()`.
34
+
35
+ Returns:
36
+ WalletResponse with the full wallet shape.
37
+
38
+ Raises:
39
+ AuthenticationError: Invalid API key.
40
+ """
41
+ return await self._get("/v1/wallet", cast_to=WalletResponse)
@@ -0,0 +1,85 @@
1
+ """Wallet request/response types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import StrEnum
6
+ from typing import Annotated, Literal
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+
11
+ class WalletAutoReloadState(StrEnum):
12
+ """Auto-reload configuration state."""
13
+
14
+ UNCONFIGURED = "unconfigured"
15
+ ON = "on"
16
+ OFF = "off"
17
+ PAUSED_PAYMENT_FAILED = "paused_payment_failed"
18
+ NEEDS_PAYMENT_METHOD = "needs_payment_method"
19
+
20
+
21
+ class WalletAutoReloadUnconfigured(BaseModel):
22
+ """Auto-reload has never been configured for this wallet."""
23
+
24
+ state: Literal[WalletAutoReloadState.UNCONFIGURED] = Field(..., description="Current auto-reload state")
25
+
26
+
27
+ class WalletAutoReloadConfigured(BaseModel):
28
+ """Auto-reload is configured — threshold and recharge_to are always present."""
29
+
30
+ state: Literal[
31
+ WalletAutoReloadState.ON,
32
+ WalletAutoReloadState.OFF,
33
+ WalletAutoReloadState.PAUSED_PAYMENT_FAILED,
34
+ WalletAutoReloadState.NEEDS_PAYMENT_METHOD,
35
+ ] = Field(..., description="Current auto-reload state")
36
+ threshold: str = Field(..., description="Balance floor that triggers a reload.")
37
+ recharge_to: str = Field(..., description="Balance the wallet is topped up to when a reload triggers.")
38
+
39
+
40
+ WalletAutoReload = Annotated[
41
+ WalletAutoReloadUnconfigured | WalletAutoReloadConfigured,
42
+ Field(discriminator="state"),
43
+ ]
44
+
45
+
46
+ class WalletMeter(BaseModel):
47
+ """One priced product on the caller's rate contract."""
48
+
49
+ label: str = Field(..., description="Human-readable meter label")
50
+ unit_amount: str = Field(..., description="Per-unit rate, decimal string")
51
+ currency: str = Field(..., description="ISO 4217 currency code, e.g. USD")
52
+ per: str | None = Field(None, description="Billable unit this meter charges per. Absent when unlabeled.")
53
+
54
+
55
+ class WalletRates(BaseModel):
56
+ """Every priced product on the caller's rate contract, read live."""
57
+
58
+ meters: list[WalletMeter] = Field(..., description="Priced products on the contract")
59
+ as_of: str = Field(..., description="ISO timestamp the rates were read")
60
+
61
+
62
+ class WalletPendingTopUp(BaseModel):
63
+ """An in-flight top-up. Completed, failed, and no-attempt states read null."""
64
+
65
+ amount: str = Field(..., description="Top-up amount, decimal string")
66
+ started_at: str = Field(..., description="ISO timestamp the top-up started")
67
+
68
+
69
+ class WalletResponse(BaseModel):
70
+ """Wallet balance, auto-reload, per-product rates, and any in-flight top-up."""
71
+
72
+ available_balance: str = Field(
73
+ ..., description="Current spendable balance. A negative value means the wallet is overdrawn."
74
+ )
75
+ currency: str = Field(..., description="ISO 4217 currency code, e.g. USD")
76
+ as_of: str = Field(..., description="ISO timestamp when the wallet was read")
77
+ auto_reload: WalletAutoReload | None = Field(
78
+ None, description="None means the auto-reload read failed, not that it is unconfigured"
79
+ )
80
+ pending_top_up: WalletPendingTopUp | None = Field(
81
+ None, description="None means no in-flight top-up, or the ledger read failed"
82
+ )
83
+ rates: WalletRates | None = Field(
84
+ None, description="None means the rates read failed, or the wallet has no rate contract yet"
85
+ )
@@ -101,6 +101,26 @@ def test_exception_message_fallback_to_text(client: TinyFish, respx_mock: MockRo
101
101
  assert exc.value.message # non-empty
102
102
 
103
103
 
104
+ # The response body's error.code is captured on the exception, not silently dropped
105
+ @pytest.mark.respx(base_url=BASE_URL)
106
+ def test_exception_code_captured_from_json(client: TinyFish, respx_mock: MockRouter):
107
+ respx_mock.post(_PATH).mock(
108
+ return_value=httpx.Response(404, json={"error": {"code": "FEATURE_NOT_AVAILABLE", "message": "nope"}})
109
+ )
110
+ with pytest.raises(NotFoundError) as exc:
111
+ client.agent.run(**_BODY)
112
+ assert exc.value.code == "FEATURE_NOT_AVAILABLE"
113
+
114
+
115
+ # When the body carries no code, the attribute is None rather than a stale/wrong value
116
+ @pytest.mark.respx(base_url=BASE_URL)
117
+ def test_exception_code_none_when_absent(client: TinyFish, respx_mock: MockRouter):
118
+ respx_mock.post(_PATH).mock(return_value=httpx.Response(404, json=_err_json()))
119
+ with pytest.raises(NotFoundError) as exc:
120
+ client.agent.run(**_BODY)
121
+ assert exc.value.code is None
122
+
123
+
104
124
  # httpx timeout is wrapped as APITimeoutError
105
125
  @pytest.mark.respx(base_url=BASE_URL)
106
126
  def test_timeout_raises(client: TinyFish, respx_mock: MockRouter):
@@ -0,0 +1,255 @@
1
+ """Tests for wallet.get — sync and async."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+ import pytest
9
+ from pydantic import ValidationError
10
+ from respx import MockRouter
11
+
12
+ from tests.conftest import BASE_URL
13
+ from tinyfish import AsyncTinyFish, AuthenticationError, NotFoundError, TinyFish
14
+ from tinyfish.wallet.types import WalletAutoReloadState, WalletResponse
15
+
16
+ # ─── Constants ────────────────────────────────────────────────────────────────
17
+
18
+ _WALLET_PATH = "/v1/wallet"
19
+ _AS_OF = "2026-08-10T18:04:11.220Z"
20
+
21
+
22
+ def _meter(**overrides: Any) -> dict[str, Any]:
23
+ base: dict[str, Any] = {
24
+ "label": "Agent steps",
25
+ "unit_amount": "0.016000",
26
+ "currency": "USD",
27
+ "per": "step",
28
+ }
29
+ return {**base, **overrides}
30
+
31
+
32
+ def _rates(**overrides: Any) -> dict[str, Any]:
33
+ base: dict[str, Any] = {
34
+ "meters": [_meter()],
35
+ "as_of": _AS_OF,
36
+ }
37
+ return {**base, **overrides}
38
+
39
+
40
+ def _wallet_response(**overrides: Any) -> dict[str, Any]:
41
+ base: dict[str, Any] = {
42
+ "available_balance": "21.44",
43
+ "currency": "USD",
44
+ "as_of": _AS_OF,
45
+ "auto_reload": {"state": "unconfigured"},
46
+ "pending_top_up": None,
47
+ "rates": _rates(),
48
+ }
49
+ return {**base, **overrides}
50
+
51
+
52
+ # ═══════════════════════════════════════════════════════════════════════════════
53
+ # wallet.get — sync
54
+ # ═══════════════════════════════════════════════════════════════════════════════
55
+
56
+
57
+ @pytest.mark.respx(base_url=BASE_URL)
58
+ def test_get_returns_full_shape(client: TinyFish, respx_mock: MockRouter):
59
+ respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
60
+ result = client.wallet.get()
61
+ assert isinstance(result, WalletResponse)
62
+ assert result.available_balance == "21.44"
63
+ assert result.currency == "USD"
64
+ assert result.as_of == _AS_OF
65
+ assert result.auto_reload is not None
66
+ assert result.auto_reload.state == WalletAutoReloadState.UNCONFIGURED
67
+ assert result.pending_top_up is None
68
+ assert result.rates is not None
69
+ assert len(result.rates.meters) == 1
70
+
71
+
72
+ @pytest.mark.respx(base_url=BASE_URL)
73
+ def test_get_sends_get_method(client: TinyFish, respx_mock: MockRouter):
74
+ route = respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
75
+ client.wallet.get()
76
+ assert route.calls[0].request.method == "GET"
77
+
78
+
79
+ @pytest.mark.respx(base_url=BASE_URL)
80
+ def test_get_round_trips_negative_balance(client: TinyFish, respx_mock: MockRouter):
81
+ respx_mock.get(_WALLET_PATH).mock(
82
+ return_value=httpx.Response(200, json=_wallet_response(available_balance="-14.02"))
83
+ )
84
+ result = client.wallet.get()
85
+ assert result.available_balance == "-14.02"
86
+
87
+
88
+ @pytest.mark.respx(base_url=BASE_URL)
89
+ def test_get_fully_degraded_response(client: TinyFish, respx_mock: MockRouter):
90
+ respx_mock.get(_WALLET_PATH).mock(
91
+ return_value=httpx.Response(200, json=_wallet_response(auto_reload=None, pending_top_up=None, rates=None))
92
+ )
93
+ result = client.wallet.get()
94
+ assert result.auto_reload is None
95
+ assert result.pending_top_up is None
96
+ assert result.rates is None
97
+
98
+
99
+ @pytest.mark.respx(base_url=BASE_URL)
100
+ def test_get_auto_reload_unconfigured_has_no_threshold(client: TinyFish, respx_mock: MockRouter):
101
+ respx_mock.get(_WALLET_PATH).mock(
102
+ return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "unconfigured"}))
103
+ )
104
+ result = client.wallet.get()
105
+ assert result.auto_reload is not None
106
+ assert result.auto_reload.state == WalletAutoReloadState.UNCONFIGURED
107
+ assert not hasattr(result.auto_reload, "threshold")
108
+ assert not hasattr(result.auto_reload, "recharge_to")
109
+
110
+
111
+ @pytest.mark.parametrize(
112
+ "state",
113
+ ["on", "off", "paused_payment_failed", "needs_payment_method"],
114
+ )
115
+ @pytest.mark.respx(base_url=BASE_URL)
116
+ def test_get_auto_reload_configured_states(state: str, client: TinyFish, respx_mock: MockRouter):
117
+ respx_mock.get(_WALLET_PATH).mock(
118
+ return_value=httpx.Response(
119
+ 200,
120
+ json=_wallet_response(auto_reload={"state": state, "threshold": "10.00", "recharge_to": "50.00"}),
121
+ )
122
+ )
123
+ result = client.wallet.get()
124
+ assert result.auto_reload is not None
125
+ assert result.auto_reload.state == state
126
+ assert result.auto_reload.threshold == "10.00"
127
+ assert result.auto_reload.recharge_to == "50.00"
128
+
129
+
130
+ @pytest.mark.respx(base_url=BASE_URL)
131
+ def test_get_auto_reload_configured_missing_threshold_raises(client: TinyFish, respx_mock: MockRouter):
132
+ respx_mock.get(_WALLET_PATH).mock(
133
+ return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "on", "recharge_to": "50.00"}))
134
+ )
135
+ with pytest.raises(ValidationError):
136
+ client.wallet.get()
137
+
138
+
139
+ @pytest.mark.respx(base_url=BASE_URL)
140
+ def test_get_pending_top_up(client: TinyFish, respx_mock: MockRouter):
141
+ respx_mock.get(_WALLET_PATH).mock(
142
+ return_value=httpx.Response(
143
+ 200, json=_wallet_response(pending_top_up={"amount": "50.00", "started_at": _AS_OF})
144
+ )
145
+ )
146
+ result = client.wallet.get()
147
+ assert result.pending_top_up is not None
148
+ assert result.pending_top_up.amount == "50.00"
149
+ assert result.pending_top_up.started_at == _AS_OF
150
+
151
+
152
+ @pytest.mark.respx(base_url=BASE_URL)
153
+ def test_get_meter_without_per(client: TinyFish, respx_mock: MockRouter):
154
+ meter = _meter()
155
+ del meter["per"]
156
+ respx_mock.get(_WALLET_PATH).mock(
157
+ return_value=httpx.Response(200, json=_wallet_response(rates=_rates(meters=[meter])))
158
+ )
159
+ result = client.wallet.get()
160
+ assert result.rates is not None
161
+ assert result.rates.meters[0].per is None
162
+
163
+
164
+ @pytest.mark.respx(base_url=BASE_URL)
165
+ def test_get_strips_unknown_field(client: TinyFish, respx_mock: MockRouter):
166
+ respx_mock.get(_WALLET_PATH).mock(
167
+ return_value=httpx.Response(200, json=_wallet_response(unexpected_field="surprise"))
168
+ )
169
+ result = client.wallet.get()
170
+ assert result.available_balance == "21.44"
171
+ assert not hasattr(result, "unexpected_field")
172
+
173
+
174
+ @pytest.mark.respx(base_url=BASE_URL)
175
+ def test_get_401(client: TinyFish, respx_mock: MockRouter):
176
+ respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
177
+ with pytest.raises(AuthenticationError):
178
+ client.wallet.get()
179
+
180
+
181
+ @pytest.mark.respx(base_url=BASE_URL)
182
+ def test_get_feature_not_available(client: TinyFish, respx_mock: MockRouter):
183
+ respx_mock.get(_WALLET_PATH).mock(
184
+ return_value=httpx.Response(
185
+ 404,
186
+ json={
187
+ "error": {
188
+ "code": "FEATURE_NOT_AVAILABLE",
189
+ "message": "Wallet is not available for your account yet.",
190
+ }
191
+ },
192
+ )
193
+ )
194
+ with pytest.raises(NotFoundError) as exc:
195
+ client.wallet.get()
196
+ assert exc.value.code == "FEATURE_NOT_AVAILABLE"
197
+ assert exc.value.message == "Wallet is not available for your account yet."
198
+
199
+
200
+ # ═══════════════════════════════════════════════════════════════════════════════
201
+ # wallet.get — async
202
+ # ═══════════════════════════════════════════════════════════════════════════════
203
+
204
+
205
+ @pytest.mark.respx(base_url=BASE_URL)
206
+ async def test_async_get_returns_full_shape(async_client: AsyncTinyFish, respx_mock: MockRouter):
207
+ respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(200, json=_wallet_response()))
208
+ async with async_client as c:
209
+ result = await c.wallet.get()
210
+ assert isinstance(result, WalletResponse)
211
+ assert result.available_balance == "21.44"
212
+ assert result.rates is not None
213
+ assert len(result.rates.meters) == 1
214
+
215
+
216
+ @pytest.mark.respx(base_url=BASE_URL)
217
+ async def test_async_get_round_trips_negative_balance(async_client: AsyncTinyFish, respx_mock: MockRouter):
218
+ respx_mock.get(_WALLET_PATH).mock(
219
+ return_value=httpx.Response(200, json=_wallet_response(available_balance="-14.02"))
220
+ )
221
+ async with async_client as c:
222
+ result = await c.wallet.get()
223
+ assert result.available_balance == "-14.02"
224
+
225
+
226
+ @pytest.mark.respx(base_url=BASE_URL)
227
+ async def test_async_get_fully_degraded_response(async_client: AsyncTinyFish, respx_mock: MockRouter):
228
+ respx_mock.get(_WALLET_PATH).mock(
229
+ return_value=httpx.Response(200, json=_wallet_response(auto_reload=None, pending_top_up=None, rates=None))
230
+ )
231
+ async with async_client as c:
232
+ result = await c.wallet.get()
233
+ assert result.auto_reload is None
234
+ assert result.pending_top_up is None
235
+ assert result.rates is None
236
+
237
+
238
+ @pytest.mark.respx(base_url=BASE_URL)
239
+ async def test_async_get_auto_reload_configured_missing_threshold_raises(
240
+ async_client: AsyncTinyFish, respx_mock: MockRouter
241
+ ):
242
+ respx_mock.get(_WALLET_PATH).mock(
243
+ return_value=httpx.Response(200, json=_wallet_response(auto_reload={"state": "on", "recharge_to": "50.00"}))
244
+ )
245
+ async with async_client as c:
246
+ with pytest.raises(ValidationError):
247
+ await c.wallet.get()
248
+
249
+
250
+ @pytest.mark.respx(base_url=BASE_URL)
251
+ async def test_async_get_401(async_client: AsyncTinyFish, respx_mock: MockRouter):
252
+ respx_mock.get(_WALLET_PATH).mock(return_value=httpx.Response(401, json={"error": {"message": "unauthorized"}}))
253
+ async with async_client as c:
254
+ with pytest.raises(AuthenticationError):
255
+ await c.wallet.get()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes