@duanz/pi-d-reach 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/SKILL.md +480 -0
- package/fanout-defaults.example.json +33 -0
- package/package.json +52 -4
- package/plugin/index.ts +4097 -0
- package/plugin/pwa.ts +1078 -0
- package/plugin/scripts/fanout.sh +1944 -0
- package/plugin/scripts/load_key.sh +36 -0
- package/plugin/scripts/mcp_call.py +137 -0
- package/plugin/scripts/pdf2text.py +39 -0
- package/plugin/scripts/quota.py +281 -0
- package/plugin/scripts/quota_probe.py +272 -0
- package/plugin/scripts/render.mjs +234 -0
- package/plugin/scripts/route_config.py +156 -0
- package/references/channels.md +226 -0
- package/references/cn-reach.md +153 -0
- package/references/dev.md +65 -0
- package/references/finance.md +84 -0
- package/references/scrape.md +283 -0
- package/references/search.md +308 -0
- package/references/social.md +76 -0
- package/references/video.md +82 -0
- package/scripts/fanout.sh +1944 -0
- package/scripts/load_key.sh +36 -0
- package/scripts/mcp_call.py +137 -0
- package/scripts/quota.py +281 -0
- package/scripts/quota_probe.py +272 -0
- package/scripts/route_config.py +156 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# D-Reach 凭据查找链 —— 技能与密钥来源解耦(接口不碰内容)
|
|
3
|
+
# 用法: EXA=$(sh "$SKILL_DIR/scripts/load_key.sh" EXA_API_KEY https://dashboard.exa.ai) || exit 1
|
|
4
|
+
# 查找顺序: 1) $NAME 环境变量 2) ~/.config/agents/env 3) <skill目录>/.env 4) ~/.secrets/console_cookies.txt
|
|
5
|
+
# (第 4 项是 cookie-getter 推送到面板后落的盘,登录态 cookie 走这条路)
|
|
6
|
+
# 找不到 → stderr 输出四要素引导(变量名/申请URL/写入位置/降级说明), exit 1
|
|
7
|
+
# 安全: 本脚本永不 echo key 值; 调用方也不得 echo/cat 结果
|
|
8
|
+
NAME="$1"
|
|
9
|
+
URL="$2"
|
|
10
|
+
SKILL_DIR="${SKILL_DIR:-$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)}"
|
|
11
|
+
|
|
12
|
+
val=""
|
|
13
|
+
# 1) 环境变量
|
|
14
|
+
eval "val=\${$NAME:-}"
|
|
15
|
+
# 2)+3) env 文件候选
|
|
16
|
+
if [ -z "$val" ]; then
|
|
17
|
+
for f in "$HOME/.config/agents/env" "$SKILL_DIR/.env" "$HOME/.secrets/console_cookies.txt"; do
|
|
18
|
+
[ -f "$f" ] || continue
|
|
19
|
+
v=$(sed -n "s/^${NAME}=//p" "$f" | head -1 | tr -d '\r\n"')
|
|
20
|
+
if [ -n "$v" ]; then val="$v"; break; fi
|
|
21
|
+
done
|
|
22
|
+
fi
|
|
23
|
+
|
|
24
|
+
if [ -n "$val" ]; then
|
|
25
|
+
printf '%s' "$val"
|
|
26
|
+
exit 0
|
|
27
|
+
fi
|
|
28
|
+
|
|
29
|
+
cat >&2 <<EOF
|
|
30
|
+
[load_key] 缺少 $NAME
|
|
31
|
+
1. 申请: ${URL:-见 SKILL.md 路由表对应服务}(多数有免费额度)
|
|
32
|
+
2. 写入(推荐): echo "$NAME=你的key" >> ~/.config/agents/env (该文件权限设为 600)
|
|
33
|
+
或写入本技能目录 .env(已在 .gitignore 内,永不提交)
|
|
34
|
+
3. 不想配: 本次自动降级到路由表备选通道(免费但结果可能差些)
|
|
35
|
+
EOF
|
|
36
|
+
exit 1
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""极简 MCP streamable-HTTP 客户端:一次调用完成 initialize → tools/call。
|
|
3
|
+
|
|
4
|
+
只做 d-reach 需要的那一种用法:无认证、单次请求-响应、结果要 JSON。
|
|
5
|
+
不实现 SSE 长连接、不实现 notifications 队列、不实现 resumability ——
|
|
6
|
+
Parallel 的免费档三个工具都是「问一次答一次」,用不上那些。
|
|
7
|
+
|
|
8
|
+
用法:
|
|
9
|
+
mcp_call.py <endpoint> <tool> '<json-args>'
|
|
10
|
+
mcp_call.py https://mcp.parallel.ai/mcp web_search '{"objective":"...","search_queries":["..."]}'
|
|
11
|
+
|
|
12
|
+
成功: 把 tool 返回的第一个 content[].text 原样打到 stdout(通常是 JSON 字符串)
|
|
13
|
+
失败: 打一行 `MCP_ERROR: ...` 到 stdout 并退出码 1(调用方按文本判失败,不必解析 stderr)
|
|
14
|
+
"""
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.request
|
|
20
|
+
|
|
21
|
+
PROTO = "2024-11-05"
|
|
22
|
+
TIMEOUT = 40
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _post(endpoint: str, body: dict, session: str | None) -> tuple[str, str | None]:
|
|
26
|
+
data = json.dumps(body).encode()
|
|
27
|
+
req = urllib.request.Request(endpoint, data=data, method="POST")
|
|
28
|
+
req.add_header("Content-Type", "application/json")
|
|
29
|
+
# 不声明 text/event-stream 时部分服务端只回 JSON,声明后回 SSE —— 两种都吃
|
|
30
|
+
req.add_header("Accept", "application/json, text/event-stream")
|
|
31
|
+
# 有些 MCP 网关(You.com)会 403 掉 Python-urllib 的默认 UA
|
|
32
|
+
req.add_header("User-Agent", "d-reach/1.0")
|
|
33
|
+
# 需要鉴权的 MCP 网关(如 TinyFish)走环境变量传 Bearer,别把 key 写进命令行
|
|
34
|
+
_auth = os.environ.get("MCP_AUTH", "")
|
|
35
|
+
if _auth:
|
|
36
|
+
req.add_header("Authorization", _auth)
|
|
37
|
+
req.add_header("MCP-Protocol-Version", PROTO)
|
|
38
|
+
if session:
|
|
39
|
+
req.add_header("Mcp-Session-Id", session)
|
|
40
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
41
|
+
raw = resp.read().decode("utf-8", "replace")
|
|
42
|
+
sid = resp.headers.get("Mcp-Session-Id") or session
|
|
43
|
+
return raw, sid
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse(raw: str) -> dict | None:
|
|
47
|
+
"""SSE 里取最后一条 data: 的 JSON;纯 JSON 响应直接解析。"""
|
|
48
|
+
text = raw.strip()
|
|
49
|
+
if text.startswith("{"):
|
|
50
|
+
try:
|
|
51
|
+
return json.loads(text)
|
|
52
|
+
except json.JSONDecodeError:
|
|
53
|
+
return None
|
|
54
|
+
payloads = []
|
|
55
|
+
for line in text.splitlines():
|
|
56
|
+
if line.startswith("data:"):
|
|
57
|
+
chunk = line[5:].strip()
|
|
58
|
+
if chunk:
|
|
59
|
+
payloads.append(chunk)
|
|
60
|
+
for chunk in reversed(payloads):
|
|
61
|
+
try:
|
|
62
|
+
return json.loads(chunk)
|
|
63
|
+
except json.JSONDecodeError:
|
|
64
|
+
continue
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def main() -> int:
|
|
69
|
+
if len(sys.argv) < 4:
|
|
70
|
+
print("MCP_ERROR: 用法 mcp_call.py <endpoint> <tool> '<json-args>'")
|
|
71
|
+
return 1
|
|
72
|
+
endpoint, tool, args_raw = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
73
|
+
try:
|
|
74
|
+
args = json.loads(args_raw)
|
|
75
|
+
except json.JSONDecodeError as e:
|
|
76
|
+
print(f"MCP_ERROR: 参数不是合法 JSON({e})")
|
|
77
|
+
return 1
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
raw, sid = _post(
|
|
81
|
+
endpoint,
|
|
82
|
+
{
|
|
83
|
+
"jsonrpc": "2.0",
|
|
84
|
+
"id": 1,
|
|
85
|
+
"method": "initialize",
|
|
86
|
+
"params": {
|
|
87
|
+
"protocolVersion": PROTO,
|
|
88
|
+
"capabilities": {},
|
|
89
|
+
"clientInfo": {"name": "d-reach", "version": "1.0"},
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
None,
|
|
93
|
+
)
|
|
94
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
95
|
+
print(f"MCP_ERROR: initialize 失败({e})")
|
|
96
|
+
return 1
|
|
97
|
+
if not (_parse(raw) or {}).get("result"):
|
|
98
|
+
print(f"MCP_ERROR: initialize 无 result({raw[:160]})")
|
|
99
|
+
return 1
|
|
100
|
+
|
|
101
|
+
# notifications/initialized 是单向通知,服务端可能回 202 空体,失败也无所谓
|
|
102
|
+
try:
|
|
103
|
+
_post(endpoint, {"jsonrpc": "2.0", "method": "notifications/initialized"}, sid)
|
|
104
|
+
except (urllib.error.URLError, TimeoutError, OSError):
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
raw, _ = _post(
|
|
109
|
+
endpoint,
|
|
110
|
+
{
|
|
111
|
+
"jsonrpc": "2.0",
|
|
112
|
+
"id": 2,
|
|
113
|
+
"method": "tools/call",
|
|
114
|
+
"params": {"name": tool, "arguments": args},
|
|
115
|
+
},
|
|
116
|
+
sid,
|
|
117
|
+
)
|
|
118
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
119
|
+
print(f"MCP_ERROR: tools/call 失败({e})")
|
|
120
|
+
return 1
|
|
121
|
+
|
|
122
|
+
msg = _parse(raw) or {}
|
|
123
|
+
if "error" in msg:
|
|
124
|
+
err = msg["error"]
|
|
125
|
+
print(f"MCP_ERROR: {err.get('message', err) if isinstance(err, dict) else err}")
|
|
126
|
+
return 1
|
|
127
|
+
content = (msg.get("result") or {}).get("content") or []
|
|
128
|
+
for block in content:
|
|
129
|
+
if block.get("type") == "text" and block.get("text"):
|
|
130
|
+
print(block["text"])
|
|
131
|
+
return 0
|
|
132
|
+
print(f"MCP_ERROR: 返回里没有 text 块({raw[:160]})")
|
|
133
|
+
return 1
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
if __name__ == "__main__":
|
|
137
|
+
sys.exit(main())
|
package/scripts/quota.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""D-Reach 免费额度计数器 + 裕度线(默认保留 30%)。
|
|
3
|
+
|
|
4
|
+
只管两件事:记数、判断有没有越过"裕度线/免费线"。选路与执行由 agent 按 SKILL.md 直接调。
|
|
5
|
+
|
|
6
|
+
quota.py status 看所有通道原始计数
|
|
7
|
+
quota.py budget 规划本轮调研:到裕度线还剩多少、今日建议额度
|
|
8
|
+
quota.py use <svc> [n] 记一次占用(fanout 在请求成功后才调)。exit 0/2/1
|
|
9
|
+
quota.py check <svc> [n] 只看不占,退出码同 use
|
|
10
|
+
quota.py reset [svc] 清零
|
|
11
|
+
|
|
12
|
+
环境变量:
|
|
13
|
+
D_REACH_RESERVE 裕度比例,默认 0.30(即用到 70% 就提示转免费通道)
|
|
14
|
+
D_REACH_QUOTA_FILE 计数文件路径(默认 ~/.agent-reach/quota.json;仅测试时覆盖)
|
|
15
|
+
|
|
16
|
+
百度千帆不在此记账 —— 由 baiduaisearchwithquota 自己的计数器负责。
|
|
17
|
+
Firecrawl Research Index(论文端点)官方明确免费,本技能也不记账。
|
|
18
|
+
免 Key 不限量通道(Firecrawl Dev Index / TinyFish / StackExchange / HN / OpenAlex / Crossref / 掘金 / gh …)不记账。
|
|
19
|
+
"""
|
|
20
|
+
import contextlib
|
|
21
|
+
import fcntl
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import sys
|
|
25
|
+
from datetime import datetime, timezone
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
FILE = Path(os.environ.get("D_REACH_QUOTA_FILE")
|
|
29
|
+
or Path.home() / ".agent-reach/quota.json")
|
|
30
|
+
try:
|
|
31
|
+
RESERVE = float(os.environ.get("D_REACH_RESERVE", "0.30"))
|
|
32
|
+
except ValueError:
|
|
33
|
+
RESERVE = 0.30
|
|
34
|
+
RESERVE = min(max(RESERVE, 0.0), 0.9)
|
|
35
|
+
|
|
36
|
+
# 服务: (月上限, 日上限);None = 该项不限
|
|
37
|
+
# 数字口径:2026-10-26 重新对官方定价页核实,改数字先回头对一次账。
|
|
38
|
+
LIMITS = {
|
|
39
|
+
"brightdata": (5000, None), # MCP/Unlocker Free Tier: 5,000 requests/月(官方 pricing/mcp-server)
|
|
40
|
+
"exa": (2500, 50), # 免费余额 $10/月,约合 2,500 次 Lite search(官方 pricing,每月 1 号重置)
|
|
41
|
+
"firecrawl": (1000, 200), # Free plan: 1,000 credits/月,每月重置、不结转(官方 pricing);论文端点免费不计这里
|
|
42
|
+
"serper": (2500, None), # Serper:2,500 次一次性赠送(**不是每月重置**),之后 $1/1000
|
|
43
|
+
"brave": (1000, None), # Brave:每月 $5 免费 credits,$5/1,000 requests = 1,000 次/月;用完 429 自动停
|
|
44
|
+
"langsearch": (None, 50), # 官方只给“daily token 额度”(00:00 UTC 重置、起始 5 RPS),无明确请求数;50=本技能自设保守线
|
|
45
|
+
"jina_reader": (None, 300), # 免 key 约 20 RPM(按 IP 限速),有 key 提到约 200 RPM;300/日 = 自设保守线
|
|
46
|
+
# browser_use 已移除:本机没有这个工具(pi 未注册、CLI 不存在),记了也是假账
|
|
47
|
+
"xhs": (None, 200), # 登录态免费,防风控
|
|
48
|
+
"bili": (None, 200),
|
|
49
|
+
"youcom": (None, 100), # You.com 官方 Search API 免费档 100 次/天(2026-12-04 核实)
|
|
50
|
+
"twitter": (None, 100),
|
|
51
|
+
}
|
|
52
|
+
# 不限量、不记账的免 Key 通道(写在这里只为 budget 里提醒,别去 use 它们)
|
|
53
|
+
# 2026-10-26 校正:剔除已投毒的 cn.bing、搜索已退役的 V2EX、已退役的博客园,
|
|
54
|
+
# 补上一直在用却没列进来的 Firecrawl Developer Index 与 TinyFish($0/次)。
|
|
55
|
+
FREE_CHANNELS = ("Firecrawl Developer Index", "TinyFish search/fetch", "StackExchange",
|
|
56
|
+
"HN Algolia", "OpenAlex", "Crossref", "掘金", "SegmentFault",
|
|
57
|
+
"36氪/InfoQ/澎湃/界面", "豆瓣", "gh CLI", "DeepWiki")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _soft(limit):
|
|
61
|
+
"""裕度线:留 RESERVE 比例。"""
|
|
62
|
+
if limit is None:
|
|
63
|
+
return None
|
|
64
|
+
return int(limit * (1 - RESERVE))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _load():
|
|
68
|
+
try:
|
|
69
|
+
d = json.loads(FILE.read_text())
|
|
70
|
+
except Exception:
|
|
71
|
+
return {}
|
|
72
|
+
if not isinstance(d, dict):
|
|
73
|
+
return {}
|
|
74
|
+
d.pop("buckets", None) # 旧版 quota_manager 的 schema,一次性丢弃
|
|
75
|
+
return d
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _save(d):
|
|
79
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
FILE.write_text(json.dumps(d, indent=2))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@contextlib.contextmanager
|
|
84
|
+
def _locked():
|
|
85
|
+
"""跨进程互斥:fanout.sh 会并行调多路 use,无锁会丢失更新。
|
|
86
|
+
|
|
87
|
+
ponytail: 一把全局锁串行化所有服务;单机低频完全够用。
|
|
88
|
+
并发量真上去(>50 进程/秒)再换 per-service 锁。
|
|
89
|
+
"""
|
|
90
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
lock_path = FILE.with_suffix(FILE.suffix + ".lock")
|
|
92
|
+
with open(lock_path, "a+") as fh:
|
|
93
|
+
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
94
|
+
try:
|
|
95
|
+
yield
|
|
96
|
+
finally:
|
|
97
|
+
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _bucket(d, svc):
|
|
101
|
+
"""跨月/跨日自动归零。"""
|
|
102
|
+
now = datetime.now(timezone.utc)
|
|
103
|
+
b = d.get(svc)
|
|
104
|
+
if not isinstance(b, dict):
|
|
105
|
+
b = {"month": now.strftime("%Y-%m"), "day": now.strftime("%Y-%m-%d"),
|
|
106
|
+
"monthly": 0, "daily": 0}
|
|
107
|
+
d[svc] = b
|
|
108
|
+
if b["month"] != now.strftime("%Y-%m"):
|
|
109
|
+
b["monthly"], b["month"] = 0, now.strftime("%Y-%m")
|
|
110
|
+
if b["day"] != now.strftime("%Y-%m-%d"):
|
|
111
|
+
b["daily"], b["day"] = 0, now.strftime("%Y-%m-%d")
|
|
112
|
+
return b
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _try(d, svc, n, consume):
|
|
116
|
+
"""返回 (code, 说明)。code: 0 正常 / 2 已过裕度线 / 1 越免费线。"""
|
|
117
|
+
if svc not in LIMITS:
|
|
118
|
+
return 0, f"{svc}: 无限额(免 Key/本地 CLI),不记账"
|
|
119
|
+
mo, day = LIMITS[svc]
|
|
120
|
+
b = _bucket(d, svc)
|
|
121
|
+
over = []
|
|
122
|
+
if mo and b["monthly"] + n > mo:
|
|
123
|
+
over.append(f"月 {b['monthly']}+{n}/{mo}")
|
|
124
|
+
if day and b["daily"] + n > day:
|
|
125
|
+
over.append(f"日 {b['daily']}+{n}/{day}")
|
|
126
|
+
if over:
|
|
127
|
+
return 1, (f"{svc} 越免费线({';'.join(over)})→ 不记账,立刻换备选/免费通道")
|
|
128
|
+
|
|
129
|
+
near = []
|
|
130
|
+
if mo and b["monthly"] + n > _soft(mo):
|
|
131
|
+
near.append(f"月 {b['monthly']}+{n}>{_soft(mo)}/{mo}")
|
|
132
|
+
if day and b["daily"] + n > _soft(day):
|
|
133
|
+
near.append(f"日 {b['daily']}+{n}>{_soft(day)}/{day}")
|
|
134
|
+
code = 2 if near else 0
|
|
135
|
+
if consume:
|
|
136
|
+
b["monthly"] += n
|
|
137
|
+
b["daily"] += n
|
|
138
|
+
_save(d)
|
|
139
|
+
state = "已过裕度线" if code == 2 else "ok"
|
|
140
|
+
hint = "(仍记账;此后只用在免费通道拿不到的内容上)" if code == 2 else ""
|
|
141
|
+
detail = f"{svc} {state}{hint} [月 {b['monthly']}/{mo or '不限'}"
|
|
142
|
+
if mo:
|
|
143
|
+
detail += f"(裕度线 {_soft(mo)})"
|
|
144
|
+
detail += f", 日 {b['daily']}/{day or '不限'}"
|
|
145
|
+
if day:
|
|
146
|
+
detail += f"(裕度线 {_soft(day)})"
|
|
147
|
+
detail += "]"
|
|
148
|
+
if near:
|
|
149
|
+
detail += " 触发:" + ";".join(near)
|
|
150
|
+
return code, detail
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _status(d):
|
|
154
|
+
out = {}
|
|
155
|
+
for svc, (mo, day) in LIMITS.items():
|
|
156
|
+
b = _bucket(d, svc)
|
|
157
|
+
out[svc] = {"monthly": f"{b['monthly']}/{mo if mo else '不限'}",
|
|
158
|
+
"daily": f"{b['daily']}/{day if day else '不限'}"}
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def price_str(svc):
|
|
163
|
+
"""单价按「美分」显示更直观:0.005 → 0.5 美分。"""
|
|
164
|
+
return f"{UNIT_PRICE_USD[svc] * 100:g} 美分"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# 按次计费的通道:单价(美元/次)。只有这些会在 budget 里折算成钱。
|
|
168
|
+
UNIT_PRICE_USD = {
|
|
169
|
+
"youcom": 0.005, # Web Search Standard $5/1K CALLS(官方 pricing,2026-12-04 核实)
|
|
170
|
+
}
|
|
171
|
+
# 月度花费警戒线(美元)。越过就提醒,不阻断。
|
|
172
|
+
SPEND_WARN_USD = 20.0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _budget(d):
|
|
176
|
+
"""给 agent 看的规划视图:到裕度线还剩多少,以及今日可用建议。"""
|
|
177
|
+
now = datetime.now(timezone.utc)
|
|
178
|
+
days_in_month = 28 if now.month == 2 else 30 if now.month in (4, 6, 9, 11) else 31
|
|
179
|
+
days_left = max(days_in_month - now.day + 1, 1)
|
|
180
|
+
lines, advice = [], []
|
|
181
|
+
lines.append(f"裕度:保留 {RESERVE:.0%}(裕度线 = 上限的 {1 - RESERVE:.0%});"
|
|
182
|
+
f"本月剩 {days_left} 天")
|
|
183
|
+
lines.append(f"{'通道':13s}{'月 已用/裕度线/上限':>26s}{'日 已用/裕度线':>18s} 状态")
|
|
184
|
+
for svc, (mo, day) in LIMITS.items():
|
|
185
|
+
b = _bucket(d, svc)
|
|
186
|
+
sm, sd = _soft(mo), _soft(day)
|
|
187
|
+
sta = "充裕"
|
|
188
|
+
if (mo and b["monthly"] >= _soft(mo)) or (day and b["daily"] >= _soft(day)):
|
|
189
|
+
sta = "已过裕度线"
|
|
190
|
+
if (mo and b["monthly"] >= mo) or (day and b["daily"] >= day):
|
|
191
|
+
sta = "越免费线"
|
|
192
|
+
m_col = f"{b['monthly']}/{sm if sm else '-'}/{mo if mo else '-'}" if mo else "—"
|
|
193
|
+
d_col = (f"{b['daily']}/{sd if sd else '-'}" if day
|
|
194
|
+
else (f"{b['daily']}/—" if b["daily"] else "—"))
|
|
195
|
+
lines.append(f"{svc:13s}{m_col:>26s}{d_col:>18s} {sta}")
|
|
196
|
+
if mo:
|
|
197
|
+
room_m = max(sm - b["monthly"], 0)
|
|
198
|
+
advice.append(f"{svc} 月余量到裕度线 {room_m} 次(≈{room_m // days_left}/日)")
|
|
199
|
+
elif day:
|
|
200
|
+
advice.append(f"{svc} 日余量到裕度线 {max(sd - b['daily'], 0)} 次")
|
|
201
|
+
out = "\n".join(lines)
|
|
202
|
+
# 按次计费的通道折算成美元:次数 × 单价,越过警戒线就点名
|
|
203
|
+
spend = []
|
|
204
|
+
for svc, price in UNIT_PRICE_USD.items():
|
|
205
|
+
n = _bucket(d, svc)["monthly"]
|
|
206
|
+
usd = n * price
|
|
207
|
+
spend.append((svc, n, usd))
|
|
208
|
+
if spend:
|
|
209
|
+
lines2 = ["\n按次计费的通道($/次 × 本月次数):"]
|
|
210
|
+
for svc, n, usd in spend:
|
|
211
|
+
warn = " ⚠️ 已过月度警戒线" if usd >= SPEND_WARN_USD else ""
|
|
212
|
+
lines2.append(f" {svc}: {n} 次 × {price_str(svc)} = ${usd:.2f}"
|
|
213
|
+
f"(警戒线 ${SPEND_WARN_USD:.0f}/月){warn}")
|
|
214
|
+
out = "\n".join(lines) + "\n" + "\n".join(lines2)
|
|
215
|
+
out += "\n\n今日可用(到裕度线):" + ";".join(advice)
|
|
216
|
+
out += ("\n免 Key 不限量通道(不记账,深挖优先铺满):" + " / ".join(FREE_CHANNELS))
|
|
217
|
+
off = d.get("_official") or {}
|
|
218
|
+
if off:
|
|
219
|
+
out += "\n官方额度校准(最近一次 quota_probe):"
|
|
220
|
+
for name, v in off.items():
|
|
221
|
+
st = v.get("state")
|
|
222
|
+
if st == "ok" and name == "firecrawl":
|
|
223
|
+
out += (f"\n {name}: 剩余 {v.get('remaining')}/{v.get('total')} credits"
|
|
224
|
+
f",账期至 {str(v.get('period_end'))[:10]}")
|
|
225
|
+
elif st == "ok" and name == "tinyfish":
|
|
226
|
+
out += f"\n {name}: 钱包 {v.get('balance')} {v.get('currency')}"
|
|
227
|
+
elif st == "ok":
|
|
228
|
+
out += f"\n {name}: ok"
|
|
229
|
+
elif st == "no_permission":
|
|
230
|
+
out += f"\n {name}: 权限不足"
|
|
231
|
+
elif st == "unavailable":
|
|
232
|
+
out += f"\n {name}: 无公开接口"
|
|
233
|
+
elif st == "no_key":
|
|
234
|
+
continue
|
|
235
|
+
else:
|
|
236
|
+
out += f"\n {name}: {v.get('error')}"
|
|
237
|
+
out += "\n (本地计数 = 我们发过几次;官方数字 = 厂商真实剩余,差异大说明漏记)"
|
|
238
|
+
else:
|
|
239
|
+
out += "\n官方额度:尚未校准,跑 `python3 scripts/quota_probe.py`(fanout 结束会自动跑一次)"
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def main(argv):
|
|
244
|
+
cmd = argv[1] if len(argv) > 1 else "status"
|
|
245
|
+
with _locked():
|
|
246
|
+
d = _load()
|
|
247
|
+
if cmd == "status":
|
|
248
|
+
print(json.dumps(_status(d), indent=2, ensure_ascii=False))
|
|
249
|
+
return 0
|
|
250
|
+
if cmd == "budget":
|
|
251
|
+
print(_budget(d))
|
|
252
|
+
return 0
|
|
253
|
+
if cmd in ("use", "check"):
|
|
254
|
+
svc = argv[2] if len(argv) > 2 else ""
|
|
255
|
+
if not svc:
|
|
256
|
+
print("usage: quota.py use|check <service> [count]")
|
|
257
|
+
return 2
|
|
258
|
+
try:
|
|
259
|
+
n = int(argv[3]) if len(argv) > 3 else 1
|
|
260
|
+
except ValueError:
|
|
261
|
+
print(f"count 必须是整数:{argv[3]!r}")
|
|
262
|
+
return 2
|
|
263
|
+
code, msg = _try(d, svc, n, cmd == "use")
|
|
264
|
+
print(msg)
|
|
265
|
+
return code
|
|
266
|
+
if cmd == "reset":
|
|
267
|
+
svc = argv[2] if len(argv) > 2 else None
|
|
268
|
+
if svc:
|
|
269
|
+
d.pop(svc, None)
|
|
270
|
+
else:
|
|
271
|
+
for k in LIMITS:
|
|
272
|
+
d.pop(k, None)
|
|
273
|
+
_save(d)
|
|
274
|
+
print(f"reset {svc if svc else 'all'}")
|
|
275
|
+
return 0
|
|
276
|
+
print(f"unknown command: {cmd}")
|
|
277
|
+
return 2
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
if __name__ == "__main__":
|
|
281
|
+
sys.exit(main(sys.argv))
|