mouter-cli 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.
mouter_cli/client.py ADDED
@@ -0,0 +1,320 @@
1
+ """Bounded HTTP transport and resumable polling; paid POST requests are never retried."""
2
+
3
+ import asyncio
4
+ import math
5
+ import random
6
+ import re
7
+ import sys
8
+ import time
9
+ from collections.abc import Callable
10
+ from datetime import UTC, datetime
11
+ from email.utils import parsedate_to_datetime
12
+ from typing import Any
13
+
14
+ import httpx
15
+ import simplejson
16
+
17
+ from mouter_cli import __version__
18
+ from mouter_cli.errors import CliError
19
+
20
+ # Messages are client-owned: never print arbitrary proxy/upstream response text.
21
+ PUBLIC_ERRORS = {
22
+ "UNAUTHENTICATED": "The credential is invalid, expired or revoked; run mouter auth login.",
23
+ "FORBIDDEN": "This credential does not permit the request.",
24
+ "INVALID_REQUEST": "The request is invalid; check the tool schema and parameters.",
25
+ "TOOL_NOT_FOUND": "The tool was not found.",
26
+ "TOOL_DISABLED": "The tool is disabled.",
27
+ "TASK_NOT_FOUND": "The task was not found for this credential.",
28
+ "IDEMPOTENCY_CONFLICT": "This idempotency key was used with different parameters.",
29
+ "INSUFFICIENT_BALANCE": "There is insufficient available balance.",
30
+ "INSUFFICIENT_QUOTA": "There is insufficient available quota.",
31
+ "RATE_LIMITED": "The request rate limit was reached.",
32
+ "SERVICE_UNAVAILABLE": "The service is temporarily unavailable.",
33
+ "REQUEST_TOO_LARGE": "The request is too large.",
34
+ }
35
+ TERMINAL = {"succeeded", "failed", "timed_out", "canceled"}
36
+ STATUSES = TERMINAL | {"submitted", "queued", "in_progress"}
37
+
38
+
39
+ def success(data: Any) -> dict[str, Any]:
40
+ return {"code": 0, "message": "", "data": data, "request_id": None}
41
+
42
+
43
+ def request_id(response: httpx.Response) -> str | None:
44
+ value = response.headers.get("x-request-id", "")
45
+ return value if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", value) else None
46
+
47
+
48
+ class Client:
49
+ def __init__(
50
+ self,
51
+ origin: str,
52
+ secret: str | None = None,
53
+ *,
54
+ verbose: bool = False,
55
+ transport: httpx.AsyncBaseTransport | None = None,
56
+ sleep: Callable[[float], None] = time.sleep,
57
+ clock: Callable[[], float] = time.monotonic,
58
+ token_provider: Callable[[float | None], str] | None = None,
59
+ ) -> None:
60
+ self.secret, self.verbose, self.sleep, self.clock = secret, verbose, sleep, clock
61
+ self.token_provider = token_provider
62
+ self.runner = asyncio.Runner()
63
+ self.http = httpx.AsyncClient(
64
+ base_url=origin,
65
+ follow_redirects=False,
66
+ transport=transport,
67
+ timeout=httpx.Timeout(30, connect=5, pool=5),
68
+ headers={"Accept": "application/json", "User-Agent": f"mouter-cli/{__version__}"},
69
+ trust_env=False,
70
+ )
71
+
72
+ def __enter__(self) -> "Client":
73
+ return self
74
+
75
+ def __exit__(self, *_: Any) -> None:
76
+ try:
77
+ self.runner.run(self.http.aclose())
78
+ finally:
79
+ self.runner.close()
80
+
81
+ def request(
82
+ self,
83
+ method: str,
84
+ path: str,
85
+ *,
86
+ params: dict[str, Any] | None = None,
87
+ body: dict[str, Any] | None = None,
88
+ idempotency_key: str | None = None,
89
+ authenticated: bool = False,
90
+ deadline: float | None = None,
91
+ ) -> dict[str, Any]:
92
+ end = min(self.clock() + 30, deadline) if deadline is not None else self.clock() + 30
93
+ headers = {}
94
+ if authenticated:
95
+ if self.token_provider is not None:
96
+ self.secret = self.token_provider(end)
97
+ if self.secret is None:
98
+ raise CliError("UNAUTHENTICATED", "Run mouter auth login or set MOUTER_API_KEY.", 3)
99
+ headers["Authorization"] = "Bearer " + self.secret
100
+ if idempotency_key is not None:
101
+ headers["Idempotency-Key"] = idempotency_key
102
+ response = None
103
+ for attempt in range(3 if method == "GET" else 1):
104
+ remaining = end - self.clock()
105
+ if remaining <= 0:
106
+ raise CliError("NETWORK_ERROR", "The request deadline was reached.")
107
+ try:
108
+ response = self.runner.run(
109
+ self._exchange(method, path, params, body, headers, remaining)
110
+ )
111
+ if self.clock() >= end:
112
+ raise TimeoutError
113
+ except (httpx.RequestError, TimeoutError) as exc:
114
+ if method != "GET":
115
+ raise CliError(
116
+ "SUBMISSION_UNKNOWN",
117
+ "Submission status is unknown; "
118
+ "retry with the same idempotency key within 24 hours.",
119
+ 7,
120
+ ) from None
121
+ if isinstance(exc, TimeoutError) and deadline is not None and end == deadline:
122
+ # Event loop timer resolution can expire the absolute wait budget
123
+ # just before clock() observes the same deadline on Windows.
124
+ raise CliError(
125
+ "WAIT_TIMEOUT", "Stopped waiting; resume with tasks wait.", 6
126
+ ) from None
127
+ if attempt == 2 or self.clock() + 2**attempt >= end:
128
+ raise CliError("NETWORK_ERROR", "Cannot reach the Mouter API.") from None
129
+ self.sleep(2**attempt)
130
+ continue
131
+ if self.verbose:
132
+ print(
133
+ f"{method} {path} status={response.status_code} "
134
+ f"request_id={request_id(response) or '-'}",
135
+ file=sys.stderr,
136
+ )
137
+ if method == "GET" and response.status_code in {429, 502, 503, 504} and attempt < 2:
138
+ delay = self._retry_delay(response, 2**attempt)
139
+ if self.clock() + delay < end:
140
+ self.sleep(delay)
141
+ continue
142
+ break
143
+ assert response is not None
144
+ rid = request_id(response)
145
+ if method == "POST" and (response.status_code >= 500 or response.is_redirect):
146
+ raise CliError(
147
+ "SUBMISSION_UNKNOWN",
148
+ "Submission may have been accepted; recover using the same idempotency key.",
149
+ 7,
150
+ request_id=rid,
151
+ )
152
+ try:
153
+ value = (
154
+ simplejson.loads(response.content, use_decimal=True)
155
+ if re.fullmatch(r"/v1/tasks/[A-Za-z0-9_-]{1,40}/billing", path)
156
+ else response.json()
157
+ )
158
+ except (ValueError, UnicodeError, RecursionError):
159
+ raise CliError(
160
+ "SUBMISSION_UNKNOWN" if method == "POST" else "PROTOCOL_ERROR",
161
+ "Invalid API response; recover submissions using the same idempotency key.",
162
+ 7 if method == "POST" else 4,
163
+ request_id=rid,
164
+ ) from None
165
+ valid = (
166
+ isinstance(value, dict)
167
+ and "data" in value
168
+ and "request_id" in value
169
+ and isinstance(value.get("message"), str)
170
+ and (
171
+ type(value.get("code")) is int
172
+ and value["code"] == 0
173
+ or isinstance(value.get("code"), str)
174
+ )
175
+ )
176
+ if not valid:
177
+ raise CliError(
178
+ "SUBMISSION_UNKNOWN" if method == "POST" else "PROTOCOL_ERROR",
179
+ "Invalid API response; recover submissions using the same idempotency key.",
180
+ 7 if method == "POST" else 4,
181
+ request_id=rid,
182
+ )
183
+ # The response header, rather than an arbitrary JSON string, is the trace identifier.
184
+ value["request_id"] = rid
185
+ if not response.is_success or value["code"] != 0:
186
+ code = value["code"] if value["code"] in PUBLIC_ERRORS else "API_ERROR"
187
+ exit_code = 3 if response.status_code in {401, 403} else 4
188
+ raise CliError(
189
+ code, PUBLIC_ERRORS.get(code, "The API request failed."), exit_code, request_id=rid
190
+ )
191
+ # Only documented public envelope fields enter output. Never echo proxy headers.
192
+ result = {key: value[key] for key in ("code", "message", "data", "request_id")}
193
+ result["message"] = ""
194
+ if "page" in value:
195
+ result["page"] = value["page"]
196
+ if method == "POST":
197
+ result["meta"] = {"replayed": response.headers.get("Idempotency-Replayed") == "true"}
198
+ return result
199
+
200
+ async def _exchange(
201
+ self,
202
+ method: str,
203
+ path: str,
204
+ params: dict[str, Any] | None,
205
+ body: dict[str, Any] | None,
206
+ headers: dict[str, str],
207
+ remaining: float,
208
+ ) -> httpx.Response:
209
+ # HTTPX phase timeouts alone do not bound a slowly streaming response.
210
+ async with asyncio.timeout(remaining):
211
+ async with self.http.stream(
212
+ method,
213
+ path,
214
+ params=params,
215
+ json=body,
216
+ headers=headers,
217
+ timeout=httpx.Timeout(remaining, connect=min(5, remaining), pool=min(5, remaining)),
218
+ ) as response:
219
+ content = bytearray()
220
+ async for chunk in response.aiter_bytes():
221
+ content.extend(chunk)
222
+ if len(content) > 8 * 1024 * 1024:
223
+ raise httpx.DecodingError("Response exceeds public client limit")
224
+ return httpx.Response(
225
+ response.status_code,
226
+ headers={
227
+ key: value
228
+ for key, value in response.headers.items()
229
+ if key.lower() not in {"content-encoding", "content-length"}
230
+ },
231
+ content=bytes(content),
232
+ request=response.request,
233
+ )
234
+
235
+ @staticmethod
236
+ def _retry_delay(response: httpx.Response, fallback: int) -> float:
237
+ value = response.headers.get("Retry-After", "")
238
+ try:
239
+ delay = float(value)
240
+ if not math.isfinite(delay) or delay < 0:
241
+ raise ValueError
242
+ return delay
243
+ except ValueError:
244
+ try:
245
+ date = parsedate_to_datetime(value)
246
+ return max(0, (date - datetime.now(UTC)).total_seconds())
247
+ except (ValueError, TypeError, OverflowError):
248
+ return float(fallback)
249
+
250
+ def wait(
251
+ self,
252
+ task_id: str,
253
+ timeout: float,
254
+ initial: dict[str, Any] | None = None,
255
+ *,
256
+ deadline: float | None = None,
257
+ ) -> dict[str, Any]:
258
+ deadline = (
259
+ min(self.clock() + timeout, deadline)
260
+ if deadline is not None
261
+ else self.clock() + timeout
262
+ )
263
+ value = initial
264
+ interval = 1.0
265
+ while True:
266
+ if value is not None:
267
+ task = task_data(value)
268
+ if task["status"] in TERMINAL:
269
+ if task["status"] == "succeeded":
270
+ return value
271
+ raise CliError(
272
+ "TASK_FAILED",
273
+ "The task did not succeed; inspect its public status and error.",
274
+ 5,
275
+ data=task,
276
+ request_id=value["request_id"],
277
+ )
278
+ remaining = deadline - self.clock()
279
+ if remaining <= 0:
280
+ raise CliError(
281
+ "WAIT_TIMEOUT",
282
+ "Stopped waiting; the task continues. Resume with tasks wait.",
283
+ 6,
284
+ data=value["data"] if value else {"task_id": task_id},
285
+ request_id=value["request_id"] if value else None,
286
+ )
287
+ if value is not None:
288
+ self.sleep(min(interval + random.uniform(0, 0.1), remaining))
289
+ interval = min(interval * 2, 5)
290
+ if self.clock() >= deadline:
291
+ continue
292
+ try:
293
+ value = self.request(
294
+ "GET", f"/v1/tasks/{task_id}", authenticated=True, deadline=deadline
295
+ )
296
+ except CliError as exc:
297
+ if exc.payload["code"] == "WAIT_TIMEOUT" or (
298
+ self.clock() >= deadline and exc.payload["code"] == "NETWORK_ERROR"
299
+ ):
300
+ raise CliError(
301
+ "WAIT_TIMEOUT",
302
+ "Stopped waiting; resume with tasks wait.",
303
+ 6,
304
+ data=value["data"] if value else {"task_id": task_id},
305
+ request_id=value["request_id"] if value else None,
306
+ ) from None
307
+ raise
308
+
309
+
310
+ def task_data(value: dict[str, Any]) -> dict[str, Any]:
311
+ task = value["data"]
312
+ if (
313
+ not isinstance(task, dict)
314
+ or not isinstance(task.get("status"), str)
315
+ or task.get("status") not in STATUSES
316
+ or not isinstance(task.get("task_id"), str)
317
+ or not re.fullmatch(r"[A-Za-z0-9_-]{1,40}", task["task_id"])
318
+ ):
319
+ raise CliError("PROTOCOL_ERROR", "The API returned invalid task metadata.")
320
+ return task
mouter_cli/config.py ADDED
@@ -0,0 +1,56 @@
1
+ """Origin-bound configuration, with HTTPS required outside literal loopback addresses."""
2
+
3
+ import ipaddress
4
+ import os
5
+ from pathlib import Path
6
+ from urllib.parse import urlsplit
7
+
8
+ from mouter_cli.errors import invalid
9
+
10
+ # Official site exposes the public REST API at this origin.
11
+ DEFAULT_ORIGIN = "https://mouter.ai"
12
+
13
+
14
+ def api_origin(value: str | None = None) -> str:
15
+ raw = value if value is not None else os.environ.get("MOUTER_BASE_URL", DEFAULT_ORIGIN)
16
+ if not raw or any(ord(c) < 33 or ord(c) == 127 for c in raw):
17
+ raise invalid("Set MOUTER_BASE_URL to the Mouter API origin (https://host).")
18
+ try:
19
+ parsed = urlsplit(raw)
20
+ host = parsed.hostname
21
+ port = parsed.port
22
+ loopback = bool(host and ipaddress.ip_address(host).is_loopback)
23
+ except ValueError:
24
+ # DNS hostnames are valid, but never qualify for the HTTP loopback exception.
25
+ try:
26
+ parsed = urlsplit(raw)
27
+ host, port, loopback = parsed.hostname, parsed.port, False
28
+ except ValueError:
29
+ raise invalid("Invalid API origin.") from None
30
+ if (
31
+ not host
32
+ or parsed.username is not None
33
+ or parsed.password is not None
34
+ or parsed.path not in {"", "/"}
35
+ or parsed.query
36
+ or parsed.fragment
37
+ or parsed.scheme not in {"https", "http"}
38
+ or (parsed.scheme == "http" and not loopback)
39
+ or "\\" in raw
40
+ or "%" in host
41
+ ):
42
+ raise invalid("Use an HTTPS API origin without credentials, path, query or fragment.")
43
+ host = host.lower().encode("idna").decode("ascii")
44
+ authority = f"[{host}]" if ":" in host else host
45
+ if port is not None and port != (443 if parsed.scheme == "https" else 80):
46
+ authority += f":{port}"
47
+ return f"{parsed.scheme}://{authority}"
48
+
49
+
50
+ def state_directory() -> Path:
51
+ override = os.environ.get("MOUTER_STATE_DIR")
52
+ if override:
53
+ return Path(override).expanduser()
54
+ if os.name == "nt":
55
+ return Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "Mouter"
56
+ return Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local/state"))) / "mouter"
mouter_cli/errors.py ADDED
@@ -0,0 +1,22 @@
1
+ """Stable local errors. Exception and response text never become terminal diagnostics."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ class CliError(Exception):
7
+ def __init__(
8
+ self,
9
+ code: str,
10
+ message: str,
11
+ exit_code: int = 4,
12
+ *,
13
+ data: Any = None,
14
+ request_id: str | None = None,
15
+ ) -> None:
16
+ super().__init__(code)
17
+ self.exit_code = exit_code
18
+ self.payload = {"code": code, "message": message, "data": data, "request_id": request_id}
19
+
20
+
21
+ def invalid(message: str) -> CliError:
22
+ return CliError("INVALID_REQUEST", message, 2)