codebee 0.1.66 → 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.
- package/CHANGELOG.md +543 -520
- package/LICENSE +21 -21
- package/README.md +11 -7
- package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +88 -0
- package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +126 -0
- package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
- package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +210 -0
- package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
- package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
- package/app/.playwright-cli/run-detail-after.png +0 -0
- package/app/core/acceptance.py +100 -0
- package/app/core/aiflavor.py +197 -197
- package/app/core/artifacts.py +148 -148
- package/app/core/assets.py +110 -0
- package/app/core/attachments.py +623 -532
- package/app/core/automation.py +758 -758
- package/app/core/backup.py +470 -470
- package/app/core/beekeeper.py +183 -183
- package/app/core/board.py +209 -209
- package/app/core/bookmeta.py +930 -796
- package/app/core/bookmeta_catalog.py +180 -180
- package/app/core/branching.py +137 -137
- package/app/core/builtin_agent.py +1234 -1234
- package/app/core/capability.py +144 -144
- package/app/core/catalog.py +42 -0
- package/app/core/chaptersafe.py +32 -32
- package/app/core/cleanup.py +303 -303
- package/app/core/compaction.py +201 -201
- package/app/core/covergen.py +356 -356
- package/app/core/defectretro.py +43 -0
- package/app/core/diagnostics.py +114 -114
- package/app/core/dispatch.py +173 -173
- package/app/core/dispatch_log.py +128 -113
- package/app/core/env_scrub.py +85 -85
- package/app/core/error_codes.py +23 -23
- package/app/core/errorlog.py +137 -137
- package/app/core/evaluation.py +174 -174
- package/app/core/failure_notify.py +290 -290
- package/app/core/flows.py +48 -2
- package/app/core/goal_service.py +167 -167
- package/app/core/health.py +374 -374
- package/app/core/history.py +38 -38
- package/app/core/hooks.py +162 -162
- package/app/core/jobs.py +46 -26
- package/app/core/knowledge.py +57 -3
- package/app/core/manager.py +2122 -2115
- package/app/core/market.py +362 -362
- package/app/core/market_remote.py +124 -26
- package/app/core/mocks.py +64 -64
- package/app/core/modelhub.py +51 -3
- package/app/core/notify.py +106 -106
- package/app/core/operations.py +228 -0
- package/app/core/paihang.py +138 -109
- package/app/core/paths.py +2 -2
- package/app/core/pipeline.py +221 -12
- package/app/core/planner.py +6 -1
- package/app/core/portguard.py +111 -111
- package/app/core/preview.py +293 -293
- package/app/core/publish/__init__.py +7 -7
- package/app/core/publish/auto.py +367 -367
- package/app/core/publish/browser.py +539 -533
- package/app/core/publish/fanqie.py +159 -128
- package/app/core/publish/flow.py +440 -432
- package/app/core/publish/flows-fanqie-calibrated.json +332 -332
- package/app/core/publish/flows-qimao-calibrated.json +7 -3
- package/app/core/publish/ledger.py +203 -198
- package/app/core/publish/manager.py +692 -623
- package/app/core/publish/qimao.py +141 -141
- package/app/core/publish/ws.py +139 -139
- package/app/core/redact.py +38 -38
- package/app/core/repeat_guard.py +129 -129
- package/app/core/revisions.py +51 -0
- package/app/core/router.py +398 -398
- package/app/core/runner.py +2067 -2050
- package/app/core/selfupdate.py +384 -384
- package/app/core/session_log.py +161 -161
- package/app/core/sessions.py +312 -312
- package/app/core/settings.py +149 -149
- package/app/core/settings_schema.py +262 -262
- package/app/core/share_page.py +114 -114
- package/app/core/skill_scan.py +122 -114
- package/app/core/skillpacks/fanqie-novel.md +80 -80
- package/app/core/skillpacks/market/character-bible.md +66 -66
- package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
- package/app/core/skillpacks/market/git-workflow.md +57 -57
- package/app/core/skillpacks/market/release-notes.md +72 -72
- package/app/core/skillpacks/market/weekly-report.md +71 -71
- package/app/core/skillpacks/market/worldview-consistency.md +70 -70
- package/app/core/skills.py +109 -2
- package/app/core/step_runner.py +132 -132
- package/app/core/store.py +278 -41
- package/app/core/task_compile.py +199 -199
- package/app/core/telemetry.py +292 -292
- package/app/core/tlsctx.py +64 -64
- package/app/core/token_meter.py +147 -147
- package/app/core/tracing.py +144 -0
- package/app/core/upstream.py +41 -41
- package/app/core/usage.py +862 -858
- package/app/core/volumes.py +389 -355
- package/app/core/wxdigest.py +858 -858
- package/app/core/zentao.py +2465 -2447
- package/app/main.py +2981 -2838
- package/app/pick_dialog.py +110 -110
- package/app/ui/app.js +14399 -13994
- package/app/ui/artdiff.js +74 -0
- package/app/ui/board.html +162 -162
- package/app/ui/board.js +305 -305
- package/app/ui/i18n.js +2770 -2716
- package/app/ui/icons/bee.svg +79 -79
- package/app/ui/index.html +6 -0
- package/app/ui/manifest.json +16 -16
- package/app/ui/qrcode.js +2297 -2297
- package/app/ui/style.css +96 -24
- package/bin/tutti.js +147 -147
- package/package.json +46 -46
- package/tools/wx_reader.py +261 -261
package/app/core/errorlog.py
CHANGED
|
@@ -1,137 +1,137 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""错误台账:把分散在各处的失败(步骤失败/超时/看门狗击杀、CLI 启动失败)
|
|
3
|
-
统一落成结构化记录——「客户遇到了问题我们根本不知道」的第一块拼图。
|
|
4
|
-
|
|
5
|
-
落盘:data/errors/errors-YYYYMM.jsonl(按月分文件,append-only,一行一记录)。
|
|
6
|
-
与 usage.py 同一套纪律:
|
|
7
|
-
- record() 任何异常都吞掉——埋点失败绝不能影响任务执行;
|
|
8
|
-
- 落盘前先脱敏(scrub_text):密钥/令牌/绝对路径/超长文本一概不进台账。
|
|
9
|
-
|
|
10
|
-
隐私红线(上传侧在 telemetry.py 再兜一道底):
|
|
11
|
-
1. API KEY / 凭据绝不入台账;
|
|
12
|
-
2. 任务正文 / 章节内容(用户版权内容)绝不入台账——detail 只允许失败原因摘录;
|
|
13
|
-
3. 绝对路径剥成相对片段。
|
|
14
|
-
"""
|
|
15
|
-
from __future__ import annotations
|
|
16
|
-
|
|
17
|
-
import json
|
|
18
|
-
import threading
|
|
19
|
-
import time
|
|
20
|
-
import uuid
|
|
21
|
-
|
|
22
|
-
from . import paths
|
|
23
|
-
from .redact import scrub_text
|
|
24
|
-
|
|
25
|
-
LOCK = threading.RLock()
|
|
26
|
-
|
|
27
|
-
FIELDS = ("id", "ts", "day", "category", "reason", "detail", "provider",
|
|
28
|
-
"model", "tool", "role", "run_id", "task_id", "step",
|
|
29
|
-
"exit_code", "app_version", "os")
|
|
30
|
-
|
|
31
|
-
# detail 摘录上限(字符):失败原因足够,不要变成日志搬运
|
|
32
|
-
DETAIL_LIMIT = 600
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
# ---------------------------------------------------------------- 脱敏
|
|
36
|
-
|
|
37
|
-
def _coerce_str(v, limit):
|
|
38
|
-
return str(v or "")[:limit]
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def _os_tag():
|
|
42
|
-
import sys
|
|
43
|
-
return {"win32": "windows", "darwin": "macos"}.get(sys.platform, sys.platform)
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
def _version():
|
|
47
|
-
try:
|
|
48
|
-
from . import selfupdate
|
|
49
|
-
return str(selfupdate.package_version() or "dev")
|
|
50
|
-
except Exception:
|
|
51
|
-
return "dev"
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def record(category="", reason="", detail="", provider="", model="", tool="",
|
|
55
|
-
role="", run_id="", task_id="", step=0, exit_code=None, source=""):
|
|
56
|
-
"""追加一条错误记录。缺省字段留空;任何异常都吞掉(埋点不拖垮业务)。
|
|
57
|
-
|
|
58
|
-
category: step / run / launch / service(枚举放宽,未知值原样入库)
|
|
59
|
-
reason: 失败原因码(error_codes.ErrorCode 的字符串值优先,如 TIMEOUT)
|
|
60
|
-
detail: 失败摘录(内部先过 scrub_text,绝不存原文)
|
|
61
|
-
"""
|
|
62
|
-
try:
|
|
63
|
-
rec = {
|
|
64
|
-
"id": "%s-%s" % (time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
65
|
-
uuid.uuid4().hex[:8]),
|
|
66
|
-
"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
67
|
-
"day": time.strftime("%Y-%m-%d"),
|
|
68
|
-
"category": _coerce_str(category, 24) or "step",
|
|
69
|
-
"reason": _coerce_str(reason, 40) or "UNKNOWN",
|
|
70
|
-
"detail": scrub_text(detail),
|
|
71
|
-
"provider": _coerce_str(provider, 60),
|
|
72
|
-
"model": _coerce_str(model, 80),
|
|
73
|
-
"tool": _coerce_str(tool, 24),
|
|
74
|
-
"role": _coerce_str(role, 40),
|
|
75
|
-
"run_id": _coerce_str(run_id, 64),
|
|
76
|
-
"task_id": _coerce_str(task_id, 64),
|
|
77
|
-
"step": int(step or 0),
|
|
78
|
-
"exit_code": exit_code,
|
|
79
|
-
"app_version": _version()[:24],
|
|
80
|
-
"os": _os_tag(),
|
|
81
|
-
}
|
|
82
|
-
line = json.dumps(rec, ensure_ascii=False)
|
|
83
|
-
day = rec["day"]
|
|
84
|
-
with LOCK:
|
|
85
|
-
paths.ERRORS_DIR.mkdir(parents=True, exist_ok=True)
|
|
86
|
-
with open(paths.ERRORS_DIR / ("errors-%s.jsonl" % day[:7].replace("-", "")),
|
|
87
|
-
"a", encoding="utf-8") as f:
|
|
88
|
-
f.write(line + "\n")
|
|
89
|
-
except Exception:
|
|
90
|
-
pass
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def iter_records(days=0):
|
|
94
|
-
"""按时间范围读取台账(days=0 表示全部)。返回按写入顺序的记录列表。"""
|
|
95
|
-
out = []
|
|
96
|
-
try:
|
|
97
|
-
files = sorted(paths.ERRORS_DIR.glob("errors-*.jsonl")) if paths.ERRORS_DIR.is_dir() else []
|
|
98
|
-
except Exception:
|
|
99
|
-
return out
|
|
100
|
-
since_day = ""
|
|
101
|
-
if days:
|
|
102
|
-
import datetime
|
|
103
|
-
since_day = (datetime.date.today()
|
|
104
|
-
- datetime.timedelta(days=int(days) - 1)).isoformat()
|
|
105
|
-
for p in files:
|
|
106
|
-
try:
|
|
107
|
-
for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
108
|
-
line = line.strip()
|
|
109
|
-
if not line.startswith("{"):
|
|
110
|
-
continue
|
|
111
|
-
try:
|
|
112
|
-
r = json.loads(line)
|
|
113
|
-
except Exception:
|
|
114
|
-
continue
|
|
115
|
-
if not isinstance(r, dict):
|
|
116
|
-
continue
|
|
117
|
-
if since_day and str(r.get("day", "")) < since_day:
|
|
118
|
-
continue
|
|
119
|
-
out.append(r)
|
|
120
|
-
except Exception:
|
|
121
|
-
continue
|
|
122
|
-
return out
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def pending_since(cursor, limit=200):
|
|
126
|
-
"""取 cursor(上次上传到的记录 id)之后的记录,最多 limit 条。
|
|
127
|
-
|
|
128
|
-
id 以时间开头、uuid 尾巴保证唯一且字典序≈时间序;返回 (records, new_cursor)。
|
|
129
|
-
"""
|
|
130
|
-
try:
|
|
131
|
-
recs = [r for r in iter_records(0) if str(r.get("id") or "") > str(cursor or "")]
|
|
132
|
-
recs.sort(key=lambda r: str(r.get("id") or ""))
|
|
133
|
-
batch = recs[:max(1, int(limit))]
|
|
134
|
-
new_cursor = str(batch[-1].get("id")) if batch else str(cursor or "")
|
|
135
|
-
return batch, new_cursor
|
|
136
|
-
except Exception:
|
|
137
|
-
return [], str(cursor or "")
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""错误台账:把分散在各处的失败(步骤失败/超时/看门狗击杀、CLI 启动失败)
|
|
3
|
+
统一落成结构化记录——「客户遇到了问题我们根本不知道」的第一块拼图。
|
|
4
|
+
|
|
5
|
+
落盘:data/errors/errors-YYYYMM.jsonl(按月分文件,append-only,一行一记录)。
|
|
6
|
+
与 usage.py 同一套纪律:
|
|
7
|
+
- record() 任何异常都吞掉——埋点失败绝不能影响任务执行;
|
|
8
|
+
- 落盘前先脱敏(scrub_text):密钥/令牌/绝对路径/超长文本一概不进台账。
|
|
9
|
+
|
|
10
|
+
隐私红线(上传侧在 telemetry.py 再兜一道底):
|
|
11
|
+
1. API KEY / 凭据绝不入台账;
|
|
12
|
+
2. 任务正文 / 章节内容(用户版权内容)绝不入台账——detail 只允许失败原因摘录;
|
|
13
|
+
3. 绝对路径剥成相对片段。
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
|
|
22
|
+
from . import paths
|
|
23
|
+
from .redact import scrub_text
|
|
24
|
+
|
|
25
|
+
LOCK = threading.RLock()
|
|
26
|
+
|
|
27
|
+
FIELDS = ("id", "ts", "day", "category", "reason", "detail", "provider",
|
|
28
|
+
"model", "tool", "role", "run_id", "task_id", "step",
|
|
29
|
+
"exit_code", "app_version", "os")
|
|
30
|
+
|
|
31
|
+
# detail 摘录上限(字符):失败原因足够,不要变成日志搬运
|
|
32
|
+
DETAIL_LIMIT = 600
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------- 脱敏
|
|
36
|
+
|
|
37
|
+
def _coerce_str(v, limit):
|
|
38
|
+
return str(v or "")[:limit]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _os_tag():
|
|
42
|
+
import sys
|
|
43
|
+
return {"win32": "windows", "darwin": "macos"}.get(sys.platform, sys.platform)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _version():
|
|
47
|
+
try:
|
|
48
|
+
from . import selfupdate
|
|
49
|
+
return str(selfupdate.package_version() or "dev")
|
|
50
|
+
except Exception:
|
|
51
|
+
return "dev"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def record(category="", reason="", detail="", provider="", model="", tool="",
|
|
55
|
+
role="", run_id="", task_id="", step=0, exit_code=None, source=""):
|
|
56
|
+
"""追加一条错误记录。缺省字段留空;任何异常都吞掉(埋点不拖垮业务)。
|
|
57
|
+
|
|
58
|
+
category: step / run / launch / service(枚举放宽,未知值原样入库)
|
|
59
|
+
reason: 失败原因码(error_codes.ErrorCode 的字符串值优先,如 TIMEOUT)
|
|
60
|
+
detail: 失败摘录(内部先过 scrub_text,绝不存原文)
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
rec = {
|
|
64
|
+
"id": "%s-%s" % (time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
65
|
+
uuid.uuid4().hex[:8]),
|
|
66
|
+
"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
|
|
67
|
+
"day": time.strftime("%Y-%m-%d"),
|
|
68
|
+
"category": _coerce_str(category, 24) or "step",
|
|
69
|
+
"reason": _coerce_str(reason, 40) or "UNKNOWN",
|
|
70
|
+
"detail": scrub_text(detail),
|
|
71
|
+
"provider": _coerce_str(provider, 60),
|
|
72
|
+
"model": _coerce_str(model, 80),
|
|
73
|
+
"tool": _coerce_str(tool, 24),
|
|
74
|
+
"role": _coerce_str(role, 40),
|
|
75
|
+
"run_id": _coerce_str(run_id, 64),
|
|
76
|
+
"task_id": _coerce_str(task_id, 64),
|
|
77
|
+
"step": int(step or 0),
|
|
78
|
+
"exit_code": exit_code,
|
|
79
|
+
"app_version": _version()[:24],
|
|
80
|
+
"os": _os_tag(),
|
|
81
|
+
}
|
|
82
|
+
line = json.dumps(rec, ensure_ascii=False)
|
|
83
|
+
day = rec["day"]
|
|
84
|
+
with LOCK:
|
|
85
|
+
paths.ERRORS_DIR.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
with open(paths.ERRORS_DIR / ("errors-%s.jsonl" % day[:7].replace("-", "")),
|
|
87
|
+
"a", encoding="utf-8") as f:
|
|
88
|
+
f.write(line + "\n")
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def iter_records(days=0):
|
|
94
|
+
"""按时间范围读取台账(days=0 表示全部)。返回按写入顺序的记录列表。"""
|
|
95
|
+
out = []
|
|
96
|
+
try:
|
|
97
|
+
files = sorted(paths.ERRORS_DIR.glob("errors-*.jsonl")) if paths.ERRORS_DIR.is_dir() else []
|
|
98
|
+
except Exception:
|
|
99
|
+
return out
|
|
100
|
+
since_day = ""
|
|
101
|
+
if days:
|
|
102
|
+
import datetime
|
|
103
|
+
since_day = (datetime.date.today()
|
|
104
|
+
- datetime.timedelta(days=int(days) - 1)).isoformat()
|
|
105
|
+
for p in files:
|
|
106
|
+
try:
|
|
107
|
+
for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
108
|
+
line = line.strip()
|
|
109
|
+
if not line.startswith("{"):
|
|
110
|
+
continue
|
|
111
|
+
try:
|
|
112
|
+
r = json.loads(line)
|
|
113
|
+
except Exception:
|
|
114
|
+
continue
|
|
115
|
+
if not isinstance(r, dict):
|
|
116
|
+
continue
|
|
117
|
+
if since_day and str(r.get("day", "")) < since_day:
|
|
118
|
+
continue
|
|
119
|
+
out.append(r)
|
|
120
|
+
except Exception:
|
|
121
|
+
continue
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def pending_since(cursor, limit=200):
|
|
126
|
+
"""取 cursor(上次上传到的记录 id)之后的记录,最多 limit 条。
|
|
127
|
+
|
|
128
|
+
id 以时间开头、uuid 尾巴保证唯一且字典序≈时间序;返回 (records, new_cursor)。
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
recs = [r for r in iter_records(0) if str(r.get("id") or "") > str(cursor or "")]
|
|
132
|
+
recs.sort(key=lambda r: str(r.get("id") or ""))
|
|
133
|
+
batch = recs[:max(1, int(limit))]
|
|
134
|
+
new_cursor = str(batch[-1].get("id")) if batch else str(cursor or "")
|
|
135
|
+
return batch, new_cursor
|
|
136
|
+
except Exception:
|
|
137
|
+
return [], str(cursor or "")
|
package/app/core/evaluation.py
CHANGED
|
@@ -1,174 +1,174 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""Expiring model/provider evaluation conclusions.
|
|
3
|
-
|
|
4
|
-
An evaluation is evidence captured at a point in time, not a permanent
|
|
5
|
-
capability claim. Results are kept as a small, content-free local ledger so
|
|
6
|
-
the UI or a router can distinguish a fresh ``passed`` result from an expired
|
|
7
|
-
one. A provider health failure invalidates matching conclusions immediately;
|
|
8
|
-
the health probe can show recovery, but only a fresh evaluation restores
|
|
9
|
-
``passed``.
|
|
10
|
-
"""
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
|
-
import json
|
|
14
|
-
import math
|
|
15
|
-
import os
|
|
16
|
-
from pathlib import Path
|
|
17
|
-
import threading
|
|
18
|
-
import time
|
|
19
|
-
|
|
20
|
-
DEFAULT_TTL_SECONDS = 24 * 60 * 60
|
|
21
|
-
_LOCK = threading.RLock()
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def _path() -> Path:
|
|
25
|
-
from . import paths
|
|
26
|
-
return Path(paths.DATA_DIR) / "evaluations.json"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def ttl_seconds() -> float:
|
|
30
|
-
try:
|
|
31
|
-
return max(60.0, float(os.environ.get(
|
|
32
|
-
"TUTTI_EVALUATION_TTL_S", DEFAULT_TTL_SECONDS)))
|
|
33
|
-
except (TypeError, ValueError):
|
|
34
|
-
return float(DEFAULT_TTL_SECONDS)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
def _read() -> dict:
|
|
38
|
-
try:
|
|
39
|
-
value = json.loads(_path().read_text(encoding="utf-8"))
|
|
40
|
-
return value if isinstance(value, dict) else {}
|
|
41
|
-
except (OSError, json.JSONDecodeError):
|
|
42
|
-
return {}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def _write(value: dict) -> None:
|
|
46
|
-
path = _path()
|
|
47
|
-
try:
|
|
48
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
49
|
-
tmp = path.with_suffix(".tmp")
|
|
50
|
-
tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2),
|
|
51
|
-
encoding="utf-8")
|
|
52
|
-
tmp.replace(path)
|
|
53
|
-
except OSError:
|
|
54
|
-
# Evaluation is telemetry. A read-only data directory must not turn
|
|
55
|
-
# a successful model call into a task failure.
|
|
56
|
-
pass
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def key(kind: str, provider_id: str, model: str = "", protocol: str = "",
|
|
60
|
-
key_id: str = "") -> str:
|
|
61
|
-
base = "%s|%s|%s" % (str(kind or "provider"),
|
|
62
|
-
str(provider_id or ""), str(model or ""))
|
|
63
|
-
suffix = "|".join((str(protocol or ""), str(key_id or "")))
|
|
64
|
-
return base if not suffix.strip("|") else base + "|" + suffix
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
def decorate(result: dict, *, now=None) -> dict:
|
|
68
|
-
"""Attach an evaluated-at timestamp and expiry to an API response."""
|
|
69
|
-
out = dict(result or {})
|
|
70
|
-
now = time.time() if now is None else float(now)
|
|
71
|
-
out["evaluated_at"] = now
|
|
72
|
-
out["expires_at"] = now + ttl_seconds()
|
|
73
|
-
out["fresh"] = True
|
|
74
|
-
return out
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def record(kind: str, provider_id: str, model: str, result: dict,
|
|
78
|
-
*, protocol: str = "", requested_model: str = "",
|
|
79
|
-
served_model: str = "", key_id: str = "") -> dict:
|
|
80
|
-
"""Persist safe metadata for one completed evaluation and return it."""
|
|
81
|
-
out = decorate(result)
|
|
82
|
-
entry = {
|
|
83
|
-
"kind": str(kind or "provider"),
|
|
84
|
-
"provider_id": str(provider_id or ""),
|
|
85
|
-
"model": str(model or ""),
|
|
86
|
-
"status": str(out.get("status") or "failed"),
|
|
87
|
-
"ok": bool(out.get("ok")),
|
|
88
|
-
"evaluated_at": out["evaluated_at"],
|
|
89
|
-
"expires_at": out["expires_at"],
|
|
90
|
-
"protocol": str(protocol or ""),
|
|
91
|
-
"key_id": str(key_id or result.get("key_id") or ""),
|
|
92
|
-
"requested_model": str(requested_model or model or ""),
|
|
93
|
-
"served_model": str(served_model or ""),
|
|
94
|
-
}
|
|
95
|
-
with _LOCK:
|
|
96
|
-
data = _read()
|
|
97
|
-
data.setdefault("entries", {})[key(
|
|
98
|
-
kind, provider_id, model, protocol, key_id or result.get("key_id") or "")] = entry
|
|
99
|
-
_write(data)
|
|
100
|
-
return out
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def invalidate_provider(provider_id: str, model: str = "",
|
|
104
|
-
*, reason: str = "health_failure") -> None:
|
|
105
|
-
"""Invalidate one model, or all conclusions, after a health event."""
|
|
106
|
-
provider_id = str(provider_id or "").strip()
|
|
107
|
-
if not provider_id:
|
|
108
|
-
return
|
|
109
|
-
with _LOCK:
|
|
110
|
-
data = _read()
|
|
111
|
-
at = time.time()
|
|
112
|
-
invalidations = data.setdefault("invalidated", {})
|
|
113
|
-
invalidations[provider_id] = {
|
|
114
|
-
"at": at, "reason": str(reason or "health_failure")[:80]}
|
|
115
|
-
if model:
|
|
116
|
-
invalidations[key("model", provider_id, model)] = {
|
|
117
|
-
"at": at, "reason": str(reason or "health_failure")[:80]}
|
|
118
|
-
_write(data)
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def _safe_float(value, default=0.0) -> float:
|
|
122
|
-
try:
|
|
123
|
-
result = float(value)
|
|
124
|
-
return result if math.isfinite(result) else float(default)
|
|
125
|
-
except (TypeError, ValueError):
|
|
126
|
-
return float(default)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
def get(kind: str, provider_id: str, model: str = "", *, now=None):
|
|
130
|
-
"""Read an evaluation, returning a stale marker after TTL/health expiry."""
|
|
131
|
-
now = time.time() if now is None else float(now)
|
|
132
|
-
with _LOCK:
|
|
133
|
-
data = _read()
|
|
134
|
-
entries = data.get("entries") or {}
|
|
135
|
-
base_key = key(kind, provider_id, model)
|
|
136
|
-
entry = entries.get(base_key)
|
|
137
|
-
matches = [value for name, value in entries.items()
|
|
138
|
-
if str(name).startswith(base_key + "|") and isinstance(value, dict)]
|
|
139
|
-
candidates = ([entry] if isinstance(entry, dict) else []) + matches
|
|
140
|
-
entry = max(candidates, key=lambda value: _safe_float(value.get("evaluated_at")),
|
|
141
|
-
default=None)
|
|
142
|
-
if not isinstance(entry, dict):
|
|
143
|
-
return None
|
|
144
|
-
out = dict(entry)
|
|
145
|
-
invalidated = data.get("invalidated") or {}
|
|
146
|
-
exact_invalid = invalidated.get(key(kind, provider_id, model)) or {}
|
|
147
|
-
provider_invalid = invalidated.get(str(provider_id or "")) or {}
|
|
148
|
-
invalid = max((candidate for candidate in (exact_invalid, provider_invalid)
|
|
149
|
-
if isinstance(candidate, dict)),
|
|
150
|
-
key=lambda candidate: _safe_float(candidate.get("at")),
|
|
151
|
-
default={})
|
|
152
|
-
invalid_at = _safe_float(invalid.get("at"))
|
|
153
|
-
expires_at = _safe_float(out.get("expires_at"))
|
|
154
|
-
stale_reason = ""
|
|
155
|
-
if invalid_at and invalid_at >= _safe_float(out.get("evaluated_at")):
|
|
156
|
-
stale_reason = str(invalid.get("reason") or "health_failure")
|
|
157
|
-
elif expires_at <= now:
|
|
158
|
-
stale_reason = "ttl_expired"
|
|
159
|
-
if stale_reason:
|
|
160
|
-
out["fresh"] = False
|
|
161
|
-
out["ok"] = False
|
|
162
|
-
out["status"] = "stale"
|
|
163
|
-
out["stale_reason"] = stale_reason
|
|
164
|
-
else:
|
|
165
|
-
out["fresh"] = True
|
|
166
|
-
return out
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
def reset_for_tests() -> None:
|
|
170
|
-
with _LOCK:
|
|
171
|
-
try:
|
|
172
|
-
_path().unlink()
|
|
173
|
-
except OSError:
|
|
174
|
-
pass
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Expiring model/provider evaluation conclusions.
|
|
3
|
+
|
|
4
|
+
An evaluation is evidence captured at a point in time, not a permanent
|
|
5
|
+
capability claim. Results are kept as a small, content-free local ledger so
|
|
6
|
+
the UI or a router can distinguish a fresh ``passed`` result from an expired
|
|
7
|
+
one. A provider health failure invalidates matching conclusions immediately;
|
|
8
|
+
the health probe can show recovery, but only a fresh evaluation restores
|
|
9
|
+
``passed``.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
DEFAULT_TTL_SECONDS = 24 * 60 * 60
|
|
21
|
+
_LOCK = threading.RLock()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _path() -> Path:
|
|
25
|
+
from . import paths
|
|
26
|
+
return Path(paths.DATA_DIR) / "evaluations.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def ttl_seconds() -> float:
|
|
30
|
+
try:
|
|
31
|
+
return max(60.0, float(os.environ.get(
|
|
32
|
+
"TUTTI_EVALUATION_TTL_S", DEFAULT_TTL_SECONDS)))
|
|
33
|
+
except (TypeError, ValueError):
|
|
34
|
+
return float(DEFAULT_TTL_SECONDS)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _read() -> dict:
|
|
38
|
+
try:
|
|
39
|
+
value = json.loads(_path().read_text(encoding="utf-8"))
|
|
40
|
+
return value if isinstance(value, dict) else {}
|
|
41
|
+
except (OSError, json.JSONDecodeError):
|
|
42
|
+
return {}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _write(value: dict) -> None:
|
|
46
|
+
path = _path()
|
|
47
|
+
try:
|
|
48
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
tmp = path.with_suffix(".tmp")
|
|
50
|
+
tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2),
|
|
51
|
+
encoding="utf-8")
|
|
52
|
+
tmp.replace(path)
|
|
53
|
+
except OSError:
|
|
54
|
+
# Evaluation is telemetry. A read-only data directory must not turn
|
|
55
|
+
# a successful model call into a task failure.
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def key(kind: str, provider_id: str, model: str = "", protocol: str = "",
|
|
60
|
+
key_id: str = "") -> str:
|
|
61
|
+
base = "%s|%s|%s" % (str(kind or "provider"),
|
|
62
|
+
str(provider_id or ""), str(model or ""))
|
|
63
|
+
suffix = "|".join((str(protocol or ""), str(key_id or "")))
|
|
64
|
+
return base if not suffix.strip("|") else base + "|" + suffix
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def decorate(result: dict, *, now=None) -> dict:
|
|
68
|
+
"""Attach an evaluated-at timestamp and expiry to an API response."""
|
|
69
|
+
out = dict(result or {})
|
|
70
|
+
now = time.time() if now is None else float(now)
|
|
71
|
+
out["evaluated_at"] = now
|
|
72
|
+
out["expires_at"] = now + ttl_seconds()
|
|
73
|
+
out["fresh"] = True
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def record(kind: str, provider_id: str, model: str, result: dict,
|
|
78
|
+
*, protocol: str = "", requested_model: str = "",
|
|
79
|
+
served_model: str = "", key_id: str = "") -> dict:
|
|
80
|
+
"""Persist safe metadata for one completed evaluation and return it."""
|
|
81
|
+
out = decorate(result)
|
|
82
|
+
entry = {
|
|
83
|
+
"kind": str(kind or "provider"),
|
|
84
|
+
"provider_id": str(provider_id or ""),
|
|
85
|
+
"model": str(model or ""),
|
|
86
|
+
"status": str(out.get("status") or "failed"),
|
|
87
|
+
"ok": bool(out.get("ok")),
|
|
88
|
+
"evaluated_at": out["evaluated_at"],
|
|
89
|
+
"expires_at": out["expires_at"],
|
|
90
|
+
"protocol": str(protocol or ""),
|
|
91
|
+
"key_id": str(key_id or result.get("key_id") or ""),
|
|
92
|
+
"requested_model": str(requested_model or model or ""),
|
|
93
|
+
"served_model": str(served_model or ""),
|
|
94
|
+
}
|
|
95
|
+
with _LOCK:
|
|
96
|
+
data = _read()
|
|
97
|
+
data.setdefault("entries", {})[key(
|
|
98
|
+
kind, provider_id, model, protocol, key_id or result.get("key_id") or "")] = entry
|
|
99
|
+
_write(data)
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def invalidate_provider(provider_id: str, model: str = "",
|
|
104
|
+
*, reason: str = "health_failure") -> None:
|
|
105
|
+
"""Invalidate one model, or all conclusions, after a health event."""
|
|
106
|
+
provider_id = str(provider_id or "").strip()
|
|
107
|
+
if not provider_id:
|
|
108
|
+
return
|
|
109
|
+
with _LOCK:
|
|
110
|
+
data = _read()
|
|
111
|
+
at = time.time()
|
|
112
|
+
invalidations = data.setdefault("invalidated", {})
|
|
113
|
+
invalidations[provider_id] = {
|
|
114
|
+
"at": at, "reason": str(reason or "health_failure")[:80]}
|
|
115
|
+
if model:
|
|
116
|
+
invalidations[key("model", provider_id, model)] = {
|
|
117
|
+
"at": at, "reason": str(reason or "health_failure")[:80]}
|
|
118
|
+
_write(data)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _safe_float(value, default=0.0) -> float:
|
|
122
|
+
try:
|
|
123
|
+
result = float(value)
|
|
124
|
+
return result if math.isfinite(result) else float(default)
|
|
125
|
+
except (TypeError, ValueError):
|
|
126
|
+
return float(default)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def get(kind: str, provider_id: str, model: str = "", *, now=None):
|
|
130
|
+
"""Read an evaluation, returning a stale marker after TTL/health expiry."""
|
|
131
|
+
now = time.time() if now is None else float(now)
|
|
132
|
+
with _LOCK:
|
|
133
|
+
data = _read()
|
|
134
|
+
entries = data.get("entries") or {}
|
|
135
|
+
base_key = key(kind, provider_id, model)
|
|
136
|
+
entry = entries.get(base_key)
|
|
137
|
+
matches = [value for name, value in entries.items()
|
|
138
|
+
if str(name).startswith(base_key + "|") and isinstance(value, dict)]
|
|
139
|
+
candidates = ([entry] if isinstance(entry, dict) else []) + matches
|
|
140
|
+
entry = max(candidates, key=lambda value: _safe_float(value.get("evaluated_at")),
|
|
141
|
+
default=None)
|
|
142
|
+
if not isinstance(entry, dict):
|
|
143
|
+
return None
|
|
144
|
+
out = dict(entry)
|
|
145
|
+
invalidated = data.get("invalidated") or {}
|
|
146
|
+
exact_invalid = invalidated.get(key(kind, provider_id, model)) or {}
|
|
147
|
+
provider_invalid = invalidated.get(str(provider_id or "")) or {}
|
|
148
|
+
invalid = max((candidate for candidate in (exact_invalid, provider_invalid)
|
|
149
|
+
if isinstance(candidate, dict)),
|
|
150
|
+
key=lambda candidate: _safe_float(candidate.get("at")),
|
|
151
|
+
default={})
|
|
152
|
+
invalid_at = _safe_float(invalid.get("at"))
|
|
153
|
+
expires_at = _safe_float(out.get("expires_at"))
|
|
154
|
+
stale_reason = ""
|
|
155
|
+
if invalid_at and invalid_at >= _safe_float(out.get("evaluated_at")):
|
|
156
|
+
stale_reason = str(invalid.get("reason") or "health_failure")
|
|
157
|
+
elif expires_at <= now:
|
|
158
|
+
stale_reason = "ttl_expired"
|
|
159
|
+
if stale_reason:
|
|
160
|
+
out["fresh"] = False
|
|
161
|
+
out["ok"] = False
|
|
162
|
+
out["status"] = "stale"
|
|
163
|
+
out["stale_reason"] = stale_reason
|
|
164
|
+
else:
|
|
165
|
+
out["fresh"] = True
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def reset_for_tests() -> None:
|
|
170
|
+
with _LOCK:
|
|
171
|
+
try:
|
|
172
|
+
_path().unlink()
|
|
173
|
+
except OSError:
|
|
174
|
+
pass
|