@duanz/pi-d-reach 1.0.1 → 1.0.3
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/SKILL.md +7 -5
- package/package.json +1 -1
- package/plugin/index.ts +636 -403
- package/plugin/pwa.ts +142 -25
- package/plugin/runtime.ts +771 -0
- package/plugin/scripts/fanout.sh +290 -140
- package/plugin/scripts/mcp_call.py +39 -3
- package/plugin/scripts/quota.py +44 -11
- package/plugin/scripts/quota_probe.py +31 -8
- package/plugin/scripts/render.mjs +164 -5
- package/references/channels.md +6 -5
- package/scripts/fanout.sh +290 -140
- package/scripts/mcp_call.py +39 -3
- package/scripts/quota.py +44 -11
- package/scripts/quota_probe.py +31 -8
package/scripts/mcp_call.py
CHANGED
|
@@ -15,6 +15,7 @@ Parallel 的免费档三个工具都是「问一次答一次」,用不上那
|
|
|
15
15
|
import json
|
|
16
16
|
import os
|
|
17
17
|
import sys
|
|
18
|
+
import time
|
|
18
19
|
import urllib.error
|
|
19
20
|
import urllib.request
|
|
20
21
|
|
|
@@ -22,7 +23,20 @@ PROTO = "2024-11-05"
|
|
|
22
23
|
TIMEOUT = 40
|
|
23
24
|
|
|
24
25
|
|
|
25
|
-
def
|
|
26
|
+
def _budget_secs() -> float:
|
|
27
|
+
raw = os.environ.get("D_REACH_MCP_BUDGET", "").strip()
|
|
28
|
+
if not raw:
|
|
29
|
+
return 45.0
|
|
30
|
+
try:
|
|
31
|
+
val = float(raw)
|
|
32
|
+
return val if val > 0 else 45.0
|
|
33
|
+
except ValueError:
|
|
34
|
+
return 45.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _post(
|
|
38
|
+
endpoint: str, body: dict, session: str | None, timeout: float = TIMEOUT
|
|
39
|
+
) -> tuple[str, str | None]:
|
|
26
40
|
data = json.dumps(body).encode()
|
|
27
41
|
req = urllib.request.Request(endpoint, data=data, method="POST")
|
|
28
42
|
req.add_header("Content-Type", "application/json")
|
|
@@ -37,7 +51,7 @@ def _post(endpoint: str, body: dict, session: str | None) -> tuple[str, str | No
|
|
|
37
51
|
req.add_header("MCP-Protocol-Version", PROTO)
|
|
38
52
|
if session:
|
|
39
53
|
req.add_header("Mcp-Session-Id", session)
|
|
40
|
-
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
54
|
+
with urllib.request.urlopen(req, timeout=max(0.05, min(TIMEOUT, timeout))) as resp:
|
|
41
55
|
raw = resp.read().decode("utf-8", "replace")
|
|
42
56
|
sid = resp.headers.get("Mcp-Session-Id") or session
|
|
43
57
|
return raw, sid
|
|
@@ -76,6 +90,13 @@ def main() -> int:
|
|
|
76
90
|
print(f"MCP_ERROR: 参数不是合法 JSON({e})")
|
|
77
91
|
return 1
|
|
78
92
|
|
|
93
|
+
budget = _budget_secs()
|
|
94
|
+
deadline = time.monotonic() + budget
|
|
95
|
+
|
|
96
|
+
rem = deadline - time.monotonic()
|
|
97
|
+
if rem <= 0:
|
|
98
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
99
|
+
return 1
|
|
79
100
|
try:
|
|
80
101
|
raw, sid = _post(
|
|
81
102
|
endpoint,
|
|
@@ -90,6 +111,7 @@ def main() -> int:
|
|
|
90
111
|
},
|
|
91
112
|
},
|
|
92
113
|
None,
|
|
114
|
+
timeout=min(TIMEOUT, rem),
|
|
93
115
|
)
|
|
94
116
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
95
117
|
print(f"MCP_ERROR: initialize 失败({e})")
|
|
@@ -99,11 +121,24 @@ def main() -> int:
|
|
|
99
121
|
return 1
|
|
100
122
|
|
|
101
123
|
# notifications/initialized 是单向通知,服务端可能回 202 空体,失败也无所谓
|
|
124
|
+
rem = deadline - time.monotonic()
|
|
125
|
+
if rem <= 0:
|
|
126
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
127
|
+
return 1
|
|
102
128
|
try:
|
|
103
|
-
_post(
|
|
129
|
+
_post(
|
|
130
|
+
endpoint,
|
|
131
|
+
{"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
132
|
+
sid,
|
|
133
|
+
timeout=min(TIMEOUT, rem),
|
|
134
|
+
)
|
|
104
135
|
except (urllib.error.URLError, TimeoutError, OSError):
|
|
105
136
|
pass
|
|
106
137
|
|
|
138
|
+
rem = deadline - time.monotonic()
|
|
139
|
+
if rem <= 0:
|
|
140
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
141
|
+
return 1
|
|
107
142
|
try:
|
|
108
143
|
raw, _ = _post(
|
|
109
144
|
endpoint,
|
|
@@ -114,6 +149,7 @@ def main() -> int:
|
|
|
114
149
|
"params": {"name": tool, "arguments": args},
|
|
115
150
|
},
|
|
116
151
|
sid,
|
|
152
|
+
timeout=min(TIMEOUT, rem),
|
|
117
153
|
)
|
|
118
154
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
119
155
|
print(f"MCP_ERROR: tools/call 失败({e})")
|
package/scripts/quota.py
CHANGED
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
Firecrawl Research Index(论文端点)官方明确免费,本技能也不记账。
|
|
18
18
|
免 Key 不限量通道(Firecrawl Dev Index / TinyFish / StackExchange / HN / OpenAlex / Crossref / 掘金 / gh …)不记账。
|
|
19
19
|
"""
|
|
20
|
+
import calendar
|
|
20
21
|
import contextlib
|
|
21
22
|
import fcntl
|
|
22
23
|
import json
|
|
23
24
|
import os
|
|
24
25
|
import sys
|
|
26
|
+
import threading
|
|
25
27
|
from datetime import datetime, timezone
|
|
26
28
|
from pathlib import Path
|
|
27
29
|
|
|
@@ -75,9 +77,28 @@ def _load():
|
|
|
75
77
|
return d
|
|
76
78
|
|
|
77
79
|
|
|
80
|
+
def _reset_stale_buckets(d, now=None):
|
|
81
|
+
"""写回前归零已跨月/跨日的旧服务桶,避免过时计数滞留磁盘。"""
|
|
82
|
+
now = now or datetime.now(timezone.utc)
|
|
83
|
+
cur_month = now.strftime("%Y-%m")
|
|
84
|
+
cur_day = now.strftime("%Y-%m-%d")
|
|
85
|
+
for svc, b in list(d.items()):
|
|
86
|
+
if svc.startswith("_") or not isinstance(b, dict):
|
|
87
|
+
continue
|
|
88
|
+
if b.get("month") != cur_month or b.get("day") != cur_day:
|
|
89
|
+
_bucket(d, svc, now=now)
|
|
90
|
+
|
|
91
|
+
|
|
78
92
|
def _save(d):
|
|
93
|
+
_reset_stale_buckets(d)
|
|
79
94
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
-
FILE.
|
|
95
|
+
tmp = FILE.with_name(f"{FILE.name}.tmp.{os.getpid()}.{threading.get_ident()}")
|
|
96
|
+
try:
|
|
97
|
+
tmp.write_text(json.dumps(d, indent=2, ensure_ascii=False))
|
|
98
|
+
tmp.replace(FILE)
|
|
99
|
+
except Exception:
|
|
100
|
+
tmp.unlink(missing_ok=True)
|
|
101
|
+
raise
|
|
81
102
|
|
|
82
103
|
|
|
83
104
|
@contextlib.contextmanager
|
|
@@ -88,7 +109,7 @@ def _locked():
|
|
|
88
109
|
并发量真上去(>50 进程/秒)再换 per-service 锁。
|
|
89
110
|
"""
|
|
90
111
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
-
lock_path = FILE.
|
|
112
|
+
lock_path = FILE.with_name(FILE.name + ".lock")
|
|
92
113
|
with open(lock_path, "a+") as fh:
|
|
93
114
|
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
94
115
|
try:
|
|
@@ -97,18 +118,30 @@ def _locked():
|
|
|
97
118
|
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
98
119
|
|
|
99
120
|
|
|
100
|
-
def
|
|
121
|
+
def _nonneg_int(val):
|
|
122
|
+
try:
|
|
123
|
+
n = int(val)
|
|
124
|
+
return n if n >= 0 else 0
|
|
125
|
+
except (TypeError, ValueError):
|
|
126
|
+
return 0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _bucket(d, svc, now=None):
|
|
101
130
|
"""跨月/跨日自动归零。"""
|
|
102
|
-
now = datetime.now(timezone.utc)
|
|
131
|
+
now = now or datetime.now(timezone.utc)
|
|
132
|
+
cur_month = now.strftime("%Y-%m")
|
|
133
|
+
cur_day = now.strftime("%Y-%m-%d")
|
|
103
134
|
b = d.get(svc)
|
|
104
135
|
if not isinstance(b, dict):
|
|
105
|
-
b = {"month":
|
|
106
|
-
"monthly": 0, "daily": 0}
|
|
136
|
+
b = {"month": cur_month, "day": cur_day, "monthly": 0, "daily": 0}
|
|
107
137
|
d[svc] = b
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
138
|
+
return b
|
|
139
|
+
b["monthly"] = _nonneg_int(b.get("monthly"))
|
|
140
|
+
b["daily"] = _nonneg_int(b.get("daily"))
|
|
141
|
+
if b.get("month") != cur_month:
|
|
142
|
+
b["monthly"], b["month"] = 0, cur_month
|
|
143
|
+
if b.get("day") != cur_day:
|
|
144
|
+
b["daily"], b["day"] = 0, cur_day
|
|
112
145
|
return b
|
|
113
146
|
|
|
114
147
|
|
|
@@ -175,7 +208,7 @@ SPEND_WARN_USD = 20.0
|
|
|
175
208
|
def _budget(d):
|
|
176
209
|
"""给 agent 看的规划视图:到裕度线还剩多少,以及今日可用建议。"""
|
|
177
210
|
now = datetime.now(timezone.utc)
|
|
178
|
-
days_in_month =
|
|
211
|
+
days_in_month = calendar.monthrange(now.year, now.month)[1]
|
|
179
212
|
days_left = max(days_in_month - now.day + 1, 1)
|
|
180
213
|
lines, advice = [], []
|
|
181
214
|
lines.append(f"裕度:保留 {RESERVE:.0%}(裕度线 = 上限的 {1 - RESERVE:.0%});"
|
package/scripts/quota_probe.py
CHANGED
|
@@ -18,10 +18,13 @@
|
|
|
18
18
|
jina 只有 dashboard,无公开额度 API
|
|
19
19
|
langsearch 官方只给 token 日额度,无查询端点
|
|
20
20
|
"""
|
|
21
|
+
import contextlib
|
|
22
|
+
import fcntl
|
|
21
23
|
import json
|
|
22
24
|
import os
|
|
23
25
|
import re
|
|
24
26
|
import sys
|
|
27
|
+
import threading
|
|
25
28
|
import time
|
|
26
29
|
import urllib.request
|
|
27
30
|
from concurrent.futures import ThreadPoolExecutor
|
|
@@ -167,24 +170,43 @@ PROBES = {
|
|
|
167
170
|
}
|
|
168
171
|
|
|
169
172
|
|
|
173
|
+
@contextlib.contextmanager
|
|
174
|
+
def _locked():
|
|
175
|
+
"""与 quota.py 共用同一把锁,避免官方校准覆盖并发计数写入。"""
|
|
176
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
lock_path = FILE.with_name(FILE.name + ".lock")
|
|
178
|
+
with open(lock_path, "a+") as fh:
|
|
179
|
+
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
180
|
+
try:
|
|
181
|
+
yield
|
|
182
|
+
finally:
|
|
183
|
+
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
184
|
+
|
|
185
|
+
|
|
170
186
|
def load():
|
|
171
187
|
try:
|
|
172
|
-
|
|
188
|
+
d = json.loads(FILE.read_text())
|
|
189
|
+
return d if isinstance(d, dict) else {}
|
|
173
190
|
except Exception:
|
|
174
191
|
return {}
|
|
175
192
|
|
|
176
193
|
|
|
177
194
|
def save(d):
|
|
178
195
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
-
tmp = FILE.
|
|
180
|
-
|
|
181
|
-
|
|
196
|
+
tmp = FILE.with_name(f"{FILE.name}.tmp.{os.getpid()}.{threading.get_ident()}")
|
|
197
|
+
try:
|
|
198
|
+
tmp.write_text(json.dumps(d, indent=2))
|
|
199
|
+
tmp.replace(FILE)
|
|
200
|
+
except Exception:
|
|
201
|
+
tmp.unlink(missing_ok=True)
|
|
202
|
+
raise
|
|
182
203
|
|
|
183
204
|
|
|
184
205
|
def run(max_age=0):
|
|
185
206
|
"""max_age>0 时:如果上次校准已在 N 秒内,直接复用,不重复请求厂商接口。"""
|
|
186
207
|
if max_age:
|
|
187
|
-
|
|
208
|
+
with _locked():
|
|
209
|
+
old = (load().get("_official") or {})
|
|
188
210
|
stamps = [v.get("probed_at") for v in old.values() if v.get("state") == "ok"]
|
|
189
211
|
if stamps:
|
|
190
212
|
try:
|
|
@@ -204,9 +226,10 @@ def run(max_age=0):
|
|
|
204
226
|
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
205
227
|
for v in out.values():
|
|
206
228
|
v["probed_at"] = stamp
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
229
|
+
with _locked():
|
|
230
|
+
d = load()
|
|
231
|
+
d["_official"] = out
|
|
232
|
+
save(d)
|
|
210
233
|
return out
|
|
211
234
|
|
|
212
235
|
|