mendao-cli 1.2.1__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.
mendao_cli/http.py ADDED
@@ -0,0 +1,191 @@
1
+ """The way to the site. Turns every failure into a CliError with something to do next."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+ import re
6
+ import time
7
+ from collections.abc import Callable
8
+ from datetime import datetime, timedelta, timezone
9
+ from email.utils import parsedate_to_datetime
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from mendao_cli import __version__, config
15
+ from mendao_cli.errors import CliError
16
+
17
+ LIBRARY = "/api/v1/mendao"
18
+ INTERNAL = "/api/v1/internal"
19
+ DEFAULT_TIMEOUT = 30.0
20
+ USER_AGENT = f"mendao-cli/{__version__}"
21
+ #: Idempotent requests are tried again this many times after a dropped connection or a gateway error, inside --timeout.
22
+ RETRIES = 2
23
+ RETRY_STATUSES = (502, 503, 504)
24
+ IDEMPOTENT = ("GET", "HEAD", "OPTIONS")
25
+ BACKOFF_SECONDS = 0.5
26
+ BACKOFF_CAP_SECONDS = 8.0
27
+ _MAX_DETAIL = 200
28
+ _RATELIMIT_RESET = re.compile(r"(?:^|;)\s*t=(\d+)")
29
+
30
+ #: Indirections the tests replace, so retries run at once and every wait can be read.
31
+ _monotonic: Callable[[], float] = time.monotonic
32
+ _sleep: Callable[[float], None] = time.sleep
33
+ _jitter: Callable[[], float] = random.random
34
+
35
+
36
+ def backoff(attempt: int) -> float:
37
+ """Exponential with equal jitter: half the step is fixed, half random, so parallel Agents do not retry in step."""
38
+ step = min(BACKOFF_CAP_SECONDS, BACKOFF_SECONDS * (1 << attempt))
39
+ return step / 2 + step / 2 * _jitter()
40
+
41
+
42
+ class Site:
43
+ """One site, with whichever credential applies. `anonymous` sends none, for the sign-in endpoints."""
44
+
45
+ def __init__(self, *, timeout: float = DEFAULT_TIMEOUT, use_secret: bool = False, key: str | None = None, anonymous: bool = False) -> None:
46
+ self.url = config.base_url()
47
+ self.timeout = timeout
48
+ self.use_secret = use_secret
49
+ self.key = key
50
+ if key is None and not use_secret and not anonymous:
51
+ found = config.current_key(self.url)
52
+ self.key = found.value if found else None
53
+ self.secret = None if anonymous else config.internal_secret()
54
+
55
+ @property
56
+ def has_access(self) -> bool:
57
+ return bool(self.key or self.secret)
58
+
59
+ def _headers(self) -> dict[str, str]:
60
+ headers = {"user-agent": USER_AGENT, "accept": "application/json"}
61
+ if self.use_secret:
62
+ if not self.secret:
63
+ raise CliError("auth", "没有配置内部密钥")
64
+ headers["x-internal-secret"] = self.secret
65
+ elif self.key:
66
+ headers["authorization"] = "Bearer " + self.key
67
+ elif self.secret:
68
+ headers["x-internal-secret"] = self.secret
69
+ if len(headers) > 2 and not config.safe_for_credentials(self.url):
70
+ raise CliError("security", "地址不是 https,密钥不会发出去", error_code="mendao.insecure-url")
71
+ return headers
72
+
73
+ def send(self, method: str, path: str, *, params: dict[str, Any] | None = None, body: dict[str, Any] | None = None,
74
+ form: dict[str, str] | None = None, timeout: float | None = None) -> httpx.Response:
75
+ """One answer from the site, whatever its status. An idempotent request survives a dropped connection or a 502, 503, 504:
76
+ it is tried again up to RETRIES times with backoff, and all of it, waits included, stays inside `timeout`."""
77
+ clean = {k: v for k, v in (params or {}).items() if v is not None}
78
+ budget = self.timeout if timeout is None else timeout
79
+ deadline = _monotonic() + budget
80
+ headers = self._headers()
81
+ retry = method.upper() in IDEMPOTENT
82
+ attempt = 0
83
+ while True:
84
+ remaining = deadline - _monotonic()
85
+ if remaining <= 0:
86
+ raise CliError("timeout", f"门道 {budget:g} 秒内没有回应", suggestion="稍后重试,或加大 --timeout")
87
+ try:
88
+ # A system proxy would answer for this machine's own ports. Everywhere else the reader's proxy settings apply.
89
+ with httpx.Client(base_url=self.url, timeout=remaining, follow_redirects=False, trust_env=not config.is_loopback(self.url)) as client:
90
+ response = client.request(method, path, params=clean, json=body, data=form, headers=headers)
91
+ except httpx.TimeoutException:
92
+ raise CliError("timeout", f"门道 {budget:g} 秒内没有回应", suggestion="稍后重试,或加大 --timeout") from None
93
+ except (httpx.NetworkError, httpx.RemoteProtocolError):
94
+ wait = backoff(attempt)
95
+ if not retry or attempt >= RETRIES or _monotonic() + wait >= deadline:
96
+ raise CliError("network", "连不上门道", error_code="mendao.offline") from None
97
+ except (httpx.TransportError, httpx.InvalidURL):
98
+ raise CliError("network", "连不上门道", error_code="mendao.offline") from None
99
+ else:
100
+ if not retry or response.status_code not in RETRY_STATUSES or attempt >= RETRIES:
101
+ return response
102
+ asked = retry_after(response)
103
+ wait = float(asked) if asked is not None else backoff(attempt)
104
+ if _monotonic() + wait >= deadline:
105
+ return response
106
+ _sleep(wait)
107
+ attempt += 1
108
+
109
+ def request(self, method: str, path: str, *, params: dict[str, Any] | None = None, body: dict[str, Any] | None = None) -> Any:
110
+ return self._decode(self.send(method, path, params=params, body=body))
111
+
112
+ def _decode(self, response: httpx.Response) -> Any:
113
+ status = response.status_code
114
+ if 200 <= status < 300:
115
+ try:
116
+ return response.json()
117
+ except ValueError:
118
+ raise CliError("api", "门道返回的不是 JSON", code=502, suggestion="稍后重试;一直这样就是站点在更新或出了故障") from None
119
+ detail = _detail(response)
120
+ if status in (401, 403):
121
+ if self.key and "login_required" in (detail, _problem_code(response)):
122
+ # The key is good; what it asked for is for members, and this account's membership is not running (never opened, or ended).
123
+ raise CliError("auth", "这项内容要会员:这个账号的会员没开通或已到期", code=status, error_code="mendao.needs-membership",
124
+ suggestion="到 https://mendaoai.com/membership 开通或续费;不开通会员也能读每个问题排名前 60 的做法")
125
+ if self.key:
126
+ raise CliError("auth", "密钥被拒绝", code=status, error_code="mendao.key-rejected")
127
+ if self.use_secret:
128
+ raise CliError("auth", "内部密钥被拒绝", code=status, suggestion="核对环境变量 MENDAO_INTERNAL_SECRET")
129
+ raise CliError("auth", "这项内容要 Agent 密钥", code=status, error_code="mendao.needs-key")
130
+ if status == 404:
131
+ raise CliError("not_found", "找不到这项内容", code=404, suggestion="mendao search <关键词> 或 mendao questions 找到正确的编号")
132
+ if status == 429:
133
+ raise rate_limited(response)
134
+ if status in (400, 422):
135
+ raise CliError("validation", f"门道拒绝了这个参数:{detail}", code=status, suggestion="mendao commands <命令> 查看参数")
136
+ if status == 409:
137
+ raise CliError("conflict", f"门道报告冲突:{detail}", code=409, suggestion="重新取一次最新内容后再试")
138
+ raise CliError("api", f"门道出错了({status})", code=status, suggestion="稍后重试;一直这样请运行 mendao whoami 确认地址")
139
+
140
+
141
+ def rate_limited(response: httpx.Response) -> CliError:
142
+ """A 429 is never retried here. `retry_after` is what the server said, never a guess; a daily cap says when it resets."""
143
+ wait = retry_after(response)
144
+ if "key_rate_limited" in (_problem_code(response), _detail(response)):
145
+ if wait is None:
146
+ return CliError("rate_limit", "这把密钥今天的调用次数用完了;服务器没有说什么时候恢复", code=429, error_code="mendao.daily-limit")
147
+ resets = (datetime.now(timezone.utc) + timedelta(seconds=wait)).strftime("%Y-%m-%d %H:%M UTC")
148
+ hours, minutes = divmod(max(1, (wait + 59) // 60), 60)
149
+ later = f"{hours} 小时 {minutes} 分钟" if hours else f"{minutes} 分钟"
150
+ return CliError("rate_limit", f"这把密钥今天的调用次数用完了,{resets} 恢复(约 {later}后)", code=429, retry_after=wait,
151
+ error_code="mendao.daily-limit", suggestion=f"{resets} 之后再试,现在重试不会成功;mendao whoami 看今天的用量")
152
+ if wait is None:
153
+ return CliError("rate_limit", "调用太频繁,已被限流;服务器没有说要等多久", code=429, error_code="mendao.rate-limited")
154
+ return CliError("rate_limit", "调用太频繁,已被限流", code=429, retry_after=wait, error_code="mendao.rate-limited")
155
+
156
+
157
+ def retry_after(response: httpx.Response) -> int | None:
158
+ """Seconds the server asked for: `Retry-After` (seconds or a date), else the reset of `RateLimit` (design 3.4). None when it said nothing."""
159
+ raw = response.headers.get("retry-after", "").strip()
160
+ if raw.isdigit():
161
+ return int(raw)
162
+ if raw:
163
+ try:
164
+ when = parsedate_to_datetime(raw)
165
+ except (TypeError, ValueError):
166
+ when = None
167
+ if when is not None and when.tzinfo is not None:
168
+ return max(0, int((when - datetime.now(timezone.utc)).total_seconds()))
169
+ found = _RATELIMIT_RESET.search(response.headers.get("ratelimit", ""))
170
+ if found:
171
+ return int(found.group(1))
172
+ reset = response.headers.get("ratelimit-reset", "").strip()
173
+ return int(reset) if reset.isdigit() else None
174
+
175
+
176
+ def _problem_code(response: httpx.Response) -> str:
177
+ """The server's problem+json carries the machine reason in `code` (`login_required`) and prose in `detail`; older answers had it in `detail`."""
178
+ try:
179
+ value = response.json()
180
+ except ValueError:
181
+ return ""
182
+ return str(value.get("code") or "") if isinstance(value, dict) else ""
183
+
184
+
185
+ def _detail(response: httpx.Response) -> str:
186
+ try:
187
+ value = response.json()
188
+ except ValueError:
189
+ return "未说明原因"
190
+ detail = value.get("detail") if isinstance(value, dict) else None
191
+ return str(detail)[:_MAX_DETAIL] if detail else "未说明原因"
mendao_cli/library.py ADDED
@@ -0,0 +1,248 @@
1
+ """Reading the library: questions, posts, search, one post, the calendar, the changes feed."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import re
6
+ from datetime import date
7
+ from typing import Any
8
+
9
+ from mendao_cli import config, shape
10
+ from mendao_cli.errors import CliError, notice
11
+ from mendao_cli.http import LIBRARY, Site
12
+ from mendao_cli.result import Result
13
+
14
+ #: The server's page size (LIST_PAGE_SIZE, design decision 13): one number for every list, here as everywhere.
15
+ MAX_PAGE = 30
16
+ MAX_CHANGES = 500
17
+ MAX_QUERY = 200
18
+ DEFAULT_MONTHS = 12
19
+ DEFAULT_QUESTIONS = 200
20
+ #: The facet flags of posts and search, as the API names them.
21
+ FACETS = ("form", "level", "practice", "evidence", "source", "scale", "tool", "topic")
22
+ MAX_FACET_VALUES = 6
23
+ _SLUG = re.compile(r"^[a-z0-9-]{1,50}$")
24
+ _CONSUMER = re.compile(r"^[\w.-]{1,60}$")
25
+ #: Third-party text travels in `data`; this says so, for whoever orchestrates the Agent.
26
+ UNTRUSTED = {"_untrusted": True}
27
+
28
+
29
+ def _site(args: argparse.Namespace) -> Site:
30
+ return Site(timeout=args.timeout)
31
+
32
+
33
+ def _slug(value: str | None, name: str) -> str | None:
34
+ if value is not None and not _SLUG.match(value):
35
+ raise CliError("validation", f"--{name} 要用编号,只含小写字母、数字和短横线", suggestion="mendao questions 列出全部编号")
36
+ return value
37
+
38
+
39
+ def _day(value: str | None, name: str) -> str | None:
40
+ if value is None:
41
+ return None
42
+ try:
43
+ if len(value) != 10:
44
+ raise ValueError
45
+ date.fromisoformat(value)
46
+ except ValueError:
47
+ raise CliError("validation", f"--{name} 要写成 YYYY-MM-DD", suggestion=f"--{name} 2026-11-01") from None
48
+ return value
49
+
50
+
51
+ def _limit(value: int, top: int) -> int:
52
+ if value < 1 or value > top:
53
+ raise CliError("validation", f"--limit 要在 1 到 {top} 之间", suggestion=f"--limit {min(top, 20)},更多内容用 next_cursor 翻页")
54
+ return value
55
+
56
+
57
+ def _field_notices(items: list[dict[str, Any]], fields: list[str] | None) -> list[dict[str, str]]:
58
+ missing = shape.missing_fields(items, fields)
59
+ if not missing:
60
+ return []
61
+ return [{"id": "mendao.unknown-field", "text": "这些字段没有内容:" + ",".join(missing), "fix": "mendao post <id> --full 看全部字段"}]
62
+
63
+
64
+ def _facet(value: str | None, name: str) -> str | None:
65
+ """Comma-separated values, each an id or a Chinese label; the server says which one it does not know."""
66
+ if value is None:
67
+ return None
68
+ parts = [p.strip() for p in value.replace(",", ",").split(",") if p.strip()]
69
+ if not parts or len(parts) > MAX_FACET_VALUES or any(len(p) > 50 for p in parts):
70
+ raise CliError("validation", f"--{name} 写一到 {MAX_FACET_VALUES} 个值,逗号分开", suggestion=f"mendao tags 看 {name} 的可选值")
71
+ return ",".join(parts)
72
+
73
+
74
+ def _page_query(args: argparse.Namespace, q: str | None) -> dict[str, Any]:
75
+ return {
76
+ "industry": _slug(args.industry, "industry"),
77
+ "question": _slug(args.question, "question"),
78
+ "platform": args.platform.lower() if args.platform else None,
79
+ "tag": args.tag,
80
+ **{name: _facet(getattr(args, name, None), name) for name in FACETS},
81
+ "since": _day(args.since, "since"),
82
+ "until": _day(args.until, "until"),
83
+ "sort": args.sort,
84
+ "q": q,
85
+ }
86
+
87
+
88
+ def _list(args: argparse.Namespace, q: str | None) -> Result:
89
+ query = _page_query(args, q)
90
+ digest = shape.query_digest(query)
91
+ fields = shape.parse_fields(args.fields)
92
+ size = _limit(args.limit, MAX_PAGE)
93
+ page, skip = 1, 0
94
+ if args.cursor:
95
+ cursor = shape.decode_cursor(args.cursor, digest, lambda: "用上一次输出里的 next_cursor,原样传回")
96
+ page, skip, size = cursor.page, cursor.skip, cursor.size
97
+ site = _site(args)
98
+ body = site.request("GET", f"{LIBRARY}/library/posts", params={**query, "page": page, "size": size})
99
+ # The size the server used, when it says: a server that serves fewer than asked must not make the next page skip any.
100
+ served = body.get("size")
101
+ size = served if isinstance(served, int) and 0 < served <= size else size
102
+ raw = body.get("posts", [])[skip:]
103
+ items = [shape.view_post(p, full=args.full, fields=fields) for p in raw]
104
+ kept = shape.fit_budget(items)
105
+ trimmed = kept < len(items)
106
+ total, visible = int(body.get("total", 0)), int(body.get("visible", body.get("total", 0)))
107
+ meta: dict[str, Any] = {"_count": kept, "_total": visible, **UNTRUSTED}
108
+ if trimmed:
109
+ meta["_truncated"] = True
110
+ meta["next_cursor"] = shape.Cursor(page, skip + kept, size, digest).encode()
111
+ elif page < int(body.get("pages", 1)):
112
+ meta["next_cursor"] = shape.Cursor(page + 1, 0, size, digest).encode()
113
+ notices = _field_notices(items, fields)
114
+ if visible < total:
115
+ notices.insert(0, _limit_notice(site.url, total, visible, body.get("unlock")))
116
+ data = {"query": {k: v for k, v in query.items() if v is not None}, "posts": items[:kept], "total": total, "visible": visible, "size": size,
117
+ "platforms": body.get("platforms", {}), "tags": body.get("tags", {}), "facets": {k: v for k, v in (body.get("facets") or {}).items() if v}}
118
+ return Result(data, meta, notices)
119
+
120
+
121
+ def _limit_notice(url: str, total: int, visible: int, unlock: Any) -> dict[str, str]:
122
+ """Why the list is cut, as the server says (`unlock`): no key was used (`login`), or the key's account is not a member (`subscribe`: what it needs is a membership, not another key)."""
123
+ if unlock == "subscribe":
124
+ return {**notice("mendao.needs-membership", url), "text": f"共匹配 {total} 条,这把密钥的账号还不是会员,只能看其中 {visible} 条(每个问题排名前 60 的做法)。", "fix": f"到 {url}/membership 开通会员;这把密钥不用换,开通后马上生效"}
125
+ return {**notice("mendao.free-limit", url), "text": f"共匹配 {total} 条,没有密钥只能看其中 {visible} 条(公开内容,即每个问题排名前 20 的做法;未开通会员的账号可读前 60)。"}
126
+
127
+
128
+ def posts(args: argparse.Namespace) -> Result:
129
+ return _list(args, None)
130
+
131
+
132
+ def search(args: argparse.Namespace) -> Result:
133
+ words = args.query.strip()
134
+ if not words or len(words) > MAX_QUERY:
135
+ raise CliError("validation", f"搜索词要在 1 到 {MAX_QUERY} 字之间", suggestion='mendao search "分镜 一致性"')
136
+ return _list(args, words)
137
+
138
+
139
+ def tags(args: argparse.Namespace) -> Result:
140
+ """The vocabulary to filter with. Tools without posts are left out unless asked: an Agent picks from what exists."""
141
+ body = _site(args).request("GET", f"{LIBRARY}/library/tags", params={"industry": _slug(args.industry, "industry")})
142
+ tools = [t for t in body.get("tools", []) if args.all or t.get("count")]
143
+ facets = {name: [f"{v['id']}({v['label']})" for v in facet.get("values", [])] for name, facet in (body.get("facets") or {}).items()}
144
+ data = {"facets": facets, "tools": [{k: t.get(k) for k in ("id", "label", "broader", "count") if t.get(k) is not None} for t in tools], "topics": body.get("topics", []), "version": body.get("version")}
145
+ notices = [] if tools or args.all else [{"id": "mendao.no-tools", "text": "这个范围里还没有带工具标签的做法。", "fix": "加 --all 看整张工具词表"}]
146
+ return Result(data, {"_count": len(tools)}, notices)
147
+
148
+
149
+ def post(args: argparse.Namespace) -> Result:
150
+ if not re.match(r"^[\w:./-]{1,240}$", args.post_id) or ".." in args.post_id:
151
+ raise CliError("validation", "post_id 不合法", suggestion="mendao post x:1234567890,编号来自 mendao posts 的 id 字段")
152
+ fields = shape.parse_fields(args.fields)
153
+ body = _site(args).request("GET", f"{LIBRARY}/library/post", params={"id": args.post_id, "industry": _slug(args.industry, "industry")})
154
+ if fields:
155
+ merged = {**shape.concise_post(body, excerpt=True), **shape.clip_fields(body, shape.DETAIL_FIELD_CHARS)}
156
+ return Result(shape.mask(merged, fields), dict(UNTRUSTED), _field_notices([merged], fields))
157
+ if args.full:
158
+ return Result(body, dict(UNTRUSTED))
159
+ shaped = {**shape.clip_fields(body, shape.DETAIL_FIELD_CHARS), "title": shape.headline(body)}
160
+ for drop in ("media", "metrics", "repo", "score", "isNew", "readmeTranslated", "fullText"):
161
+ shaped.pop(drop, None)
162
+ meta = {**UNTRUSTED, **({"_truncated": True} if shaped.pop("_truncated", False) else {})}
163
+ return Result(shaped, meta)
164
+
165
+
166
+ def _offset_page(rows: list[dict[str, Any]], args: argparse.Namespace, digest: str, default_limit: int) -> tuple[list[dict[str, Any]], dict[str, Any]]:
167
+ """A list the server sends whole: pages are local, with the same cursor shape."""
168
+ size = _limit(args.limit, 1000) if args.limit else default_limit
169
+ start = 0
170
+ if args.cursor:
171
+ cursor = shape.decode_cursor(args.cursor, digest, lambda: "用上一次输出里的 next_cursor,原样传回")
172
+ start, size = cursor.skip, cursor.size
173
+ window = rows[start : start + size]
174
+ kept = shape.fit_budget(window)
175
+ end = start + kept
176
+ meta: dict[str, Any] = {"_count": kept, "_total": len(rows)}
177
+ if end < len(rows):
178
+ meta["next_cursor"] = shape.Cursor(1, end, size, digest).encode()
179
+ if kept < len(window):
180
+ meta["_truncated"] = True
181
+ return window[:kept], meta
182
+
183
+
184
+ def questions(args: argparse.Namespace) -> Result:
185
+ industry = _slug(args.industry, "industry")
186
+ fields = shape.parse_fields(args.fields)
187
+ body = _site(args).request("GET", f"{LIBRARY}/library/questions")
188
+ rows: list[dict[str, Any]] = []
189
+ for group in body.get("industries", []):
190
+ if industry and group.get("id") != industry:
191
+ continue
192
+ for question in group.get("questions", []):
193
+ rows.append({"industryId": group.get("id"), "industry": group.get("name"), **question})
194
+ window, meta = _offset_page(rows, args, shape.query_digest({"questions": industry}), DEFAULT_QUESTIONS)
195
+ if fields:
196
+ window = [shape.mask(r, fields) for r in window]
197
+ return Result({"questions": window, "total": body.get("total")}, meta, _field_notices(window, fields))
198
+
199
+
200
+ def calendar(args: argparse.Namespace) -> Result:
201
+ query = {"industry": _slug(args.industry, "industry"), "question": _slug(args.question, "question")}
202
+ body = _site(args).request("GET", f"{LIBRARY}/library/calendar", params=query)
203
+ months, meta = _offset_page(list(body.get("months", [])), args, shape.query_digest(query), DEFAULT_MONTHS)
204
+ return Result({"months": months}, meta)
205
+
206
+
207
+ def _change_view(change: dict[str, Any], *, full: bool, fields: list[str] | None) -> dict[str, Any]:
208
+ if isinstance(change.get("post"), dict):
209
+ return {**change, "post": shape.view_post(change["post"], full=full, fields=fields)}
210
+ return change
211
+
212
+
213
+ def changes(args: argparse.Namespace) -> Result:
214
+ if not _CONSUMER.match(args.consumer):
215
+ raise CliError("validation", "--consumer 只能用字母、数字、点、短横线", suggestion="--consumer topic-agent")
216
+ site = _site(args)
217
+ if args.reset:
218
+ config.require_writable_state()
219
+ before = config.stored_cursor(site.url, args.consumer)
220
+ config.save_cursor(site.url, args.consumer, 0)
221
+ return Result({"consumer": args.consumer, "cursor": 0, "changed": before != 0})
222
+ if not site.has_access:
223
+ raise CliError("auth", "增量同步要 Agent 密钥", error_code="mendao.needs-key")
224
+ limit = _limit(args.limit, MAX_CHANGES)
225
+ fields = shape.parse_fields(args.fields)
226
+ replay = args.cursor is not None
227
+ if replay:
228
+ if not args.cursor.isdigit():
229
+ raise CliError("validation", "--cursor 要用上一次输出里的 next_cursor", suggestion="--cursor 1200")
230
+ after = int(args.cursor)
231
+ else:
232
+ config.require_writable_state()
233
+ after = config.stored_cursor(site.url, args.consumer)
234
+ body = site.request("GET", f"{LIBRARY}/library/changes", params={"after": after, "limit": limit})
235
+ rows = [_change_view(c, full=args.full, fields=fields) for c in body.get("changes", [])]
236
+ kept = shape.fit_budget(rows)
237
+ trimmed = kept < len(rows)
238
+ rows = rows[:kept]
239
+ position = int(rows[-1]["seq"]) if trimmed else int(body.get("cursor", after))
240
+ more = trimmed or bool(body.get("more"))
241
+ meta: dict[str, Any] = {"_count": len(rows), **UNTRUSTED}
242
+ if trimmed:
243
+ meta["_truncated"] = True
244
+ if more:
245
+ meta["next_cursor"] = str(position)
246
+ data = {"changes": rows, "after": after, "cursor": position, "more": more, "consumer": args.consumer, "remembered": not (replay or args.peek)}
247
+ delivered = None if replay or args.peek else (lambda: config.save_cursor(site.url, args.consumer, position))
248
+ return Result(data, meta, delivered=delivered)
mendao_cli/main.py ADDED
@@ -0,0 +1,142 @@
1
+ """The entry: parse, dispatch, one JSON document on stdout. Discovery touches no network and no credentials."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ from typing import Any
9
+
10
+ from mendao_cli import __version__, config, parser as cli, update
11
+ from mendao_cli.errors import GUIDANCE, CliError, close_matches
12
+ from mendao_cli.result import Result
13
+
14
+ SCHEMA_VERSION = 2
15
+ _DISCOVERY = {"summary": "mendao commands", "command": "mendao commands <command-path>", "full": "mendao commands --full"}
16
+
17
+
18
+ def _print(value: Any) -> None:
19
+ sys.stdout.write(json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "\n")
20
+ sys.stdout.flush()
21
+
22
+
23
+ def _safe_url() -> str:
24
+ try:
25
+ return config.base_url()
26
+ except CliError:
27
+ return config.DEFAULT_URL
28
+
29
+
30
+ def _reject_control_characters(argv: list[str]) -> None:
31
+ for word in argv:
32
+ if any(ord(ch) < 0x20 for ch in word):
33
+ raise CliError("validation", "参数里有控制字符", suggestion="去掉换行和不可见字符后重试")
34
+
35
+
36
+ def _entry(parser: argparse.ArgumentParser, spec: cli.Spec, *, detail: bool) -> dict[str, Any]:
37
+ args, options = cli.options_of(parser)
38
+ entry: dict[str, Any] = {"name": spec.name, "description": spec.description, "group": spec.group, "args": args, "options": options, "example": spec.example}
39
+ if detail:
40
+ entry["parameters"] = cli.parameters(parser)
41
+ entry["constraints"] = []
42
+ return entry
43
+
44
+
45
+ def _catalogue(args: argparse.Namespace, top: argparse.ArgumentParser, table: dict[str, cli.Spec]) -> dict[str, Any]:
46
+ if args.explain:
47
+ if args.explain not in GUIDANCE:
48
+ raise CliError("validation", "没有这个编号", suggestion="mendao commands --full 列出全部编号", did_you_mean=close_matches(args.explain, GUIDANCE))
49
+ entry = GUIDANCE[args.explain]
50
+ return {"code": 200, "data": {"id": args.explain, "kind": entry["kind"], "text": entry["text"], "fix": entry["fix"].format(url=_safe_url())}}
51
+ children = next(a.choices for a in top._actions if isinstance(a, argparse._SubParsersAction))
52
+ selected = list(table.values())
53
+ if args.path:
54
+ name = " ".join(args.path)
55
+ if name not in table:
56
+ raise CliError("validation", f"没有这个命令:{name}", suggestion="mendao commands", did_you_mean=close_matches(name, table))
57
+ selected = [table[name]]
58
+ if args.group:
59
+ selected = [s for s in selected if s.group == args.group]
60
+ if args.search:
61
+ selected = [s for s in selected if args.search.lower() in (s.name + s.description).lower()]
62
+ detail = args.full or bool(args.path)
63
+ out: dict[str, Any] = {
64
+ "tool": "mendao", "version": __version__, "schemaVersion": SCHEMA_VERSION,
65
+ "commands": [_entry(children[s.name], s, detail=detail) for s in selected],
66
+ "global_parameters": cli.parameters(top) if detail else [],
67
+ "global_constraints": [],
68
+ "discovery": _DISCOVERY,
69
+ }
70
+ if args.full:
71
+ out["guidance"] = {key: {**entry, "fix": entry["fix"].format(url=_safe_url())} for key, entry in GUIDANCE.items()}
72
+ return out
73
+
74
+
75
+ def _run(argv: list[str]) -> int:
76
+ top, table = cli.build()
77
+ if not argv:
78
+ top.print_help(sys.stdout)
79
+ return 0
80
+ try:
81
+ args = top.parse_args(argv)
82
+ except SystemExit as stop: # argparse's --help prints and exits 0.
83
+ return int(stop.code or 0)
84
+ if args.version:
85
+ sys.stdout.write(f"mendao-cli {__version__}\n")
86
+ return 0
87
+ if args.command is None:
88
+ top.print_help(sys.stdout)
89
+ return 0
90
+ if args.command == "commands":
91
+ _print(_catalogue(args, top, table))
92
+ return 0
93
+ _reject_control_characters(argv)
94
+ result: Result = table[args.command].handler(args)
95
+ newer = None if args.command == "update" else update.notice()
96
+ if newer:
97
+ result.notices.append(newer)
98
+ _print(result.envelope())
99
+ if result.delivered:
100
+ try:
101
+ result.delivered()
102
+ except OSError as error: # The answer is out, so a second document would break the contract: stderr and the exit code say it.
103
+ print(f"mendao: 同步位置没有存下,下次会重复这一批({type(error).__name__})", file=sys.stderr)
104
+ return 1
105
+ return 0
106
+
107
+
108
+ def _force_utf8() -> None:
109
+ """Windows pipes encode with the ANSI code page (GBK, cp1252), which cannot hold the emoji in post text. JSON out is UTF-8, and `backslashreplace` means writing can never raise."""
110
+ for stream in (sys.stdout, sys.stderr):
111
+ reconfigure = getattr(stream, "reconfigure", None)
112
+ if reconfigure is None: # A stream that cannot be reconfigured keeps what it has.
113
+ continue
114
+ try:
115
+ reconfigure(encoding="utf-8", errors="backslashreplace")
116
+ except (ValueError, OSError):
117
+ pass
118
+
119
+
120
+ def main(argv: list[str] | None = None) -> int:
121
+ _force_utf8()
122
+ words = list(sys.argv[1:] if argv is None else argv)
123
+ try:
124
+ return _run(words)
125
+ except CliError as error:
126
+ _print(error.envelope(argv=words, url=_safe_url()))
127
+ return error.exit_code
128
+ except KeyboardInterrupt:
129
+ _print(CliError("cancelled", "已中断", suggestion="重新运行同一条命令").envelope(argv=words, url=_safe_url()))
130
+ return 1
131
+ except BrokenPipeError:
132
+ # The reader went away. Nothing was delivered, so nothing moved; quiet stdout so the interpreter's exit stays clean.
133
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
134
+ return 1
135
+ except Exception as error: # An Agent gets an envelope, never a traceback.
136
+ print(f"mendao: {type(error).__name__}", file=sys.stderr)
137
+ _print(CliError("internal", f"mendao 内部错误({type(error).__name__})", suggestion="升到最新版再试:mendao update").envelope(argv=words, url=_safe_url()))
138
+ return 1
139
+
140
+
141
+ if __name__ == "__main__":
142
+ raise SystemExit(main())
mendao_cli/owner.py ADDED
@@ -0,0 +1,67 @@
1
+ """The owner's commands. They exist only where MENDAO_INTERNAL_SECRET is set: the parser adds them, or nothing does."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import shlex
6
+ from typing import Any
7
+
8
+ from mendao_cli import shape
9
+ from mendao_cli.errors import CliError
10
+ from mendao_cli.http import INTERNAL, Site
11
+ from mendao_cli.result import Result
12
+
13
+ #: The server's command errors that are the caller's to fix.
14
+ _CALLER_ERRORS = ("unknown_command", "incomplete_command", "unknown_flag", "missing_argument", "invalid_value", "invalid_argument", "too_many_arguments", "unknown_flags")
15
+
16
+
17
+ def _site(args: argparse.Namespace) -> Site:
18
+ return Site(timeout=args.timeout, use_secret=True)
19
+
20
+
21
+ def status(args: argparse.Namespace) -> Result:
22
+ body = _site(args).request("GET", f"{INTERNAL}/status")
23
+ fields = shape.parse_fields(args.fields)
24
+ return Result(shape.mask(body, fields) if fields else body)
25
+
26
+
27
+ def run(args: argparse.Namespace) -> Result:
28
+ """The tick answers when it is done, up to nine minutes away, and the gateway gives up long before that.
29
+ So no answer within the wait means started, not failed. Ticks key on stable run ids, so running it twice is safe."""
30
+ site = _site(args)
31
+ target = f"{site.url}{INTERNAL}/tick"
32
+ if args.dry_run:
33
+ return Result({"would_post": target}, {"_dry_run": True})
34
+ try:
35
+ report: Any = site.request("POST", f"{INTERNAL}/tick")
36
+ except CliError as error:
37
+ if error.error_type == "timeout" or error.code in (502, 504, 524):
38
+ return Result({"triggered": True, "answered": False, "next": "mendao status"})
39
+ raise
40
+ return Result({"triggered": True, "answered": True, "report": report})
41
+
42
+
43
+ def ops(args: argparse.Namespace) -> Result:
44
+ words = [word for word in args.line if word != "--"]
45
+ if not words:
46
+ raise CliError("validation", "ops 后面要跟一条运维命令", suggestion="mendao ops help")
47
+ line = shlex.join(words)
48
+ site = _site(args)
49
+ if args.dry_run:
50
+ return Result({"would_post": f"{site.url}{INTERNAL}/command", "line": line, "industry": args.industry}, {"_dry_run": True})
51
+ try:
52
+ envelope = site.request("POST", f"{INTERNAL}/command", body={"line": line, "industry": args.industry})
53
+ except CliError as error:
54
+ if error.code != 404:
55
+ raise
56
+ # The edge shuts the command line to every address but the host's own and the watchdog's.
57
+ raise CliError("not_found", "运维命令行只对服务器本机开放", code=404,
58
+ suggestion="先开隧道 ssh -N -L 10040:127.0.0.1:10040 us60,再用 MENDAO_URL=http://127.0.0.1:10040 运行 mendao ops") from error
59
+ if envelope.get("ok"):
60
+ meta: dict[str, Any] = {"hint": envelope["hint"]} if envelope.get("hint") else {}
61
+ return Result(envelope.get("stored") if envelope.get("stored") else envelope.get("data"), meta)
62
+ code = str(envelope.get("error") or "command_failed")
63
+ if code in _CALLER_ERRORS or code.startswith(("invalid_", "unknown_", "missing_")):
64
+ raise CliError("validation", f"{code}: {envelope.get('message', '')}", suggestion=str(envelope.get("hint") or "mendao ops help"))
65
+ if code == "not_allowed":
66
+ raise CliError("security", f"{code}: {envelope.get('message', '')}", suggestion="mendao ops help")
67
+ raise CliError("internal", f"{code}: {envelope.get('message', '')}", code=500, suggestion=str(envelope.get("hint") or "mendao status 看运行状态"))