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/__init__.py +10 -0
- mendao_cli/account.py +234 -0
- mendao_cli/admin.py +211 -0
- mendao_cli/config.py +240 -0
- mendao_cli/device.py +191 -0
- mendao_cli/errors.py +124 -0
- mendao_cli/http.py +191 -0
- mendao_cli/library.py +248 -0
- mendao_cli/main.py +142 -0
- mendao_cli/owner.py +67 -0
- mendao_cli/parser.py +249 -0
- mendao_cli/py.typed +0 -0
- mendao_cli/result.py +21 -0
- mendao_cli/shape.py +167 -0
- mendao_cli/update.py +225 -0
- mendao_cli-1.2.1.dist-info/METADATA +134 -0
- mendao_cli-1.2.1.dist-info/RECORD +20 -0
- mendao_cli-1.2.1.dist-info/WHEEL +4 -0
- mendao_cli-1.2.1.dist-info/entry_points.txt +3 -0
- mendao_cli-1.2.1.dist-info/licenses/LICENSE +21 -0
mendao_cli/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""门道 CLI: the one command-line client, for readers' Agents and the owner alike."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
#: The only source of the version is pyproject.toml.
|
|
8
|
+
__version__ = version("mendao-cli")
|
|
9
|
+
except PackageNotFoundError:
|
|
10
|
+
__version__ = "0+source"
|
mendao_cli/account.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""The Agent key: get it, store it, forget it, say who we are. A key never comes in by argv and never goes out in output."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import getpass
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from mendao_cli import config, device
|
|
14
|
+
from mendao_cli.errors import CliError, notice
|
|
15
|
+
from mendao_cli.http import DEFAULT_TIMEOUT, LIBRARY, Site
|
|
16
|
+
from mendao_cli.result import Result
|
|
17
|
+
|
|
18
|
+
_KEY = re.compile(r"^md_[A-Za-z0-9_-]{16,200}$")
|
|
19
|
+
#: How a key read by `login` came, as `whoami` reports it later (`obtained`).
|
|
20
|
+
_VIA = {"file": "key-file", "stdin": "stdin", "prompt": "prompt", "env": "env"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _is_terminal() -> bool:
|
|
24
|
+
"""A person is at the keyboard: they read the code on stderr and answer in the browser while this waits."""
|
|
25
|
+
return sys.stdin.isatty() and sys.stderr.isatty()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _stdin_bytes() -> bytes:
|
|
29
|
+
"""Bytes, not text: the console code page must not decide how the key is read (Windows pipes use the ANSI page)."""
|
|
30
|
+
buffer = getattr(sys.stdin, "buffer", None)
|
|
31
|
+
if buffer is None:
|
|
32
|
+
return str(sys.stdin.read()).encode("utf-8")
|
|
33
|
+
raw: bytes = buffer.read()
|
|
34
|
+
return raw
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _decode(raw: bytes) -> str:
|
|
38
|
+
try:
|
|
39
|
+
return config.decode_key_bytes(raw)
|
|
40
|
+
except ValueError:
|
|
41
|
+
raise CliError("validation", "密钥文件的编码读不出来(接受 UTF-8,带不带 BOM 都行,或带 BOM 的 UTF-16)", suggestion="用记事本「另存为」,编码选 UTF-8,再运行 mendao login --key-file ~/.config/mendao/key") from None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _read_key(args: argparse.Namespace) -> tuple[str, str] | None:
|
|
45
|
+
"""A key the reader already has: --key-file, `-` (stdin, without echo on a terminal) or the environment. None: sign in through the browser."""
|
|
46
|
+
if args.key_file == "-":
|
|
47
|
+
if sys.stdin.isatty():
|
|
48
|
+
return getpass.getpass("门道 Agent 密钥(输入时不显示):").strip(), "prompt"
|
|
49
|
+
return _decode(_stdin_bytes()), "stdin"
|
|
50
|
+
if args.key_file:
|
|
51
|
+
try:
|
|
52
|
+
raw = Path(args.key_file).expanduser().read_bytes()
|
|
53
|
+
except OSError:
|
|
54
|
+
raise CliError("validation", "读不了 --key-file 指定的文件", suggestion="mendao login --key-file ~/.config/mendao/key") from None
|
|
55
|
+
return _decode(raw), "file"
|
|
56
|
+
env = os.environ.get(config.ENV_KEY, "").strip()
|
|
57
|
+
return (env, "env") if env else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Standing:
|
|
62
|
+
member: bool
|
|
63
|
+
#: The server's `GET /usage` answer (design 3.3 `whoami`), or None from a server without it.
|
|
64
|
+
usage: dict[str, Any] | None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _standing(site: Site) -> Standing:
|
|
68
|
+
"""Who the key reads as. `GET /usage` first: it is not counted. A server without it (404) gets the older probe, one change, which is."""
|
|
69
|
+
try:
|
|
70
|
+
usage = site.request("GET", f"{LIBRARY}/usage")
|
|
71
|
+
except CliError as error:
|
|
72
|
+
if error.error_code == "mendao.needs-membership":
|
|
73
|
+
return Standing(False, None)
|
|
74
|
+
if error.error_type != "not_found":
|
|
75
|
+
raise
|
|
76
|
+
usage = None
|
|
77
|
+
if usage is None:
|
|
78
|
+
try:
|
|
79
|
+
site.request("GET", f"{LIBRARY}/library/changes", params={"after": 0, "limit": 1})
|
|
80
|
+
except CliError as error:
|
|
81
|
+
if error.error_code != "mendao.needs-membership":
|
|
82
|
+
raise
|
|
83
|
+
return Standing(False, None)
|
|
84
|
+
return Standing(True, None)
|
|
85
|
+
tier = usage.get("tier") if isinstance(usage, dict) else None
|
|
86
|
+
if tier not in ("member", "signed"):
|
|
87
|
+
raise CliError("auth", "密钥被拒绝", error_code="mendao.key-rejected")
|
|
88
|
+
return Standing(tier == "member", usage)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _membership_notice(url: str) -> dict[str, str]:
|
|
92
|
+
return {"id": "mendao.needs-membership", "text": "密钥有效,但这个账号的会员没开通或已到期,现在只能读每个问题排名前 60 的做法。", "fix": "到 " + url + "/membership 开通或续费;这把密钥不用换"}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def login(args: argparse.Namespace) -> Result:
|
|
96
|
+
if args.wait and args.key_file:
|
|
97
|
+
raise CliError("validation", "--wait 只用来等浏览器里的确认,不和 --key-file 一起用", suggestion="mendao login --wait")
|
|
98
|
+
found = None if args.wait else _read_key(args)
|
|
99
|
+
if found is None:
|
|
100
|
+
return _device_login(args)
|
|
101
|
+
key, source = found
|
|
102
|
+
if not _KEY.match(key):
|
|
103
|
+
raise CliError("validation", "这不像门道的 Agent 密钥(应以 md_ 开头)", suggestion="运行 mendao login 在浏览器里确认;或到会员中心创建密钥,把明文存进文件,再运行 mendao login --key-file ~/.config/mendao/key")
|
|
104
|
+
site = Site(timeout=min(args.timeout, DEFAULT_TIMEOUT), key=key)
|
|
105
|
+
verified, notices = not args.no_verify, []
|
|
106
|
+
if verified and not _standing(site).member:
|
|
107
|
+
# The key is good, the membership is not running: keep the key, so renewing needs no new one.
|
|
108
|
+
verified = False
|
|
109
|
+
notices.append(_membership_notice(site.url))
|
|
110
|
+
changed = config.stored_key(site.url) != key
|
|
111
|
+
path = config.save_key(site.url, key, {"via": _VIA[source]})
|
|
112
|
+
return Result({"stored": True, "changed": changed, "verified": verified, "source": source, "url": site.url, "key": config.Key(key, "file").masked, "path": str(path)}, notices=notices)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _device_login(args: argparse.Namespace) -> Result:
|
|
116
|
+
"""No key at hand: the device grant. On a terminal it waits here; for an Agent it returns at once and `--wait` collects."""
|
|
117
|
+
site = Site(timeout=min(args.timeout, DEFAULT_TIMEOUT), anonymous=True)
|
|
118
|
+
if not config.safe_for_credentials(site.url):
|
|
119
|
+
raise CliError("security", "地址不是 https,登录得到的密钥不能经它传回", error_code="mendao.insecure-url")
|
|
120
|
+
if args.wait:
|
|
121
|
+
pending = config.pending_device(site.url)
|
|
122
|
+
if pending is None:
|
|
123
|
+
raise CliError("not_found", "没有等待确认的登录", error_code="mendao.no-pending-login", suggestion="先运行 mendao login;已经登录的话,mendao whoami 看现在用哪把密钥")
|
|
124
|
+
if _is_terminal():
|
|
125
|
+
_tell(device.public_view(pending), args.timeout)
|
|
126
|
+
else:
|
|
127
|
+
signed_in = _already_signed_in(site)
|
|
128
|
+
if signed_in is not None:
|
|
129
|
+
return signed_in
|
|
130
|
+
pending = device.pending_or_start(site)
|
|
131
|
+
shown = device.public_view(pending)
|
|
132
|
+
if not _is_terminal():
|
|
133
|
+
note = notice("mendao.device-pending", site.url, uri=shown["verification_uri_complete"], code=shown["user_code"])
|
|
134
|
+
return Result({"status": "pending", **shown, "interval": pending["interval"], "next": "mendao login --wait", "url": site.url}, notices=[note])
|
|
135
|
+
_tell(shown, args.timeout)
|
|
136
|
+
if args.no_browser or not device._open_browser(shown["verification_uri_complete"]):
|
|
137
|
+
print("没有自动打开浏览器:请手动打开上面的地址。", file=sys.stderr, flush=True)
|
|
138
|
+
answer = device.wait(site, pending, args.timeout)
|
|
139
|
+
key = str(answer.get("access_token") or "")
|
|
140
|
+
if not _KEY.match(key):
|
|
141
|
+
raise CliError("api", "门道给回的不是 Agent 密钥", code=502, suggestion="重新运行 mendao login;一直这样请改用 mendao login --key-file ~/.config/mendao/key")
|
|
142
|
+
origin = {"via": "device"}
|
|
143
|
+
key_id = answer.get("key_id")
|
|
144
|
+
if isinstance(key_id, str) and key_id:
|
|
145
|
+
origin["keyId"] = key_id
|
|
146
|
+
changed = config.stored_key(site.url) != key
|
|
147
|
+
# Stored before anything else: the server hands a key over exactly once, and a failed check below must not lose it.
|
|
148
|
+
path = config.save_key(site.url, key, origin)
|
|
149
|
+
verified, notices = not args.no_verify, []
|
|
150
|
+
if verified:
|
|
151
|
+
try:
|
|
152
|
+
if not _standing(Site(timeout=site.timeout, key=key)).member:
|
|
153
|
+
verified = False
|
|
154
|
+
notices.append(_membership_notice(site.url))
|
|
155
|
+
except CliError as error:
|
|
156
|
+
verified = False
|
|
157
|
+
notices.append({"id": error.error_code or "mendao.offline", "text": f"密钥已经存好,但这次没能向门道确认它:{error.message}", "fix": "mendao whoami"})
|
|
158
|
+
data: dict[str, Any] = {"status": "done", "stored": True, "changed": changed, "verified": verified, "source": "device", "url": site.url,
|
|
159
|
+
"key": config.Key(key, "file").masked, "path": str(path)}
|
|
160
|
+
if "keyId" in origin:
|
|
161
|
+
data["keyId"] = origin["keyId"]
|
|
162
|
+
return Result(data, notices=notices)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _tell(shown: dict[str, Any], timeout: float) -> None:
|
|
166
|
+
print(f"在浏览器里确认登录门道:\n 打开 {shown['verification_uri_complete']}\n 核对代码 {shown['user_code']}\n"
|
|
167
|
+
f"正在等待确认,最多 {timeout:g} 秒(Ctrl-C 取消;之后运行 mendao login --wait 可以接着等)", file=sys.stderr, flush=True)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _already_signed_in(site: Site) -> Result | None:
|
|
171
|
+
"""A working key is already here: no second key is minted (an Agent may run `mendao login` every session, and an account
|
|
172
|
+
holds at most 20 live keys). A key the server rejects does not count: the sign-in goes ahead."""
|
|
173
|
+
current = config.current_key(site.url)
|
|
174
|
+
if current is None:
|
|
175
|
+
return None
|
|
176
|
+
try:
|
|
177
|
+
standing = _standing(Site(timeout=site.timeout, key=current.value))
|
|
178
|
+
except CliError as error:
|
|
179
|
+
if error.error_code != "mendao.key-rejected":
|
|
180
|
+
raise
|
|
181
|
+
return None
|
|
182
|
+
data = {"status": "signed_in", "source": current.source, "url": site.url, "key": current.masked, "location": config.key_location(current), "member": standing.member}
|
|
183
|
+
return Result(data, notices=[notice("mendao.signed-in", site.url)])
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def logout(args: argparse.Namespace) -> Result:
|
|
187
|
+
"""Forgets this site's key here. A key from the browser sign-in is first revoked on the server, since this CLI made it;
|
|
188
|
+
one the reader made by hand (--key-file, stdin, the environment) may be in use elsewhere and is left alone."""
|
|
189
|
+
url = config.base_url()
|
|
190
|
+
origin = config.stored_origin(url)
|
|
191
|
+
key = config.stored_key(url)
|
|
192
|
+
revoked = None
|
|
193
|
+
if key and origin.get("via") == "device":
|
|
194
|
+
revoked = device.revoke(Site(timeout=min(args.timeout, DEFAULT_TIMEOUT), anonymous=True), key)
|
|
195
|
+
deleted = config.forget_key(url)
|
|
196
|
+
pending = config.pending_device(url)
|
|
197
|
+
if pending is not None:
|
|
198
|
+
config.clear_pending_device(url, str(pending.get("device_code")))
|
|
199
|
+
data: dict[str, Any] = {"deleted": deleted, "url": url}
|
|
200
|
+
notices = []
|
|
201
|
+
if revoked is not None:
|
|
202
|
+
data["revoked"] = revoked
|
|
203
|
+
if origin.get("keyId"):
|
|
204
|
+
data["keyId"] = origin["keyId"]
|
|
205
|
+
if not revoked:
|
|
206
|
+
notices.append(notice("mendao.key-still-valid", url, key_id=origin["keyId"]))
|
|
207
|
+
if os.environ.get(config.ENV_KEY):
|
|
208
|
+
notices.append({"id": "mendao.env-key", "text": "环境变量 MENDAO_API_KEY 还在,仍然有效。", "fix": "unset MENDAO_API_KEY"})
|
|
209
|
+
return Result(data, notices=notices)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def whoami(args: argparse.Namespace) -> Result:
|
|
213
|
+
url = config.base_url()
|
|
214
|
+
key = config.current_key(url)
|
|
215
|
+
data: dict[str, Any] = {"url": url, "source": key.source if key else None, "key": key.masked if key else None, "access": "free", "authenticated": False}
|
|
216
|
+
notices: list[dict[str, str]] = []
|
|
217
|
+
if key:
|
|
218
|
+
origin = config.stored_origin(url) if key.source == "file" else {}
|
|
219
|
+
data["location"] = config.key_location(key)
|
|
220
|
+
data["obtained"] = {"env": "env", "key-file": "key-file"}.get(key.source) or origin.get("via", "unknown")
|
|
221
|
+
if origin.get("keyId"):
|
|
222
|
+
data["keyId"] = origin["keyId"]
|
|
223
|
+
standing = _standing(Site(timeout=args.timeout, key=key.value))
|
|
224
|
+
data.update(access="full" if standing.member else "free", authenticated=True)
|
|
225
|
+
if not standing.member:
|
|
226
|
+
# A good key whose membership is not running: say so instead of failing the status check.
|
|
227
|
+
data["membership"] = "not running"
|
|
228
|
+
notices.append(_membership_notice(url))
|
|
229
|
+
if standing.usage:
|
|
230
|
+
# Only what the server says: a field it no longer sends is left out, not shown as null.
|
|
231
|
+
data.update({name: standing.usage[name] for name in ("tier", "pageSize", "dailyCalls") if name in standing.usage})
|
|
232
|
+
if config.internal_secret():
|
|
233
|
+
data.update(access="full", internal=True)
|
|
234
|
+
return Result(data, notices=notices)
|
mendao_cli/admin.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""`mendao admin`: the site's admin surface. Every write is a dry run unless --apply; every write needs --reason.
|
|
2
|
+
|
|
3
|
+
mendao admin ops what this key may do, with parameters
|
|
4
|
+
mendao admin posts withdraw x:1,x:2 --reason 版权方要求
|
|
5
|
+
mendao admin posts import --file local.jsonl dry run: a verdict per line and the translation cost
|
|
6
|
+
mendao admin batch publish imp-… --reason 抽查过 --apply
|
|
7
|
+
mendao admin audit undo 42 --reason 撤错了 --apply
|
|
8
|
+
|
|
9
|
+
Monthly issues written by an Agent (owner only; docs/v2/ADMIN.md 「Agent 写月报」):
|
|
10
|
+
|
|
11
|
+
mendao admin report material --industry ai-video --period 2026-10 --out material.json
|
|
12
|
+
mendao admin report submit --industry ai-video --period 2026-10 --file issue.json dry run: every problem, nothing stored
|
|
13
|
+
mendao admin report submit --industry ai-video --period 2026-10 --file issue.json --apply publish; --replace to overwrite a published issue
|
|
14
|
+
mendao admin report list --period 2026-10
|
|
15
|
+
mendao admin reports withdraw ai-video:1 --reason 原因 --apply take it down again
|
|
16
|
+
|
|
17
|
+
Flags become the operation's parameters: --check-links is checkLinks, a,b is a list, [..] or {..} is JSON, null is nothing.
|
|
18
|
+
The key is MENDAO_ADMIN_KEY (scoped) or MENDAO_INTERNAL_SECRET (the owner); neither is ever read from a file.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import sys
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
from mendao_cli import config
|
|
31
|
+
from mendao_cli.errors import CliError
|
|
32
|
+
from mendao_cli.http import USER_AGENT
|
|
33
|
+
from mendao_cli.result import Result
|
|
34
|
+
|
|
35
|
+
ADMIN = "/api/v1/mendao/admin"
|
|
36
|
+
#: Flags the CLI keeps for itself; every other flag is a parameter of the operation.
|
|
37
|
+
_OWN = {"apply", "reason", "idempotency-key", "file", "out"}
|
|
38
|
+
#: `report <action>`: the Agent's monthly-issue workflow, mapped onto the reports.* operations.
|
|
39
|
+
REPORT_ACTIONS = {"material": "reports.material", "submit": "reports.submit", "list": "reports.list"}
|
|
40
|
+
_STATUS_TYPES = {400: "validation", 401: "auth", 403: "security", 404: "not_found", 409: "conflict", 413: "validation", 422: "validation", 429: "rate_limit"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _value(raw: str) -> Any:
|
|
44
|
+
if raw == "null":
|
|
45
|
+
return None
|
|
46
|
+
if raw[:1] in "[{":
|
|
47
|
+
try:
|
|
48
|
+
return json.loads(raw)
|
|
49
|
+
except ValueError:
|
|
50
|
+
raise CliError("validation", f"不是合法 JSON:{raw[:80]}") from None
|
|
51
|
+
return raw
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def split(words: list[str]) -> tuple[list[str], dict[str, Any], dict[str, Any]]:
|
|
55
|
+
"""Positional words, the operation's parameters, and the CLI's own flags."""
|
|
56
|
+
loose: list[str] = []
|
|
57
|
+
params: dict[str, Any] = {}
|
|
58
|
+
own: dict[str, Any] = {}
|
|
59
|
+
i = 0
|
|
60
|
+
while i < len(words):
|
|
61
|
+
word = words[i]
|
|
62
|
+
if not word.startswith("--") or word == "--":
|
|
63
|
+
loose.append(word)
|
|
64
|
+
i += 1
|
|
65
|
+
continue
|
|
66
|
+
name, eq, value = word[2:].partition("=")
|
|
67
|
+
if not eq:
|
|
68
|
+
if i + 1 < len(words) and not words[i + 1].startswith("--"):
|
|
69
|
+
value = words[i + 1]
|
|
70
|
+
i += 1
|
|
71
|
+
else:
|
|
72
|
+
value = "true"
|
|
73
|
+
target = own if name in _OWN else params
|
|
74
|
+
target[name if name in _OWN else name.replace("-", "_")] = value if name in _OWN else _value(value)
|
|
75
|
+
i += 1
|
|
76
|
+
return loose, params, own
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _read(path: str) -> str:
|
|
80
|
+
try:
|
|
81
|
+
return sys.stdin.read() if path == "-" else Path(path).expanduser().read_text(encoding="utf-8")
|
|
82
|
+
except (OSError, UnicodeDecodeError) as error:
|
|
83
|
+
raise CliError("validation", f"读不了文件:{path}({type(error).__name__})") from None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _headers(url: str) -> dict[str, str]:
|
|
87
|
+
headers = {"user-agent": USER_AGENT, "accept": "application/json"}
|
|
88
|
+
key, secret = config.admin_key(), config.internal_secret()
|
|
89
|
+
if key:
|
|
90
|
+
headers["x-admin-key"] = key
|
|
91
|
+
elif secret:
|
|
92
|
+
headers["x-internal-secret"] = secret
|
|
93
|
+
else:
|
|
94
|
+
raise CliError("auth", "没有管理员密钥", suggestion="export MENDAO_ADMIN_KEY=<管理员密钥>,主理人用 MENDAO_INTERNAL_SECRET")
|
|
95
|
+
if not config.safe_for_credentials(url):
|
|
96
|
+
raise CliError("security", "地址不是 https,密钥不会发出去", error_code="mendao.insecure-url")
|
|
97
|
+
return headers
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _call(method: str, path: str, body: dict[str, Any] | None, timeout: float, idempotency: str | None = None) -> Any:
|
|
101
|
+
url = config.base_url()
|
|
102
|
+
headers = _headers(url)
|
|
103
|
+
if idempotency:
|
|
104
|
+
headers["idempotency-key"] = idempotency
|
|
105
|
+
try:
|
|
106
|
+
with httpx.Client(base_url=url, timeout=timeout, follow_redirects=False, trust_env=not config.is_loopback(url)) as client:
|
|
107
|
+
response = client.request(method, path, json=body, headers=headers)
|
|
108
|
+
except httpx.TimeoutException:
|
|
109
|
+
raise CliError("timeout", f"门道 {timeout:g} 秒内没有回应", suggestion="写操作可能已执行:用同一个 --idempotency-key 重试不会重复执行") from None
|
|
110
|
+
except (httpx.TransportError, httpx.InvalidURL):
|
|
111
|
+
raise CliError("network", "连不上门道", error_code="mendao.offline") from None
|
|
112
|
+
try:
|
|
113
|
+
value = response.json()
|
|
114
|
+
except ValueError:
|
|
115
|
+
raise CliError("api", "门道返回的不是 JSON", code=502) from None
|
|
116
|
+
if response.status_code >= 400:
|
|
117
|
+
code = value.get("code", "error") if isinstance(value, dict) else "error"
|
|
118
|
+
detail = value.get("detail", "") if isinstance(value, dict) else ""
|
|
119
|
+
kind = _STATUS_TYPES.get(response.status_code, "api")
|
|
120
|
+
details = value.get("details") if isinstance(value, dict) else None
|
|
121
|
+
suggestion = SUGGESTIONS.get(code) or ("mendao admin ops 看这把钥匙能做什么、要哪些参数" if kind == "validation" else None)
|
|
122
|
+
raise CliError(kind, f"{code}: {detail}"[:600], code=response.status_code, suggestion=suggestion, details=details)
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
SUGGESTIONS = {
|
|
127
|
+
"report_rejected": "按 details.problems 逐条改 issue.json,再演练一次(不加 --apply),通过后再 --apply",
|
|
128
|
+
"issue_published": "这一期已在网站上:确认要替换就加 --replace,或先 mendao admin reports withdraw <领域:期号> --reason … --apply",
|
|
129
|
+
"period_open": "这个月还没过完,月底之后再提交",
|
|
130
|
+
"period_empty": "这个月本领域没有新收录条目,不出月报",
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _period(params: dict[str, Any]) -> None:
|
|
135
|
+
"""`--period 2026-10` is the operation's periodEnd; the server takes the month or any day of it."""
|
|
136
|
+
if "period" in params:
|
|
137
|
+
params["period_end"] = params.pop("period")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def report(action: str, rest: list[str], params: dict[str, Any], own: dict[str, Any], timeout: float) -> Result:
|
|
141
|
+
"""`mendao admin report material|submit|list`. Material can go to a file; submit reads the issue JSON from one."""
|
|
142
|
+
name = REPORT_ACTIONS.get(action)
|
|
143
|
+
if name is None:
|
|
144
|
+
raise CliError("validation", f"report 后面跟 {' / '.join(REPORT_ACTIONS)}", suggestion="mendao admin report material --industry <领域> --period 2026-10 --out material.json")
|
|
145
|
+
if rest:
|
|
146
|
+
raise CliError("validation", f"report {action} 不收位置参数:{' '.join(rest)}", suggestion="用 --industry 和 --period")
|
|
147
|
+
apply = str(own.get("apply", "false")).lower() == "true"
|
|
148
|
+
if action != "list":
|
|
149
|
+
_period(params)
|
|
150
|
+
missing = [flag for flag, key in (("--industry", "industry"), ("--period", "period_end")) if key not in params]
|
|
151
|
+
if missing:
|
|
152
|
+
raise CliError("validation", f"report {action} 要 {' 和 '.join(missing)}", suggestion=f"mendao admin report {action} --industry ai-video --period 2026-10")
|
|
153
|
+
if action == "material":
|
|
154
|
+
data = _call("POST", f"{ADMIN}/ops/{name}", {"params": params, "args": [], "apply": False, "reason": ""}, timeout)["data"]
|
|
155
|
+
out = own.get("out")
|
|
156
|
+
if not out:
|
|
157
|
+
return Result(data)
|
|
158
|
+
path = Path(out).expanduser()
|
|
159
|
+
try:
|
|
160
|
+
path.write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
|
161
|
+
except OSError as error:
|
|
162
|
+
raise CliError("dependency", f"写不了文件:{out}({type(error).__name__})") from None
|
|
163
|
+
return Result({"out": str(path), "issue": data["issue"], "items": len(data["items"]), "notices": data["notices"], "next": data["next"]})
|
|
164
|
+
if action == "list":
|
|
165
|
+
return Result(_call("POST", f"{ADMIN}/ops/{name}", {"params": params, "args": [], "apply": False, "reason": ""}, timeout)["data"])
|
|
166
|
+
if "file" not in own:
|
|
167
|
+
raise CliError("validation", "report submit 要 --file issue.json", suggestion="字段见 material 的 schema:title、framework、frameworkReason、markdown,可选 email")
|
|
168
|
+
try:
|
|
169
|
+
params["issue"] = json.loads(_read(own["file"]))
|
|
170
|
+
except ValueError:
|
|
171
|
+
raise CliError("validation", f"{own['file']} 不是合法 JSON") from None
|
|
172
|
+
reason = own.get("reason") or f"Agent 撰写 {params['industry']} {str(params['period_end'])[:7]} 月报"
|
|
173
|
+
body: dict[str, Any] = {"params": params, "args": [], "apply": apply, "reason": reason}
|
|
174
|
+
return Result(_call("POST", f"{ADMIN}/ops/{name}", body, timeout, own.get("idempotency-key")))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def admin(args: argparse.Namespace) -> Result:
|
|
178
|
+
words = [w for w in args.words]
|
|
179
|
+
if not words or words[0] in ("help", "--help"):
|
|
180
|
+
return Result({"usage": (__doc__ or "").strip()})
|
|
181
|
+
loose, params, own = split(words)
|
|
182
|
+
if not loose:
|
|
183
|
+
raise CliError("validation", "admin 后面要跟操作,如 posts withdraw", suggestion="mendao admin ops")
|
|
184
|
+
timeout = args.timeout
|
|
185
|
+
head = loose[0]
|
|
186
|
+
if head == "whoami":
|
|
187
|
+
return Result(_call("GET", f"{ADMIN}/whoami", None, timeout))
|
|
188
|
+
if head == "ops" and len(loose) == 1:
|
|
189
|
+
return Result(_call("GET", f"{ADMIN}/ops", None, timeout))
|
|
190
|
+
if head == "report":
|
|
191
|
+
return report(loose[1] if len(loose) > 1 else "", loose[2:], params, own, timeout)
|
|
192
|
+
if "." in head:
|
|
193
|
+
name, rest = head, loose[1:]
|
|
194
|
+
elif len(loose) >= 2:
|
|
195
|
+
name, rest = f"{head}.{loose[1]}", loose[2:]
|
|
196
|
+
else:
|
|
197
|
+
raise CliError("validation", f"{head} 后面要跟动作", suggestion="mendao admin ops")
|
|
198
|
+
apply = str(own.get("apply", "false")).lower() == "true"
|
|
199
|
+
reason = own.get("reason") or ""
|
|
200
|
+
if name == "audit.undo":
|
|
201
|
+
if len(rest) != 1 or not rest[0].isdigit():
|
|
202
|
+
raise CliError("validation", "audit undo 后面跟一条审计编号", suggestion="mendao admin audit list")
|
|
203
|
+
return Result(_call("POST", f"{ADMIN}/audit/{rest[0]}/undo", {"apply": apply, "reason": reason}, timeout, own.get("idempotency-key")))
|
|
204
|
+
if "file" in own:
|
|
205
|
+
text = _read(own["file"])
|
|
206
|
+
if name == "posts.import":
|
|
207
|
+
params["lines"] = [line for line in text.split("\n") if line.strip()] # JSONL: only \n ends a line
|
|
208
|
+
else:
|
|
209
|
+
params["body"] = text
|
|
210
|
+
body = {"params": params, "args": rest, "apply": apply, "reason": reason}
|
|
211
|
+
return Result(_call("POST", f"{ADMIN}/ops/{name}", body, timeout, own.get("idempotency-key")))
|