codebee 0.1.67 → 0.1.68

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +543 -532
  2. package/LICENSE +21 -21
  3. package/README.md +11 -7
  4. package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +88 -0
  5. package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +126 -0
  6. package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
  7. package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +210 -0
  8. package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
  9. package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
  10. package/app/.playwright-cli/run-detail-after.png +0 -0
  11. package/app/core/acceptance.py +100 -100
  12. package/app/core/aiflavor.py +197 -197
  13. package/app/core/artifacts.py +148 -148
  14. package/app/core/assets.py +110 -110
  15. package/app/core/attachments.py +623 -623
  16. package/app/core/automation.py +758 -758
  17. package/app/core/backup.py +470 -470
  18. package/app/core/beekeeper.py +183 -183
  19. package/app/core/board.py +209 -209
  20. package/app/core/bookmeta.py +930 -930
  21. package/app/core/bookmeta_catalog.py +180 -180
  22. package/app/core/branching.py +137 -137
  23. package/app/core/builtin_agent.py +1234 -1234
  24. package/app/core/capability.py +144 -144
  25. package/app/core/catalog.py +42 -0
  26. package/app/core/chaptersafe.py +32 -32
  27. package/app/core/cleanup.py +303 -303
  28. package/app/core/compaction.py +201 -201
  29. package/app/core/covergen.py +356 -356
  30. package/app/core/defectretro.py +43 -43
  31. package/app/core/diagnostics.py +114 -114
  32. package/app/core/dispatch.py +173 -173
  33. package/app/core/dispatch_log.py +128 -113
  34. package/app/core/env_scrub.py +85 -85
  35. package/app/core/error_codes.py +23 -23
  36. package/app/core/errorlog.py +137 -137
  37. package/app/core/evaluation.py +174 -174
  38. package/app/core/failure_notify.py +290 -290
  39. package/app/core/flows.py +2 -2
  40. package/app/core/goal_service.py +167 -167
  41. package/app/core/health.py +374 -374
  42. package/app/core/history.py +38 -38
  43. package/app/core/hooks.py +162 -162
  44. package/app/core/jobs.py +29 -25
  45. package/app/core/knowledge.py +7 -0
  46. package/app/core/manager.py +2122 -2122
  47. package/app/core/market.py +362 -362
  48. package/app/core/mocks.py +64 -64
  49. package/app/core/modelhub.py +22 -3
  50. package/app/core/notify.py +106 -106
  51. package/app/core/operations.py +228 -228
  52. package/app/core/paihang.py +138 -138
  53. package/app/core/paths.py +2 -2
  54. package/app/core/pipeline.py +16 -1
  55. package/app/core/planner.py +2 -0
  56. package/app/core/portguard.py +111 -111
  57. package/app/core/preview.py +293 -293
  58. package/app/core/publish/__init__.py +7 -7
  59. package/app/core/publish/auto.py +367 -367
  60. package/app/core/publish/browser.py +539 -539
  61. package/app/core/publish/fanqie.py +159 -159
  62. package/app/core/publish/flow.py +440 -440
  63. package/app/core/publish/flows-fanqie-calibrated.json +332 -332
  64. package/app/core/publish/flows-qimao-calibrated.json +7 -3
  65. package/app/core/publish/ledger.py +203 -203
  66. package/app/core/publish/manager.py +692 -692
  67. package/app/core/publish/qimao.py +141 -141
  68. package/app/core/publish/ws.py +139 -139
  69. package/app/core/redact.py +38 -38
  70. package/app/core/repeat_guard.py +129 -129
  71. package/app/core/router.py +398 -398
  72. package/app/core/runner.py +2067 -2065
  73. package/app/core/selfupdate.py +384 -384
  74. package/app/core/session_log.py +161 -161
  75. package/app/core/sessions.py +312 -312
  76. package/app/core/settings.py +149 -149
  77. package/app/core/settings_schema.py +262 -262
  78. package/app/core/share_page.py +114 -114
  79. package/app/core/skill_scan.py +122 -114
  80. package/app/core/skillpacks/fanqie-novel.md +80 -80
  81. package/app/core/skillpacks/market/character-bible.md +66 -66
  82. package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
  83. package/app/core/skillpacks/market/git-workflow.md +57 -57
  84. package/app/core/skillpacks/market/release-notes.md +72 -72
  85. package/app/core/skillpacks/market/weekly-report.md +71 -71
  86. package/app/core/skillpacks/market/worldview-consistency.md +70 -70
  87. package/app/core/skills.py +15 -1
  88. package/app/core/step_runner.py +132 -132
  89. package/app/core/store.py +75 -34
  90. package/app/core/task_compile.py +199 -199
  91. package/app/core/telemetry.py +292 -292
  92. package/app/core/tlsctx.py +64 -64
  93. package/app/core/token_meter.py +147 -147
  94. package/app/core/tracing.py +144 -0
  95. package/app/core/upstream.py +41 -41
  96. package/app/core/usage.py +862 -858
  97. package/app/core/volumes.py +389 -389
  98. package/app/core/wxdigest.py +858 -858
  99. package/app/core/zentao.py +2465 -2465
  100. package/app/main.py +2981 -2957
  101. package/app/pick_dialog.py +110 -110
  102. package/app/ui/app.js +14399 -14384
  103. package/app/ui/artdiff.js +74 -74
  104. package/app/ui/board.html +162 -162
  105. package/app/ui/board.js +305 -305
  106. package/app/ui/i18n.js +2770 -2766
  107. package/app/ui/icons/bee.svg +79 -79
  108. package/app/ui/manifest.json +16 -16
  109. package/app/ui/qrcode.js +2297 -2297
  110. package/app/ui/style.css +16 -16
  111. package/bin/tutti.js +147 -147
  112. package/package.json +46 -46
  113. package/tools/wx_reader.py +261 -261
