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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Independent Mouter HTTP client. Never import the backend runtime here."""
2
+
3
+ __version__ = "0.1.0"
mouter_cli/cli.py ADDED
@@ -0,0 +1,417 @@
1
+ """One JSON document per command; progress and prompts belong on stderr."""
2
+
3
+ import argparse
4
+ import getpass
5
+ import json
6
+ import math
7
+ import os
8
+ import re
9
+ import sys
10
+ import time
11
+ from collections.abc import Callable
12
+ from typing import Any, NoReturn
13
+ from uuid import uuid4
14
+
15
+ import simplejson
16
+
17
+ from mouter_cli import __version__, oauth
18
+ from mouter_cli.client import Client, success, task_data
19
+ from mouter_cli.config import api_origin
20
+ from mouter_cli.errors import CliError, invalid
21
+ from mouter_cli.storage import Credentials, Receipts, validate_key
22
+
23
+ GUIDE = """Use Mouter through shell commands. Set MOUTER_BASE_URL to the official API origin.
24
+ Use browser authorization with `mouter auth login`, or configure MOUTER_API_KEY for automation.
25
+ Never put credentials in prompts. `mouter balance` shows wallet and current credential limits;
26
+ `mouter usage` shows only this credential's recent consumption.
27
+ Only query balances, prices or consumption when the user requests that information.
28
+ 1. Understand the user's desired outcome. Extract a short keyword, not the entire request.
29
+ If the public tool key is already known, use `mouter catalog get TOOL_KEY` directly.
30
+ 2. Run `mouter catalog search 'keyword' --limit 10` or `mouter catalog categories`.
31
+ Search is literal and case-insensitive; multiple words are not an OR query.
32
+ Results are ordered by tool key, not relevance. The page contains summaries, not schemas.
33
+ 3. If necessary, rewrite the keyword at most twice, or list a relevant category with
34
+ `mouter catalog list --category KEY --limit 10`. Follow --cursor only when useful.
35
+ Never load all tool schemas. An empty result does not prove no suitable tool exists.
36
+ For broad results, prefer a distinctive capability substring over a platform name alone.
37
+ Do not concatenate unrelated keywords: literal search does not interpret intent or synonyms.
38
+ 4. Inspect selected candidates using `mouter catalog get TOOL_KEY`. Match public inputs and
39
+ outputs; if the user's goal is ambiguous, ask the user instead of guessing a paid action.
40
+ 5. Only query `mouter catalog price TOOL_KEY` when the user requests pricing.
41
+ Do not automatically query prices before execution. A quote is not a billing guarantee.
42
+ Catalog visibility does not grant execution permission. The server enforces permissions.
43
+ 6. Build a JSON input file and use `mouter call TOOL_KEY --input @file.json --wait`.
44
+ Use `--input @-` for piped JSON. Calls submit paid tasks; do not call to test discovery.
45
+ 7. Keep task_id and meta.idempotency_key. SUBMISSION_UNKNOWN means the request may have
46
+ been accepted: retry the SAME key, credential, tool and input within 24 hours.
47
+ Do not create a new key automatically. WAIT_TIMEOUT or interruption does not cancel a task.
48
+ Resume with `mouter tasks wait TASK_ID`; task reads use the original credential.
49
+ 8. JSON stdout is authoritative. `code=0` means command success, not necessarily task success:
50
+ inspect data.status. tasks get may return a failed task successfully. Failed waits exit 5.
51
+ A succeeded task with null result has no currently available result; do not resubmit it.
52
+ 9. Only query `mouter tasks billing TASK_ID` when the user requests task billing.
53
+ Do not automatically query billing after execution.
54
+ This read is free and uses the original credential; OAuth requires billing:read.
55
+ Amounts are JSON numbers in credits (unit=credit), up to 4 decimal places;
56
+ one credit equals 10,000 quota.
57
+ Use a decimal JSON parser for exact accounting. pending charged_amount=null is unknown,
58
+ not free; settled includes zero-cost success, not_charged means no charge.
59
+ Keep the task result if billing is unavailable or forbidden; report the charge as unknown.
60
+ Retry billing reads only, never resubmit paid work to recover a missing charge.
61
+ Website search is a separate browsing experience. This CLI has no embedded AI model.
62
+ """
63
+
64
+
65
+ class Parser(argparse.ArgumentParser):
66
+ def error(self, message: str) -> NoReturn:
67
+ # argparse's default message echoes arbitrary argv, potentially including secrets.
68
+ raise invalid("Invalid command arguments; run mouter --help.")
69
+
70
+
71
+ def _common(parser: argparse.ArgumentParser) -> None:
72
+ parser.add_argument("--human", action="store_true", default=argparse.SUPPRESS)
73
+ parser.add_argument("--verbose", action="store_true", default=argparse.SUPPRESS)
74
+ parser.add_argument("--base-url", default=argparse.SUPPRESS, help="Mouter API origin")
75
+
76
+
77
+ def parser() -> Parser:
78
+ root = Parser(prog="mouter", description="Discover and call Mouter tools on demand.")
79
+ _common(root)
80
+ root.add_argument("--version", action="version", version=__version__)
81
+ groups = root.add_subparsers(dest="group", required=True, parser_class=Parser)
82
+ guide = groups.add_parser("agent-guide", help="AI client discovery and execution instructions")
83
+ _common(guide)
84
+ auth = groups.add_parser("auth", help="Browser authorization or API key credentials")
85
+ _common(auth)
86
+ actions = auth.add_subparsers(dest="action", required=True, parser_class=Parser)
87
+ for name in ("login", "status", "logout"):
88
+ item = actions.add_parser(name)
89
+ _common(item)
90
+ if name == "login":
91
+ item.add_argument("--key-stdin", action="store_true", help="Read API key from stdin")
92
+ item.add_argument("--api-key", action="store_true", help="Prompt for an API key")
93
+ item.add_argument(
94
+ "--no-browser", action="store_true", help="Print the browser authorization URL"
95
+ )
96
+ item.add_argument("--login-timeout", type=float, default=180)
97
+ balance = groups.add_parser("balance", help="Wallet balance and current credential quota")
98
+ _common(balance)
99
+ usage = groups.add_parser("usage", help="Recent consumption by the current credential")
100
+ _common(usage)
101
+ usage.add_argument("--limit", type=int, default=10)
102
+ usage.add_argument("--cursor")
103
+ catalog = groups.add_parser("catalog", help="Public tool discovery")
104
+ _common(catalog)
105
+ actions = catalog.add_subparsers(dest="action", required=True, parser_class=Parser)
106
+ for name in ("categories", "list", "search", "get", "price"):
107
+ item = actions.add_parser(name)
108
+ _common(item)
109
+ if name in {"get", "price"}:
110
+ item.add_argument("tool_key")
111
+ if name == "search":
112
+ item.add_argument("query")
113
+ if name in {"list", "search"}:
114
+ item.add_argument("--category")
115
+ item.add_argument("--limit", type=int, default=10)
116
+ item.add_argument("--cursor")
117
+ item.add_argument("--status", choices=["active", "disabled", "all"], default="active")
118
+ call = groups.add_parser("call", help="Submit one paid task")
119
+ _common(call)
120
+ call.add_argument("tool_key")
121
+ call.add_argument("--input", required=True, help="JSON object, @file or @- for stdin")
122
+ call.add_argument("--idempotency-key")
123
+ call.add_argument("--wait", action="store_true")
124
+ call.add_argument("--wait-timeout", type=float, default=300)
125
+ tasks = groups.add_parser("tasks", help="Read tasks created by the current credential")
126
+ _common(tasks)
127
+ actions = tasks.add_subparsers(dest="action", required=True, parser_class=Parser)
128
+ for name in ("get", "wait", "billing"):
129
+ item = actions.add_parser(name)
130
+ _common(item)
131
+ item.add_argument("task_id")
132
+ if name == "wait":
133
+ item.add_argument("--wait-timeout", type=float, default=300)
134
+ return root
135
+
136
+
137
+ def _identifier(value: str, *, task: bool = False) -> str:
138
+ pattern = r"[A-Za-z0-9_-]{1,40}" if task else r"[a-z][a-z0-9_]{0,63}"
139
+ if not re.fullmatch(pattern, value):
140
+ raise invalid("Invalid task identifier." if task else "Invalid tool or category key.")
141
+ return value
142
+
143
+
144
+ def _timeout(value: float) -> float:
145
+ if not math.isfinite(value) or value <= 0 or value > 86400:
146
+ raise invalid("Wait timeout must be positive and at most 86400 seconds.")
147
+ return value
148
+
149
+
150
+ def _input(value: str) -> dict[str, Any]:
151
+ def unique(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
152
+ result: dict[str, Any] = {}
153
+ for key, item in pairs:
154
+ if key in result:
155
+ raise ValueError
156
+ result[key] = item
157
+ return result
158
+
159
+ def constant(_: str) -> None:
160
+ raise ValueError
161
+
162
+ try:
163
+ if value == "@-":
164
+ content = sys.stdin.buffer.read(65537)
165
+ elif value.startswith("@"):
166
+ with open(value[1:], "rb") as handle:
167
+ content = handle.read(65537)
168
+ else:
169
+ content = value.encode("utf-8")
170
+ if len(content) > 65536:
171
+ raise ValueError
172
+ body = json.loads(
173
+ content.decode("utf-8"), object_pairs_hook=unique, parse_constant=constant
174
+ )
175
+ if not isinstance(body, dict):
176
+ raise ValueError
177
+ # Python's JSON decoder may turn a huge exponent into infinity.
178
+ json.dumps(body, ensure_ascii=False, allow_nan=False).encode("utf-8")
179
+ return body
180
+ except (OSError, ValueError, UnicodeError, RecursionError):
181
+ raise invalid(
182
+ "Input must be a UTF-8 JSON object of at most 64 KiB. "
183
+ "Duplicate keys and non-finite numbers are rejected."
184
+ ) from None
185
+
186
+
187
+ def execute(args: argparse.Namespace) -> dict[str, Any]:
188
+ if args.group == "agent-guide":
189
+ return success({"guide": GUIDE})
190
+ origin = api_origin(getattr(args, "base_url", None))
191
+ credentials = Credentials(origin)
192
+ if args.group == "auth" and args.action == "logout":
193
+ revoked = oauth.logout(credentials)
194
+ return success(
195
+ {
196
+ "local_credential_deleted": True,
197
+ "oauth_revoked": revoked,
198
+ "environment_key_present": "MOUTER_API_KEY" in os.environ,
199
+ }
200
+ )
201
+ if args.group == "auth" and args.action == "login":
202
+ if args.key_stdin and args.api_key:
203
+ raise invalid("Choose either --api-key or --key-stdin.")
204
+ if not (args.key_stdin or args.api_key):
205
+ timeout = _timeout(args.login_timeout)
206
+ if timeout > 600:
207
+ raise invalid("Browser authorization timeout must be at most 600 seconds.")
208
+ return oauth.login(origin, credentials, timeout=timeout, no_browser=args.no_browser)
209
+ if args.no_browser or args.login_timeout != 180:
210
+ raise invalid("Browser options cannot be combined with API key login.")
211
+ if args.key_stdin:
212
+ secret = sys.stdin.readline(256).strip()
213
+ else:
214
+ if not sys.stdin.isatty():
215
+ raise invalid("Use auth login --key-stdin for non-interactive input.")
216
+ secret = getpass.getpass("Mouter API key: ")
217
+ secret = validate_key(secret)
218
+ with Client(origin, secret, verbose=getattr(args, "verbose", False)) as client:
219
+ value = client.request("GET", "/v1/credentials/current", authenticated=True)
220
+ with credentials.lock():
221
+ if credentials.oauth() is not None:
222
+ raise invalid("Run auth logout before replacing the saved CLI authorization.")
223
+ credentials.save(secret)
224
+ value["meta"] = {"saved": True, "environment_key_present": "MOUTER_API_KEY" in os.environ}
225
+ return value
226
+ needs_key = args.group in {"auth", "call", "tasks", "balance", "usage"} or (
227
+ args.group == "catalog" and args.action == "price"
228
+ )
229
+ provider: Callable[[float | None], str] | None = None
230
+ receipt_identity = None
231
+ record = None
232
+ wait_deadline = None
233
+ if args.group == "tasks" and args.action == "wait":
234
+ wait_deadline = time.monotonic() + _timeout(args.wait_timeout)
235
+ if needs_key and "MOUTER_API_KEY" not in os.environ:
236
+ # Read under the rotation lock so each command starts with a consistent identity.
237
+ with credentials.lock(wait_deadline):
238
+ record = credentials.oauth()
239
+ if record is not None:
240
+ oauth.validate_record(record)
241
+ receipt_identity = "oauth_grant:" + record["grant_uid"]
242
+
243
+ expected_grant, expected_client = record["grant_uid"], record["client_id"]
244
+
245
+ def read_token(deadline: float | None = None) -> str:
246
+ return oauth.access_token(
247
+ credentials,
248
+ expected_grant=expected_grant,
249
+ expected_client=expected_client,
250
+ deadline=deadline,
251
+ )
252
+
253
+ provider = read_token
254
+
255
+ secret = (
256
+ record["access_token"] if record is not None else credentials.read() if needs_key else None
257
+ )
258
+ with Client(
259
+ origin, secret, verbose=getattr(args, "verbose", False), token_provider=provider
260
+ ) as client:
261
+ if args.group == "auth":
262
+ return client.request("GET", "/v1/credentials/current", authenticated=True)
263
+ if args.group == "balance":
264
+ return client.request("GET", "/v1/credentials/balance", authenticated=True)
265
+ if args.group == "usage":
266
+ if not 1 <= args.limit <= 100:
267
+ raise invalid("Limit must be between 1 and 100.")
268
+ usage_params: dict[str, Any] = {"limit": args.limit}
269
+ if args.cursor:
270
+ usage_params["cursor"] = args.cursor
271
+ return client.request(
272
+ "GET", "/v1/credentials/usage", params=usage_params, authenticated=True
273
+ )
274
+ if args.group == "catalog":
275
+ if args.action == "categories":
276
+ return client.request("GET", "/v1/tool-categories")
277
+ if args.action in {"get", "price"}:
278
+ key = _identifier(args.tool_key)
279
+ suffix = "/price" if args.action == "price" else ""
280
+ return client.request("GET", f"/v1/tools/{key}{suffix}", authenticated=needs_key)
281
+ if not 1 <= args.limit <= 100:
282
+ raise invalid("Limit must be between 1 and 100.")
283
+ params: dict[str, Any] = {"limit": args.limit}
284
+ if args.status != "all":
285
+ params["status"] = args.status
286
+ if args.category:
287
+ params["category_key"] = _identifier(args.category)
288
+ if args.cursor:
289
+ params["cursor"] = args.cursor
290
+ if args.action == "search":
291
+ query = args.query.strip()
292
+ if (
293
+ not query
294
+ or len(query) > 200
295
+ or any(ord(c) < 32 or ord(c) == 127 for c in query)
296
+ ):
297
+ raise invalid("Use a non-empty search keyword of at most 200 characters.")
298
+ params["q"] = query
299
+ return client.request("GET", "/v1/tools", params=params)
300
+ if args.group == "tasks":
301
+ key = _identifier(args.task_id, task=True)
302
+ if args.action == "wait":
303
+ return client.wait(key, _timeout(args.wait_timeout), deadline=wait_deadline)
304
+ if args.action == "billing":
305
+ return client.request("GET", f"/v1/tasks/{key}/billing", authenticated=True)
306
+ value = client.request("GET", f"/v1/tasks/{key}", authenticated=True)
307
+ task_data(value)
308
+ return value
309
+ key = _identifier(args.tool_key)
310
+ body = _input(args.input)
311
+ timeout = _timeout(args.wait_timeout)
312
+ if secret is None:
313
+ raise CliError("UNAUTHENTICATED", "Run mouter auth login or set MOUTER_API_KEY.", 3)
314
+ idempotency_key = str(uuid4()) if args.idempotency_key is None else args.idempotency_key
315
+ receipt = Receipts(origin, receipt_identity or secret, key, idempotency_key)
316
+ receipt.prepare(body)
317
+ meta = {"idempotency_key": receipt.value["idempotency_key"]}
318
+ submitted: dict[str, Any] | None = None
319
+ try:
320
+ submitted = client.request(
321
+ "POST",
322
+ f"/v1/{key}",
323
+ body=body,
324
+ idempotency_key=meta["idempotency_key"],
325
+ authenticated=True,
326
+ )
327
+ try:
328
+ task = task_data(submitted)
329
+ except CliError:
330
+ raise CliError(
331
+ "SUBMISSION_UNKNOWN",
332
+ "Submission may have been accepted; recover using the same idempotency key.",
333
+ 7,
334
+ ) from None
335
+ meta.update(submitted.pop("meta", {}))
336
+ meta["receipt_saved"] = receipt.complete(task["task_id"])
337
+ result = (
338
+ client.wait(task["task_id"], timeout, initial=submitted) if args.wait else submitted
339
+ )
340
+ result["meta"] = meta
341
+ return result
342
+ except CliError as exc:
343
+ exc.payload["meta"] = meta
344
+ if submitted is not None and isinstance(submitted.get("data"), dict):
345
+ exc.payload["meta"]["task_id"] = submitted["data"].get("task_id")
346
+ raise
347
+ except KeyboardInterrupt:
348
+ raise CliError(
349
+ "INTERRUPTED",
350
+ "Stopped locally; the task may continue. "
351
+ "Recover using the task ID or the same idempotency key.",
352
+ 130,
353
+ data=submitted["data"]
354
+ if submitted
355
+ else {"idempotency_key": meta["idempotency_key"]},
356
+ ) from None
357
+
358
+
359
+ def _emit(payload: dict[str, Any], human: bool) -> None:
360
+ if human and isinstance(payload.get("data"), dict) and "guide" in payload["data"]:
361
+ print(payload["data"]["guide"])
362
+ else:
363
+ # Escape terminal control characters even for human output.
364
+ print(
365
+ simplejson.dumps(
366
+ payload,
367
+ use_decimal=True,
368
+ ensure_ascii=True,
369
+ allow_nan=False,
370
+ indent=2 if human else None,
371
+ )
372
+ )
373
+ data = payload.get("data")
374
+ if isinstance(data, dict) and data.get("status") == "succeeded" and data.get("result") is None:
375
+ print(
376
+ "The task succeeded, but its result is currently unavailable. "
377
+ "Do not resubmit automatically.",
378
+ file=sys.stderr,
379
+ )
380
+
381
+
382
+ def main(argv: list[str] | None = None) -> int:
383
+ args = None
384
+ try:
385
+ args = parser().parse_args(argv)
386
+ result = execute(args)
387
+ _emit(result, getattr(args, "human", False))
388
+ return 0
389
+ except CliError as exc:
390
+ _emit(exc.payload, bool(args and getattr(args, "human", False)))
391
+ return exc.exit_code
392
+ except KeyboardInterrupt:
393
+ _emit(
394
+ {
395
+ "code": "INTERRUPTED",
396
+ "message": "Stopped locally; submitted tasks continue.",
397
+ "data": None,
398
+ "request_id": None,
399
+ },
400
+ False,
401
+ )
402
+ return 130
403
+ except Exception:
404
+ _emit(
405
+ {
406
+ "code": "CLIENT_ERROR",
407
+ "message": "The client could not complete the command.",
408
+ "data": None,
409
+ "request_id": None,
410
+ },
411
+ False,
412
+ )
413
+ return 1
414
+
415
+
416
+ def entrypoint() -> None:
417
+ raise SystemExit(main())