@@ -1,374 +1,374 @@
1
- # -*- coding: utf-8 -*-
2
- """供应商健康监测与告警:连不上模型/厂商时自动降级并告警,恢复自动解除。
3
-
4
- 设计稿:docs/migration/07-token-cost.md 的延伸(2026-09-15 连载验收实战需求:
5
- cavoti 网关宕机 5 小时,系统只会反复失败重试,没有主动告知「通道已不可用」)。
6
-
7
- 状态机(按 provider):
8
- ok 正常(有近期成功或不活跃)
9
- failing 连续失败 ≥FAILING_AFTER(进入探测模式)
10
- down failing 持续 ≥DOWN_AFTER_SECONDS 或连续失败 ≥DOWN_AFTER_FAILURES
11
- → 触发告警(未静默时)
12
- recovered down/failing 后再次成功 → 自动解除告警,记一笔恢复
13
-
14
- 探针策略(省 token):正常时不主动探测(靠真实调用信号);failing/down 后按
15
- 退避(60s→120s→300s 封顶)发轻量探活(modelhub.chat,max_tokens=8)。
16
- 恢复 → 回正常节奏。
17
-
18
- 手动操作:
19
- silence(provider) 静默本次告警(不再提醒,直到恢复或手动 reset)
20
- reset(provider) 手动清除状态视为恢复(下次失败重新计数)
21
-
22
- 线程模型:上报(runner/pipeline/modelhub 多线程调用)走锁;探针单线程 daemon。
23
- """
24
- from __future__ import annotations
25
-
26
- import json
27
- import logging
28
- import threading
29
- import time
30
- from pathlib import Path
31
-
32
- log = logging.getLogger(__name__)
33
-
34
- FAILING_AFTER = 2 # 连续失败 ≥2 → failing(进入探测)
35
- DOWN_AFTER_FAILURES = 4 # 连续失败 ≥4 → down(告警)
36
- DOWN_AFTER_SECONDS = 600 # 或 failing 持续 10 分钟 → down
37
- PROBE_BACKOFF = (60, 120, 300) # 探测退避秒数(封顶 300)
38
- SILENCE_FOREVER = -1 # 手动静默不自动过期(恢复时才清除)
39
-
40
- _LOCK = threading.RLock()
41
- _PROVIDERS = {} # name -> 状态 dict
42
- _FILE = None # init() 注入(data/provider_health.json)
43
- _PROBE_THREAD = None
44
- _STARTED = False
45
-
46
-
47
- def init(data_dir=None, *, start_probe=True):
48
- """注入存储路径并从磁盘恢复状态(服务重启不丢告警上下文)。
49
-
50
- ``start_probe=False`` 供单元测试等受控场景使用,避免留下跨用例的
51
- daemon 探针线程。
52
- """
53
- global _FILE, _PROVIDERS, _STARTED, _PROBE_THREAD
54
- with _LOCK:
55
- base = Path(data_dir) if data_dir else Path(_default_dir())
56
- base.mkdir(parents=True, exist_ok=True)
57
- _FILE = base / "provider_health.json"
58
- _PROVIDERS = {}
59
- try:
60
- data = json.loads(_FILE.read_text(encoding="utf-8"))
61
- for name, st in (data.get("providers") or {}).items():
62
- if isinstance(st, dict) and st.get("name"):
63
- _PROVIDERS[name] = st
64
- except (OSError, json.JSONDecodeError):
65
- pass
66
- # 「绑定链·」静态告警胶囊已从产品移除(2026-09-18:普通用户误伤,
67
- # 用户拍板)——老版本持久化的条目启动即清,别让 0.1.6 的状态阴魂不散。
68
- stale = [k for k in _PROVIDERS if k.startswith("绑定链·")]
69
- if stale:
70
- for k in stale:
71
- _PROVIDERS.pop(k, None)
72
- _persist()
73
- # 供应商已删除的幽灵条目启动即清;运行期新增的幽灵由探针在探活时
74
- # 发现(gone 标记)随手清——探针循环里不做全量扫描,避免和测试
75
- # 夹具/运行期建条目赛跑。
76
- _prune_missing()
77
- if start_probe and not _STARTED:
78
- _STARTED = True
79
- _PROBE_THREAD = threading.Thread(
80
- target=_probe_loop, name="health-probe", daemon=True)
81
- _PROBE_THREAD.start()
82
-
83
-
84
- def _default_dir():
85
- from . import paths
86
- return str(paths.DATA_DIR)
87
-
88
-
89
- def _persist():
90
- # This is telemetry state: a storage failure must not turn a successful or
91
- # failed model call into a task failure. Callers already hold _LOCK, but
92
- # keeping the path and snapshot read under it also protects future callers.
93
- with _LOCK:
94
- path = _FILE
95
- if path is None:
96
- return
97
- try:
98
- path.parent.mkdir(parents=True, exist_ok=True)
99
- tmp = path.with_suffix(".tmp")
100
- tmp.write_text(
101
- json.dumps({"providers": _PROVIDERS}, ensure_ascii=False, indent=2),
102
- encoding="utf-8")
103
- tmp.replace(path)
104
- except OSError as e:
105
- log.warning("[health] 无法持久化供应商健康状态到 %s: %s", path, e)
106
-
107
-
108
- def _now():
109
- return time.time()
110
-
111
-
112
- def _fmt_ts(epoch):
113
- if not epoch:
114
- return ""
115
- return time.strftime("%m-%d %H:%M", time.localtime(epoch))
116
-
117
-
118
- # ---------------------------------------------------------------- 上报入口
119
-
120
- def report_success(provider: str):
121
- """一次真实成功调用(CLI 或 API 直连)。"""
122
- if not provider:
123
- return
124
- with _LOCK:
125
- st = _PROVIDERS.get(provider)
126
- if st is None:
127
- return # 没失败过就不建档(零开销)
128
- if st.get("status") in ("failing", "down"):
129
- st["status"] = "recovered"
130
- st["recovered_at"] = _now()
131
- st["consecutive_failures"] = 0
132
- st["last_ok_at"] = _now()
133
- st["probe_next_at"] = 0
134
- st["alerted"] = False
135
- st["silenced"] = False # 静默只管一次故障期;恢复后重新武装
136
- st["silence_until"] = 0
137
- log.info("[health] %s 已恢复(告警自动解除)", provider)
138
- else:
139
- st["last_ok_at"] = _now()
140
- st["consecutive_failures"] = 0
141
- _persist()
142
-
143
-
144
- def report_failure(provider: str, error: str = "", *, model: str = "",
145
- provider_id: str = ""):
146
- """一次真实失败调用。provider 用展示名(与 usage 台账一致)。"""
147
- if not provider:
148
- return
149
-
150
- # A failed live call invalidates capability evidence for this upstream.
151
- # Keep this hook lazy and best-effort: health telemetry must never make a
152
- # model call fail, and importing evaluation at module load would create a
153
- # dependency cycle during startup. ``provider_id`` is the canonical
154
- # identity used by the evaluation ledger; the display name is not safe to
155
- # use as a substitute because aliases can point at the same host.
156
- if provider_id:
157
- try:
158
- from . import evaluation
159
- evaluation.invalidate_provider(provider_id, model=model)
160
- except Exception:
161
- log.debug("[health] 无法使评测结论失效", exc_info=True)
162
- with _LOCK:
163
- st = _PROVIDERS.setdefault(provider, {
164
- "name": provider, "provider_id": provider_id or "",
165
- "model": model or "", "status": "ok",
166
- "consecutive_failures": 0, "first_fail_at": 0,
167
- "last_fail_at": 0, "last_ok_at": 0, "last_error": "",
168
- "alerted": False, "silenced": False, "silence_until": 0,
169
- "probe_next_at": 0, "probe_backoff_idx": 0,
170
- "recovered_at": 0,
171
- })
172
- st["name"] = provider
173
- if provider_id and not st.get("provider_id"):
174
- st["provider_id"] = provider_id
175
- if model and not st.get("model"):
176
- st["model"] = model
177
- n = int(st.get("consecutive_failures") or 0) + 1
178
- st["consecutive_failures"] = n
179
- st["last_fail_at"] = _now()
180
- st["last_error"] = str(error or "")[:300]
181
- if st.get("status") in ("ok", "recovered", ""):
182
- st["status"] = "failing"
183
- st["first_fail_at"] = _now()
184
- st["probe_next_at"] = _now() + PROBE_BACKOFF[0]
185
- st["probe_backoff_idx"] = 0
186
- # failing → down:连续次数或持续时间任一达到
187
- if st["status"] == "failing":
188
- dur = _now() - (st.get("first_fail_at") or _now())
189
- if n >= DOWN_AFTER_FAILURES or dur >= DOWN_AFTER_SECONDS:
190
- st["status"] = "down"
191
- if st["status"] == "down" and not st.get("silenced"):
192
- if not st.get("alerted"):
193
- st["alerted"] = True
194
- log.warning("[health] ⚠️ 供应商告警:%s 不可用(连续 %d 次失败,%s)",
195
- provider, n, st["last_error"][:120])
196
- _persist()
197
-
198
-
199
- # ------------------------------------------------- 静态死链告警(绑定层)
200
-
201
- # ---------------------------------------------------------------- 手动操作
202
-
203
- def silence(provider: str, minutes: int = 0):
204
- """手动静默告警(minutes=0 表示静默到恢复为止)。"""
205
- with _LOCK:
206
- st = _PROVIDERS.get(provider)
207
- if not st:
208
- return False, "未知的供应商"
209
- st["silenced"] = True
210
- st["silence_until"] = (_now() + minutes * 60) if minutes else SILENCE_FOREVER
211
- st["alerted"] = False
212
- _persist()
213
- return True, ""
214
-
215
-
216
- def reset(provider: str):
217
- """手动清除状态视为恢复(下次失败重新计数)。"""
218
- with _LOCK:
219
- st = _PROVIDERS.get(provider)
220
- if not st:
221
- return False, "未知的供应商"
222
- st.update({"status": "recovered", "consecutive_failures": 0,
223
- "alerted": False, "silenced": False, "silence_until": 0,
224
- "probe_next_at": 0, "recovered_at": _now()})
225
- _persist()
226
- return True, ""
227
-
228
-
229
- # ---------------------------------------------------------------- 查询
230
-
231
- def _effective_silenced(st):
232
- """静默是否仍有效(永久静默或未到过期时间)。"""
233
- if not st.get("silenced"):
234
- return False
235
- until = st.get("silence_until") or 0
236
- return until == SILENCE_FOREVER or until > _now()
237
-
238
-
239
- def snapshot():
240
- """给 API/SSE 的完整视图。"""
241
- with _LOCK:
242
- out = []
243
- for name, st in _PROVIDERS.items():
244
- silenced = _effective_silenced(st)
245
- alerting = st.get("status") == "down" and not silenced
246
- out.append({
247
- "provider": name,
248
- "provider_id": st.get("provider_id") or "",
249
- "model": st.get("model") or "",
250
- "status": st.get("status") or "ok",
251
- "consecutive_failures": st.get("consecutive_failures") or 0,
252
- "first_fail_at": _fmt_ts(st.get("first_fail_at")),
253
- "last_fail_at": _fmt_ts(st.get("last_fail_at")),
254
- "last_ok_at": _fmt_ts(st.get("last_ok_at")),
255
- "recovered_at": _fmt_ts(st.get("recovered_at")),
256
- "last_error": st.get("last_error") or "",
257
- "alerting": alerting,
258
- "silenced": silenced,
259
- "static": bool(st.get("static")),
260
- })
261
- # 稳定排序:告警中 > 故障中 > 恢复 > 正常
262
- rank = {"down": 0, "failing": 1, "recovered": 2, "ok": 3}
263
- out.sort(key=lambda x: (rank.get(x["status"], 9), x["provider"]))
264
- return {
265
- "providers": out,
266
- "alerts": [p for p in out if p["alerting"]],
267
- "any_alerting": any(p["alerting"] for p in out),
268
- }
269
-
270
-
271
- def is_down(provider: str) -> bool:
272
- """链降级查询:该供应商当前是否 down(供 resolve_binding 跳过)。"""
273
- with _LOCK:
274
- st = _PROVIDERS.get(provider)
275
- return bool(st and st.get("status") == "down")
276
-
277
-
278
- def down_names() -> set:
279
- with _LOCK:
280
- return {n for n, st in _PROVIDERS.items() if st.get("status") == "down"}
281
-
282
-
283
- # ---------------------------------------------------------------- 探针
284
-
285
- def _probe_one(st):
286
- """对单个故障 provider 发轻量探活。返回 (ok, gone):
287
- ok=是否恢复;gone=供应商已从配置里删除(健康记录应随之清掉)。"""
288
- try:
289
- from . import modelhub
290
- pid = st.get("provider_id") or ""
291
- model = st.get("model") or ""
292
- plist = modelhub.providers()
293
- provs = {p.get("name"): p for p in plist}
294
- prov = provs.get(st.get("name")) or next(
295
- (p for p in plist if pid and p.get("id") == pid), None)
296
- if not prov:
297
- return False, True # 供应商已删除:探不了也不再是「没恢复」
298
- if not prov.get("api_key"):
299
- return False, False # 供应商在但没密钥:无法探测,保持状态
300
- if not model:
301
- try:
302
- names = modelhub._enabled_models(prov)
303
- model = names[0]["name"] if names else ""
304
- except Exception:
305
- model = ""
306
- if not model:
307
- return False, False
308
- res = modelhub.chat(prov["id"], model, "1", max_tokens=8, timeout=20)
309
- return bool(res.get("ok")), False
310
- except Exception as e:
311
- log.debug("probe %s error: %s", st.get("name"), e)
312
- return False, False
313
-
314
-
315
- def _prune_missing():
316
- """供应商被删除后清掉它的健康记录。
317
-
318
- 幽灵条目探不活也永远不会恢复,还会每轮把 last_fail_at 刷成「刚刚」,
319
- 健康页看起来像它一直在报错(Z.ai 删掉后仍显示 429 的误伤案,2026-09-18)。
320
- """
321
- try:
322
- from . import modelhub
323
- plist = modelhub.providers()
324
- except Exception:
325
- return
326
- ids = {p.get("id") for p in plist}
327
- names = {p.get("name") for p in plist}
328
- with _LOCK:
329
- stale = [n for n, st in _PROVIDERS.items()
330
- if not ((st.get("provider_id") and st.get("provider_id") in ids)
331
- or st.get("name") in names)]
332
- if stale:
333
- for n in stale:
334
- _PROVIDERS.pop(n, None)
335
- _persist()
336
- log.info("[health] 清除已删除供应商的健康记录:%s", ", ".join(stale))
337
-
338
-
339
- def _record_probe_result(name, st, ok, gone):
340
- """只应用仍属于当前状态表的探针结果,忽略跨 init/测试的过期结果。"""
341
- with _LOCK:
342
- if _PROVIDERS.get(name) is not st:
343
- return
344
- if gone:
345
- _PROVIDERS.pop(name, None)
346
- _persist()
347
- log.info("[health] %s 已删除,健康记录随之清除", name)
348
- elif ok:
349
- report_success(name)
350
- log.info("[health] 探针确认 %s 已恢复", name)
351
- else:
352
- st["last_fail_at"] = _now()
353
- _persist()
354
-
355
-
356
- def _probe_loop():
357
- while True:
358
- try:
359
- with _LOCK:
360
- targets = [(name, st) for name, st in _PROVIDERS.items()
361
- if not st.get("static") # 静态死链无端点可探,绑定恢复时自动解除
362
- and st.get("status") in ("failing", "down")
363
- and (st.get("probe_next_at") or 0) <= _now()]
364
- for name, st in targets:
365
- idx = int(st.get("probe_backoff_idx") or 0)
366
- backoff = PROBE_BACKOFF[min(idx, len(PROBE_BACKOFF) - 1)]
367
- st["probe_next_at"] = _now() + backoff
368
- st["probe_backoff_idx"] = idx + 1
369
- for name, st in targets:
370
- ok, gone = _probe_one(st)
371
- _record_probe_result(name, st, ok, gone)
372
- except Exception:
373
- log.exception("health probe loop error")
374
- time.sleep(15) # 探针调度心跳
1
+ # -*- coding: utf-8 -*-
2
+ """供应商健康监测与告警:连不上模型/厂商时自动降级并告警,恢复自动解除。
3
+
4
+ 设计稿:docs/migration/07-token-cost.md 的延伸(2026-09-15 连载验收实战需求:
5
+ cavoti 网关宕机 5 小时,系统只会反复失败重试,没有主动告知「通道已不可用」)。
6
+
7
+ 状态机(按 provider):
8
+ ok 正常(有近期成功或不活跃)
9
+ failing 连续失败 ≥FAILING_AFTER(进入探测模式)
10
+ down failing 持续 ≥DOWN_AFTER_SECONDS 或连续失败 ≥DOWN_AFTER_FAILURES
11
+ → 触发告警(未静默时)
12
+ recovered down/failing 后再次成功 → 自动解除告警,记一笔恢复
13
+
14
+ 探针策略(省 token):正常时不主动探测(靠真实调用信号);failing/down 后按
15
+ 退避(60s→120s→300s 封顶)发轻量探活(modelhub.chat,max_tokens=8)。
16
+ 恢复 → 回正常节奏。
17
+
18
+ 手动操作:
19
+ silence(provider) 静默本次告警(不再提醒,直到恢复或手动 reset)
20
+ reset(provider) 手动清除状态视为恢复(下次失败重新计数)
21
+
22
+ 线程模型:上报(runner/pipeline/modelhub 多线程调用)走锁;探针单线程 daemon。
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import logging
28
+ import threading
29
+ import time
30
+ from pathlib import Path
31
+
32
+ log = logging.getLogger(__name__)
33
+
34
+ FAILING_AFTER = 2 # 连续失败 ≥2 → failing(进入探测)
35
+ DOWN_AFTER_FAILURES = 4 # 连续失败 ≥4 → down(告警)
36
+ DOWN_AFTER_SECONDS = 600 # 或 failing 持续 10 分钟 → down
37
+ PROBE_BACKOFF = (60, 120, 300) # 探测退避秒数(封顶 300)
38
+ SILENCE_FOREVER = -1 # 手动静默不自动过期(恢复时才清除)
39
+
40
+ _LOCK = threading.RLock()
41
+ _PROVIDERS = {} # name -> 状态 dict
42
+ _FILE = None # init() 注入(data/provider_health.json)
43
+ _PROBE_THREAD = None
44
+ _STARTED = False
45
+
46
+
47
+ def init(data_dir=None, *, start_probe=True):
48
+ """注入存储路径并从磁盘恢复状态(服务重启不丢告警上下文)。
49
+
50
+ ``start_probe=False`` 供单元测试等受控场景使用,避免留下跨用例的
51
+ daemon 探针线程。
52
+ """
53
+ global _FILE, _PROVIDERS, _STARTED, _PROBE_THREAD
54
+ with _LOCK:
55
+ base = Path(data_dir) if data_dir else Path(_default_dir())
56
+ base.mkdir(parents=True, exist_ok=True)
57
+ _FILE = base / "provider_health.json"
58
+ _PROVIDERS = {}
59
+ try:
60
+ data = json.loads(_FILE.read_text(encoding="utf-8"))
61
+ for name, st in (data.get("providers") or {}).items():
62
+ if isinstance(st, dict) and st.get("name"):
63
+ _PROVIDERS[name] = st
64
+ except (OSError, json.JSONDecodeError):
65
+ pass
66
+ # 「绑定链·」静态告警胶囊已从产品移除(2026-09-18:普通用户误伤,
67
+ # 用户拍板)——老版本持久化的条目启动即清,别让 0.1.6 的状态阴魂不散。
68
+ stale = [k for k in _PROVIDERS if k.startswith("绑定链·")]
69
+ if stale:
70
+ for k in stale:
71
+ _PROVIDERS.pop(k, None)
72
+ _persist()
73
+ # 供应商已删除的幽灵条目启动即清;运行期新增的幽灵由探针在探活时
74
+ # 发现(gone 标记)随手清——探针循环里不做全量扫描,避免和测试
75
+ # 夹具/运行期建条目赛跑。
76
+ _prune_missing()
77
+ if start_probe and not _STARTED:
78
+ _STARTED = True
79
+ _PROBE_THREAD = threading.Thread(
80
+ target=_probe_loop, name="health-probe", daemon=True)
81
+ _PROBE_THREAD.start()
82
+
83
+
84
+ def _default_dir():
85
+ from . import paths
86
+ return str(paths.DATA_DIR)
87
+
88
+
89
+ def _persist():
90
+ # This is telemetry state: a storage failure must not turn a successful or
91
+ # failed model call into a task failure. Callers already hold _LOCK, but
92
+ # keeping the path and snapshot read under it also protects future callers.
93
+ with _LOCK:
94
+ path = _FILE
95
+ if path is None:
96
+ return
97
+ try:
98
+ path.parent.mkdir(parents=True, exist_ok=True)
99
+ tmp = path.with_suffix(".tmp")
100
+ tmp.write_text(
101
+ json.dumps({"providers": _PROVIDERS}, ensure_ascii=False, indent=2),
102
+ encoding="utf-8")
103
+ tmp.replace(path)
104
+ except OSError as e:
105
+ log.warning("[health] 无法持久化供应商健康状态到 %s: %s", path, e)
106
+
107
+
108
+ def _now():
109
+ return time.time()
110
+
111
+
112
+ def _fmt_ts(epoch):
113
+ if not epoch:
114
+ return ""
115
+ return time.strftime("%m-%d %H:%M", time.localtime(epoch))
116
+
117
+
118
+ # ---------------------------------------------------------------- 上报入口
119
+
120
+ def report_success(provider: str):
121
+ """一次真实成功调用(CLI 或 API 直连)。"""
122
+ if not provider:
123
+ return
124
+ with _LOCK:
125
+ st = _PROVIDERS.get(provider)
126
+ if st is None:
127
+ return # 没失败过就不建档(零开销)
128
+ if st.get("status") in ("failing", "down"):
129
+ st["status"] = "recovered"
130
+ st["recovered_at"] = _now()
131
+ st["consecutive_failures"] = 0
132
+ st["last_ok_at"] = _now()
133
+ st["probe_next_at"] = 0
134
+ st["alerted"] = False
135
+ st["silenced"] = False # 静默只管一次故障期;恢复后重新武装
136
+ st["silence_until"] = 0
137
+ log.info("[health] %s 已恢复(告警自动解除)", provider)
138
+ else:
139
+ st["last_ok_at"] = _now()
140
+ st["consecutive_failures"] = 0
141
+ _persist()
142
+
143
+
144
+ def report_failure(provider: str, error: str = "", *, model: str = "",
145
+ provider_id: str = ""):
146
+ """一次真实失败调用。provider 用展示名(与 usage 台账一致)。"""
147
+ if not provider:
148
+ return
149
+
150
+ # A failed live call invalidates capability evidence for this upstream.
151
+ # Keep this hook lazy and best-effort: health telemetry must never make a
152
+ # model call fail, and importing evaluation at module load would create a
153
+ # dependency cycle during startup. ``provider_id`` is the canonical
154
+ # identity used by the evaluation ledger; the display name is not safe to
155
+ # use as a substitute because aliases can point at the same host.
156
+ if provider_id:
157
+ try:
158
+ from . import evaluation
159
+ evaluation.invalidate_provider(provider_id, model=model)
160
+ except Exception:
161
+ log.debug("[health] 无法使评测结论失效", exc_info=True)
162
+ with _LOCK:
163
+ st = _PROVIDERS.setdefault(provider, {
164
+ "name": provider, "provider_id": provider_id or "",
165
+ "model": model or "", "status": "ok",
166
+ "consecutive_failures": 0, "first_fail_at": 0,
167
+ "last_fail_at": 0, "last_ok_at": 0, "last_error": "",
168
+ "alerted": False, "silenced": False, "silence_until": 0,
169
+ "probe_next_at": 0, "probe_backoff_idx": 0,
170
+ "recovered_at": 0,
171
+ })
172
+ st["name"] = provider
173
+ if provider_id and not st.get("provider_id"):
174
+ st["provider_id"] = provider_id
175
+ if model and not st.get("model"):
176
+ st["model"] = model
177
+ n = int(st.get("consecutive_failures") or 0) + 1
178
+ st["consecutive_failures"] = n
179
+ st["last_fail_at"] = _now()
180
+ st["last_error"] = str(error or "")[:300]
181
+ if st.get("status") in ("ok", "recovered", ""):
182
+ st["status"] = "failing"
183
+ st["first_fail_at"] = _now()
184
+ st["probe_next_at"] = _now() + PROBE_BACKOFF[0]
185
+ st["probe_backoff_idx"] = 0
186
+ # failing → down:连续次数或持续时间任一达到
187
+ if st["status"] == "failing":
188
+ dur = _now() - (st.get("first_fail_at") or _now())
189
+ if n >= DOWN_AFTER_FAILURES or dur >= DOWN_AFTER_SECONDS:
190
+ st["status"] = "down"
191
+ if st["status"] == "down" and not st.get("silenced"):
192
+ if not st.get("alerted"):
193
+ st["alerted"] = True
194
+ log.warning("[health] ⚠️ 供应商告警:%s 不可用(连续 %d 次失败,%s)",
195
+ provider, n, st["last_error"][:120])
196
+ _persist()
197
+
198
+
199
+ # ------------------------------------------------- 静态死链告警(绑定层)
200
+
201
+ # ---------------------------------------------------------------- 手动操作
202
+
203
+ def silence(provider: str, minutes: int = 0):
204
+ """手动静默告警(minutes=0 表示静默到恢复为止)。"""
205
+ with _LOCK:
206
+ st = _PROVIDERS.get(provider)
207
+ if not st:
208
+ return False, "未知的供应商"
209
+ st["silenced"] = True
210
+ st["silence_until"] = (_now() + minutes * 60) if minutes else SILENCE_FOREVER
211
+ st["alerted"] = False
212
+ _persist()
213
+ return True, ""
214
+
215
+
216
+ def reset(provider: str):
217
+ """手动清除状态视为恢复(下次失败重新计数)。"""
218
+ with _LOCK:
219
+ st = _PROVIDERS.get(provider)
220
+ if not st:
221
+ return False, "未知的供应商"
222
+ st.update({"status": "recovered", "consecutive_failures": 0,
223
+ "alerted": False, "silenced": False, "silence_until": 0,
224
+ "probe_next_at": 0, "recovered_at": _now()})
225
+ _persist()
226
+ return True, ""
227
+
228
+
229
+ # ---------------------------------------------------------------- 查询
230
+
231
+ def _effective_silenced(st):
232
+ """静默是否仍有效(永久静默或未到过期时间)。"""
233
+ if not st.get("silenced"):
234
+ return False
235
+ until = st.get("silence_until") or 0
236
+ return until == SILENCE_FOREVER or until > _now()
237
+
238
+
239
+ def snapshot():
240
+ """给 API/SSE 的完整视图。"""
241
+ with _LOCK:
242
+ out = []
243
+ for name, st in _PROVIDERS.items():
244
+ silenced = _effective_silenced(st)
245
+ alerting = st.get("status") == "down" and not silenced
246
+ out.append({
247
+ "provider": name,
248
+ "provider_id": st.get("provider_id") or "",
249
+ "model": st.get("model") or "",
250
+ "status": st.get("status") or "ok",
251
+ "consecutive_failures": st.get("consecutive_failures") or 0,
252
+ "first_fail_at": _fmt_ts(st.get("first_fail_at")),
253
+ "last_fail_at": _fmt_ts(st.get("last_fail_at")),
254
+ "last_ok_at": _fmt_ts(st.get("last_ok_at")),
255
+ "recovered_at": _fmt_ts(st.get("recovered_at")),
256
+ "last_error": st.get("last_error") or "",
257
+ "alerting": alerting,
258
+ "silenced": silenced,
259
+ "static": bool(st.get("static")),
260
+ })
261
+ # 稳定排序:告警中 > 故障中 > 恢复 > 正常
262
+ rank = {"down": 0, "failing": 1, "recovered": 2, "ok": 3}
263
+ out.sort(key=lambda x: (rank.get(x["status"], 9), x["provider"]))
264
+ return {
265
+ "providers": out,
266
+ "alerts": [p for p in out if p["alerting"]],
267
+ "any_alerting": any(p["alerting"] for p in out),
268
+ }
269
+
270
+
271
+ def is_down(provider: str) -> bool:
272
+ """链降级查询:该供应商当前是否 down(供 resolve_binding 跳过)。"""
273
+ with _LOCK:
274
+ st = _PROVIDERS.get(provider)
275
+ return bool(st and st.get("status") == "down")
276
+
277
+
278
+ def down_names() -> set:
279
+ with _LOCK:
280
+ return {n for n, st in _PROVIDERS.items() if st.get("status") == "down"}
281
+
282
+
283
+ # ---------------------------------------------------------------- 探针
284
+
285
+ def _probe_one(st):
286
+ """对单个故障 provider 发轻量探活。返回 (ok, gone):
287
+ ok=是否恢复;gone=供应商已从配置里删除(健康记录应随之清掉)。"""
288
+ try:
289
+ from . import modelhub
290
+ pid = st.get("provider_id") or ""
291
+ model = st.get("model") or ""
292
+ plist = modelhub.providers()
293
+ provs = {p.get("name"): p for p in plist}
294
+ prov = provs.get(st.get("name")) or next(
295
+ (p for p in plist if pid and p.get("id") == pid), None)
296
+ if not prov:
297
+ return False, True # 供应商已删除:探不了也不再是「没恢复」
298
+ if not prov.get("api_key"):
299
+ return False, False # 供应商在但没密钥:无法探测,保持状态
300
+ if not model:
301
+ try:
302
+ names = modelhub._enabled_models(prov)
303
+ model = names[0]["name"] if names else ""
304
+ except Exception:
305
+ model = ""
306
+ if not model:
307
+ return False, False
308
+ res = modelhub.chat(prov["id"], model, "1", max_tokens=8, timeout=20)
309
+ return bool(res.get("ok")), False
310
+ except Exception as e:
311
+ log.debug("probe %s error: %s", st.get("name"), e)
312
+ return False, False
313
+
314
+
315
+ def _prune_missing():
316
+ """供应商被删除后清掉它的健康记录。
317
+
318
+ 幽灵条目探不活也永远不会恢复,还会每轮把 last_fail_at 刷成「刚刚」,
319
+ 健康页看起来像它一直在报错(Z.ai 删掉后仍显示 429 的误伤案,2026-09-18)。
320
+ """
321
+ try:
322
+ from . import modelhub
323
+ plist = modelhub.providers()
324
+ except Exception:
325
+ return
326
+ ids = {p.get("id") for p in plist}
327
+ names = {p.get("name") for p in plist}
328
+ with _LOCK:
329
+ stale = [n for n, st in _PROVIDERS.items()
330
+ if not ((st.get("provider_id") and st.get("provider_id") in ids)
331
+ or st.get("name") in names)]
332
+ if stale:
333
+ for n in stale:
334
+ _PROVIDERS.pop(n, None)
335
+ _persist()
336
+ log.info("[health] 清除已删除供应商的健康记录:%s", ", ".join(stale))
337
+
338
+
339
+ def _record_probe_result(name, st, ok, gone):
340
+ """只应用仍属于当前状态表的探针结果,忽略跨 init/测试的过期结果。"""
341
+ with _LOCK:
342
+ if _PROVIDERS.get(name) is not st:
343
+ return
344
+ if gone:
345
+ _PROVIDERS.pop(name, None)
346
+ _persist()
347
+ log.info("[health] %s 已删除,健康记录随之清除", name)
348
+ elif ok:
349
+ report_success(name)
350
+ log.info("[health] 探针确认 %s 已恢复", name)
351
+ else:
352
+ st["last_fail_at"] = _now()
353
+ _persist()
354
+
355
+
356
+ def _probe_loop():
357
+ while True:
358
+ try:
359
+ with _LOCK:
360
+ targets = [(name, st) for name, st in _PROVIDERS.items()
361
+ if not st.get("static") # 静态死链无端点可探,绑定恢复时自动解除
362
+ and st.get("status") in ("failing", "down")
363
+ and (st.get("probe_next_at") or 0) <= _now()]
364
+ for name, st in targets:
365
+ idx = int(st.get("probe_backoff_idx") or 0)
366
+ backoff = PROBE_BACKOFF[min(idx, len(PROBE_BACKOFF) - 1)]
367
+ st["probe_next_at"] = _now() + backoff
368
+ st["probe_backoff_idx"] = idx + 1
369
+ for name, st in targets:
370
+ ok, gone = _probe_one(st)
371
+ _record_probe_result(name, st, ok, gone)
372
+ except Exception:
373
+ log.exception("health probe loop error")
374
+ time.sleep(15) # 探针调度心跳