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
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""缺陷复盘报告(defect_retro,借鉴 zl2237/test-defect-retrospective)。
|
|
3
|
+
|
|
4
|
+
禅道/Jira 缺陷导出 → 产品/开发/测试三视角复盘报告。
|
|
5
|
+
数据不走网络:缺陷导出(CSV)作为任务附件注入上下文,这里只负责
|
|
6
|
+
组装分析框架提示词。无附件时提示词会点名要求补附件——报告框架
|
|
7
|
+
照常输出,不留静默空转。
|
|
8
|
+
|
|
9
|
+
对照参考实现的取舍:它是本地脚本确定性算指标(analyzer 同输入同输出),
|
|
10
|
+
我们是 direct 引擎一次性成稿——先跑通「有复盘产物」这一步,指标口径
|
|
11
|
+
固化(状态/严重度归一在提示词里给锚)后续按需升档。
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def retro_prompt(goal):
|
|
17
|
+
"""组装缺陷复盘三视角提示词。纯框架无抓取,恒有返回值。"""
|
|
18
|
+
return (
|
|
19
|
+
"你是资深质量效能专家,负责输出一份缺陷复盘报告。\n\n"
|
|
20
|
+
"## 输入\n"
|
|
21
|
+
"用户会提供缺陷平台导出数据(推荐禅道/Jira 导出 CSV 作为任务附件;"
|
|
22
|
+
"Excel 二进制读不了,请导出 CSV)。字段口径以「标题、严重程度、"
|
|
23
|
+
"状态、创建日期、所属模块、解决方案、关闭原因、责任人」为锚,"
|
|
24
|
+
"缺失字段按实际有的算并在报告中声明口径。\n\n"
|
|
25
|
+
"## 用户关注点\n%s\n\n"
|
|
26
|
+
"## 你的产出(Markdown 报告)\n"
|
|
27
|
+
"1. **整体画像**:缺陷总量、严重度分布、状态分布、时间走势"
|
|
28
|
+
"(按创建日期聚合)、模块 Top5 集中度——只用表格+一句话结论,不复述原始数据\n"
|
|
29
|
+
"2. **产品视角**:需求类缺陷(描述不清/变更频繁/逻辑矛盾)占比与典型例;"
|
|
30
|
+
"类需求缺陷(被当 Bug 提的优化)点名\n"
|
|
31
|
+
"3. **开发视角**:根因聚类(编码疏忽/设计缺陷/环境/数据/回归)占比;"
|
|
32
|
+
"重复回归的模块点名;修复后又被激活的缺陷单列\n"
|
|
33
|
+
"4. **测试视角**:发现阶段分布(提测后/上线后/用户反馈);漏测推测"
|
|
34
|
+
"(上线后才暴露的缺陷缺什么用例);严重度与发现时长的错配\n"
|
|
35
|
+
"5. **改进动作**:每个视角 2-3 条,带建议责任角色与可验证的完成标准,"
|
|
36
|
+
"拒绝「加强沟通」类空话\n\n"
|
|
37
|
+
"## 纪律\n"
|
|
38
|
+
"- 所有数字必须从提供的导出数据里数出来,数不出的指标写「数据未提供」"
|
|
39
|
+
"而不是编造\n"
|
|
40
|
+
"- 若上下文里没有任何缺陷数据,直接说明需要附带导出 CSV 并给出导出步骤"
|
|
41
|
+
"(禅道:产品-缺陷-导出-CSV),不要硬写报告\n"
|
|
42
|
+
"- 直接输出报告,不要复述本提示词"
|
|
43
|
+
% (goal or "(用户未指定,按全量缺陷复盘)"))
|
package/app/core/diagnostics.py
CHANGED
|
@@ -1,115 +1,115 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""运行时不变量注册表:质量闸门从 pytest 测试期提升到运行时。
|
|
3
|
-
|
|
4
|
-
设计稿:docs/migration/01-defense-patterns.md §5F。
|
|
5
|
-
参考 dsh packages/runtime-diagnostics/invariants/src/index.ts:
|
|
6
|
-
enabled/package_allowlist/package_blocklist 三过滤;失败抛 InvariantError 含 packageName。
|
|
7
|
-
|
|
8
|
-
CodeBee 实施简化为单文件 + pytest 钩子(设计稿说明);register(name, fn) 注册断言,
|
|
9
|
-
run_for(source, ctx) 在指定 source 下跑所有断言并返回失败列表。
|
|
10
|
-
"""
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
|
-
import logging
|
|
14
|
-
import threading
|
|
15
|
-
from typing import Optional
|
|
16
|
-
|
|
17
|
-
log = logging.getLogger(__name__)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class InvariantError(Exception):
|
|
21
|
-
def __init__(self, source: str, check_name: str, msg: str):
|
|
22
|
-
super().__init__(f"[{source}/{check_name}] {msg}")
|
|
23
|
-
self.source = source
|
|
24
|
-
self.check_name = check_name
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class InvariantRegistry:
|
|
28
|
-
"""按 source 分组的运行时断言注册表。
|
|
29
|
-
|
|
30
|
-
source 是来源标识(如 "pipeline"/"store"),name 是断言名;
|
|
31
|
-
fn(ctx) -> Optional[str] 返回 None 表示通过,返回字符串即失败消息。
|
|
32
|
-
"""
|
|
33
|
-
|
|
34
|
-
def __init__(self):
|
|
35
|
-
self._lock = threading.Lock()
|
|
36
|
-
self._checks: dict = {} # source -> {name: fn}
|
|
37
|
-
|
|
38
|
-
def register(self, source: str, name: str, fn):
|
|
39
|
-
with self._lock:
|
|
40
|
-
self._checks.setdefault(source, {})[name] = fn
|
|
41
|
-
log.debug("invariant registered: %s/%s", source, name)
|
|
42
|
-
|
|
43
|
-
def unregister(self, source: str, name: str = None):
|
|
44
|
-
"""移除断言;name=None 时清空整个 source。"""
|
|
45
|
-
with self._lock:
|
|
46
|
-
if source not in self._checks:
|
|
47
|
-
return
|
|
48
|
-
if name is None:
|
|
49
|
-
del self._checks[source]
|
|
50
|
-
else:
|
|
51
|
-
self._checks[source].pop(name, None)
|
|
52
|
-
|
|
53
|
-
def run_for(self, source: str, ctx: dict, *, fail_fast: bool = False):
|
|
54
|
-
"""在 source 下跑所有断言。
|
|
55
|
-
|
|
56
|
-
Returns:
|
|
57
|
-
[(source, name, message), ...] 失败列表(空 = 全过)。
|
|
58
|
-
|
|
59
|
-
Raises:
|
|
60
|
-
InvariantError: fail_fast=True 且首个失败。
|
|
61
|
-
"""
|
|
62
|
-
fails = []
|
|
63
|
-
with self._lock:
|
|
64
|
-
checks = dict(self._checks.get(source, {}))
|
|
65
|
-
for name, fn in checks.items():
|
|
66
|
-
try:
|
|
67
|
-
msg = fn(ctx)
|
|
68
|
-
except Exception as e:
|
|
69
|
-
msg = f"check raised: {e!r}"
|
|
70
|
-
if msg:
|
|
71
|
-
fails.append((source, name, msg))
|
|
72
|
-
log.warning("invariant FAIL: %s/%s: %s", source, name, msg)
|
|
73
|
-
if fail_fast:
|
|
74
|
-
raise InvariantError(source, name, msg)
|
|
75
|
-
return fails
|
|
76
|
-
|
|
77
|
-
def list(self, source: Optional[str] = None):
|
|
78
|
-
"""列出已注册的 source/name;source=None 时全部。"""
|
|
79
|
-
with self._lock:
|
|
80
|
-
if source is None:
|
|
81
|
-
return [(s, n) for s, m in self._checks.items() for n in m]
|
|
82
|
-
return [(source, n) for n in self._checks.get(source, {})]
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
invariants = InvariantRegistry() # 单例
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
# === 默认 invariants ===
|
|
89
|
-
def register_default_checks():
|
|
90
|
-
"""注册 CodeBee 默认运行时断言。"""
|
|
91
|
-
|
|
92
|
-
def review_no_all_fail_zero(ctx):
|
|
93
|
-
"""评审全部 0 分但 run 标 success → 不允许(已锁 test_quality_gates:62-75)。"""
|
|
94
|
-
if (ctx.get("review_scores")
|
|
95
|
-
and all(s == 0 for s in ctx["review_scores"])
|
|
96
|
-
and ctx.get("final_status") == "success"):
|
|
97
|
-
return "评审全部 0 分但 run 标 success"
|
|
98
|
-
return None
|
|
99
|
-
|
|
100
|
-
def step_count_consistency(ctx):
|
|
101
|
-
"""实际 step 数与预期不一致。"""
|
|
102
|
-
if ctx.get("actual_steps") != ctx.get("expected_steps"):
|
|
103
|
-
return f"step count {ctx.get('actual_steps')} != expected {ctx.get('expected_steps')}"
|
|
104
|
-
return None
|
|
105
|
-
|
|
106
|
-
def ok_but_error_code(ctx):
|
|
107
|
-
"""step 级:ok=True 却带非空 error_code —— 解析降级(如 codex 空输出
|
|
108
|
-
回落 stdout 尾部)被当成功,值得告警复核。"""
|
|
109
|
-
if ctx.get("ok") and ctx.get("error_code"):
|
|
110
|
-
return "step 标记成功但携带 error_code=%s(疑似降级输出)" % ctx["error_code"]
|
|
111
|
-
return None
|
|
112
|
-
|
|
113
|
-
invariants.register("pipeline", "review_no_all_fail_zero", review_no_all_fail_zero)
|
|
114
|
-
invariants.register("pipeline", "step_count_consistency", step_count_consistency)
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""运行时不变量注册表:质量闸门从 pytest 测试期提升到运行时。
|
|
3
|
+
|
|
4
|
+
设计稿:docs/migration/01-defense-patterns.md §5F。
|
|
5
|
+
参考 dsh packages/runtime-diagnostics/invariants/src/index.ts:
|
|
6
|
+
enabled/package_allowlist/package_blocklist 三过滤;失败抛 InvariantError 含 packageName。
|
|
7
|
+
|
|
8
|
+
CodeBee 实施简化为单文件 + pytest 钩子(设计稿说明);register(name, fn) 注册断言,
|
|
9
|
+
run_for(source, ctx) 在指定 source 下跑所有断言并返回失败列表。
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
import threading
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class InvariantError(Exception):
|
|
21
|
+
def __init__(self, source: str, check_name: str, msg: str):
|
|
22
|
+
super().__init__(f"[{source}/{check_name}] {msg}")
|
|
23
|
+
self.source = source
|
|
24
|
+
self.check_name = check_name
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class InvariantRegistry:
|
|
28
|
+
"""按 source 分组的运行时断言注册表。
|
|
29
|
+
|
|
30
|
+
source 是来源标识(如 "pipeline"/"store"),name 是断言名;
|
|
31
|
+
fn(ctx) -> Optional[str] 返回 None 表示通过,返回字符串即失败消息。
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self):
|
|
35
|
+
self._lock = threading.Lock()
|
|
36
|
+
self._checks: dict = {} # source -> {name: fn}
|
|
37
|
+
|
|
38
|
+
def register(self, source: str, name: str, fn):
|
|
39
|
+
with self._lock:
|
|
40
|
+
self._checks.setdefault(source, {})[name] = fn
|
|
41
|
+
log.debug("invariant registered: %s/%s", source, name)
|
|
42
|
+
|
|
43
|
+
def unregister(self, source: str, name: str = None):
|
|
44
|
+
"""移除断言;name=None 时清空整个 source。"""
|
|
45
|
+
with self._lock:
|
|
46
|
+
if source not in self._checks:
|
|
47
|
+
return
|
|
48
|
+
if name is None:
|
|
49
|
+
del self._checks[source]
|
|
50
|
+
else:
|
|
51
|
+
self._checks[source].pop(name, None)
|
|
52
|
+
|
|
53
|
+
def run_for(self, source: str, ctx: dict, *, fail_fast: bool = False):
|
|
54
|
+
"""在 source 下跑所有断言。
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
[(source, name, message), ...] 失败列表(空 = 全过)。
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
InvariantError: fail_fast=True 且首个失败。
|
|
61
|
+
"""
|
|
62
|
+
fails = []
|
|
63
|
+
with self._lock:
|
|
64
|
+
checks = dict(self._checks.get(source, {}))
|
|
65
|
+
for name, fn in checks.items():
|
|
66
|
+
try:
|
|
67
|
+
msg = fn(ctx)
|
|
68
|
+
except Exception as e:
|
|
69
|
+
msg = f"check raised: {e!r}"
|
|
70
|
+
if msg:
|
|
71
|
+
fails.append((source, name, msg))
|
|
72
|
+
log.warning("invariant FAIL: %s/%s: %s", source, name, msg)
|
|
73
|
+
if fail_fast:
|
|
74
|
+
raise InvariantError(source, name, msg)
|
|
75
|
+
return fails
|
|
76
|
+
|
|
77
|
+
def list(self, source: Optional[str] = None):
|
|
78
|
+
"""列出已注册的 source/name;source=None 时全部。"""
|
|
79
|
+
with self._lock:
|
|
80
|
+
if source is None:
|
|
81
|
+
return [(s, n) for s, m in self._checks.items() for n in m]
|
|
82
|
+
return [(source, n) for n in self._checks.get(source, {})]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
invariants = InvariantRegistry() # 单例
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# === 默认 invariants ===
|
|
89
|
+
def register_default_checks():
|
|
90
|
+
"""注册 CodeBee 默认运行时断言。"""
|
|
91
|
+
|
|
92
|
+
def review_no_all_fail_zero(ctx):
|
|
93
|
+
"""评审全部 0 分但 run 标 success → 不允许(已锁 test_quality_gates:62-75)。"""
|
|
94
|
+
if (ctx.get("review_scores")
|
|
95
|
+
and all(s == 0 for s in ctx["review_scores"])
|
|
96
|
+
and ctx.get("final_status") == "success"):
|
|
97
|
+
return "评审全部 0 分但 run 标 success"
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
def step_count_consistency(ctx):
|
|
101
|
+
"""实际 step 数与预期不一致。"""
|
|
102
|
+
if ctx.get("actual_steps") != ctx.get("expected_steps"):
|
|
103
|
+
return f"step count {ctx.get('actual_steps')} != expected {ctx.get('expected_steps')}"
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
def ok_but_error_code(ctx):
|
|
107
|
+
"""step 级:ok=True 却带非空 error_code —— 解析降级(如 codex 空输出
|
|
108
|
+
回落 stdout 尾部)被当成功,值得告警复核。"""
|
|
109
|
+
if ctx.get("ok") and ctx.get("error_code"):
|
|
110
|
+
return "step 标记成功但携带 error_code=%s(疑似降级输出)" % ctx["error_code"]
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
invariants.register("pipeline", "review_no_all_fail_zero", review_no_all_fail_zero)
|
|
114
|
+
invariants.register("pipeline", "step_count_consistency", step_count_consistency)
|
|
115
115
|
invariants.register("step", "ok_but_error_code", ok_but_error_code)
|
package/app/core/dispatch.py
CHANGED
|
@@ -1,173 +1,173 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""统一调度评分:任务画像、CLI 亲和度与模型链排序。
|
|
3
|
-
|
|
4
|
-
调用方先完成协议、启停、健康、密钥等硬约束过滤,再把可用候选交给这里评分;
|
|
5
|
-
静态能力与近期用量台账只提供软信号,相同分数保持用户原顺序。
|
|
6
|
-
"""
|
|
7
|
-
from __future__ import annotations
|
|
8
|
-
|
|
9
|
-
import math
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
TYPE_DIMENSIONS = {
|
|
13
|
-
"direct": "reasoning",
|
|
14
|
-
"code": "coding",
|
|
15
|
-
"novel": "writing",
|
|
16
|
-
"serial_novel": "writing",
|
|
17
|
-
"article": "writing",
|
|
18
|
-
"video_script": "writing",
|
|
19
|
-
"doc": "writing",
|
|
20
|
-
"translation": "writing",
|
|
21
|
-
"rank_scan": "reasoning",
|
|
22
|
-
"research": "reasoning",
|
|
23
|
-
"speech": "writing",
|
|
24
|
-
"weekly_report": "writing",
|
|
25
|
-
"email": "writing",
|
|
26
|
-
"tech_proposal": "reasoning",
|
|
27
|
-
"resume": "writing",
|
|
28
|
-
"bid_doc": "writing", # 标书:正文应答写作量大(合规判断由契约规则约束)
|
|
29
|
-
"zentao": "coding",
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
_KIND_AFFINITY = {
|
|
33
|
-
"coding": {"codex": 10, "aider": 8, "opencode": 7, "qwen": 6,
|
|
34
|
-
"claude": 5, "generic": 2},
|
|
35
|
-
"writing": {"claude": 10, "qwen": 7, "generic": 5, "codex": 3,
|
|
36
|
-
"opencode": 2, "aider": 0},
|
|
37
|
-
"reasoning": {"claude": 9, "codex": 8, "qwen": 6, "opencode": 4,
|
|
38
|
-
"generic": 3, "aider": 1},
|
|
39
|
-
"vision": {"codex": 10, "claude": 8, "qwen": 5, "opencode": 2,
|
|
40
|
-
"generic": 1, "aider": 0},
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
_TIER_SCORE = {
|
|
44
|
-
"easy": {"budget": 18.0, "standard": 8.0, "premium": -6.0},
|
|
45
|
-
"default": {"budget": 2.0, "standard": 6.0, "premium": 5.0},
|
|
46
|
-
"hard": {"budget": -8.0, "standard": 4.0, "premium": 12.0},
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def task_dimension(task_type, role=""):
|
|
51
|
-
"""把预置任务与步骤角色归一为 writing/coding/reasoning/vision。"""
|
|
52
|
-
ttype = str(task_type or "").strip().lower()
|
|
53
|
-
role = str(role or "").strip().lower()
|
|
54
|
-
if ttype in ("writing", "coding", "reasoning", "vision"):
|
|
55
|
-
return ttype
|
|
56
|
-
if role in ("plan", "review", "critique", "selector", "qa") \
|
|
57
|
-
or "review" in role or "critique" in role:
|
|
58
|
-
return "reasoning"
|
|
59
|
-
return TYPE_DIMENSIONS.get(ttype, "reasoning")
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def agent_affinity(kind, task_type, role=""):
|
|
63
|
-
"""CLI 类型对任务维度的温和偏好;只作加分,不覆盖健康与历史信号。"""
|
|
64
|
-
dim = task_dimension(task_type, role)
|
|
65
|
-
score = float((_KIND_AFFINITY.get(dim) or {}).get(kind, 0))
|
|
66
|
-
if role == "review" or "critique" in str(role or ""):
|
|
67
|
-
score += {"claude": 4, "codex": 3, "qwen": 2}.get(kind, 0)
|
|
68
|
-
return score, "%s 匹配 %+.1f" % (dim, score)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def _model_meta(provider, model):
|
|
72
|
-
for item in (provider or {}).get("models") or []:
|
|
73
|
-
if isinstance(item, dict) and item.get("name") == model:
|
|
74
|
-
return item
|
|
75
|
-
return {}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def _price_score(pricing, model, difficulty):
|
|
79
|
-
price = (pricing or {}).get(model) or {}
|
|
80
|
-
try:
|
|
81
|
-
# 输出通常比输入贵且更影响整步成本,按 2 倍权重估算。
|
|
82
|
-
blended = max(0.0, float(price.get("in") or 0.0)
|
|
83
|
-
+ 2.0 * float(price.get("out") or 0.0))
|
|
84
|
-
except (TypeError, ValueError):
|
|
85
|
-
return 0.0, "价格未知"
|
|
86
|
-
if blended <= 0:
|
|
87
|
-
return 0.0, "价格未知"
|
|
88
|
-
magnitude = max(0.0, math.log10(blended + 1.0))
|
|
89
|
-
score = -min(18.0, magnitude * (7.0 if difficulty == "easy" else 2.0))
|
|
90
|
-
return score, "估算价 %.3g(%+.1f)" % (blended, score)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _online_model_bonus(entry, task_type, role):
|
|
94
|
-
"""把真实运行指标作为模型链软信号,硬约束仍由调用方负责。"""
|
|
95
|
-
try:
|
|
96
|
-
from . import usage
|
|
97
|
-
metrics = usage.routing_stats(
|
|
98
|
-
task_type=task_type, role=role,
|
|
99
|
-
provider=entry.get("provider_id") or "",
|
|
100
|
-
model=entry.get("model") or "")
|
|
101
|
-
samples = int(metrics.get("samples") or 0)
|
|
102
|
-
if not samples:
|
|
103
|
-
return 0.0, ""
|
|
104
|
-
rate = float(metrics.get("success_rate") or 0.0)
|
|
105
|
-
success_score = max(-6.0, min(6.0, (rate - 0.75) * 18.0))
|
|
106
|
-
p95 = max(0.0, float(metrics.get("p95_duration_s") or 0.0))
|
|
107
|
-
# 模型链也必须让真实延迟影响排序,不能让 P95 数分钟的链靠静态质量分
|
|
108
|
-
# 长期压在十几秒的健康链前面。
|
|
109
|
-
latency_score = -min(12.0, max(0.0, (p95 - 30.0) / 8.0))
|
|
110
|
-
cost = max(0.0, float(metrics.get("avg_cost_usd") or 0.0))
|
|
111
|
-
cost_score = -min(3.0, max(0.0, (cost - 0.01) / 0.01))
|
|
112
|
-
total = round(success_score + latency_score + cost_score, 2)
|
|
113
|
-
success_samples = int(metrics.get("success_samples") or samples)
|
|
114
|
-
reason = ("在线 %d/%d 验收成功(%+.1f),P95 %.1fs(%+.1f),均价 $%.4f(%+.1f)"
|
|
115
|
-
% (int(metrics.get("successes") or 0), success_samples,
|
|
116
|
-
success_score, p95, latency_score, cost, cost_score))
|
|
117
|
-
return total, reason
|
|
118
|
-
except Exception:
|
|
119
|
-
return 0.0, ""
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
def score_model_entry(entry, providers, pricing, difficulty, task_type="", role=""):
|
|
123
|
-
"""给已通过硬约束的模型链条目评分,返回 (score, explanation)。"""
|
|
124
|
-
provider = (providers or {}).get(entry.get("provider_id")) \
|
|
125
|
-
or entry.get("provider") or {}
|
|
126
|
-
model = entry.get("model") or ""
|
|
127
|
-
meta = _model_meta(provider, model)
|
|
128
|
-
try:
|
|
129
|
-
priority = max(1, int(meta.get("priority") or 99))
|
|
130
|
-
except (TypeError, ValueError):
|
|
131
|
-
priority = 99
|
|
132
|
-
quality = 0.0 if priority == 99 else max(-8.0, 20.0 - (priority - 1) * 4.0)
|
|
133
|
-
tier = meta.get("tier") or provider.get("tier") or "standard"
|
|
134
|
-
tier_score = (_TIER_SCORE.get(difficulty) or {}).get(tier, 0.0)
|
|
135
|
-
price_score, price_reason = _price_score(pricing, model, difficulty)
|
|
136
|
-
dim = task_dimension(task_type, role)
|
|
137
|
-
strengths = provider.get("strengths") if isinstance(provider.get("strengths"), list) else []
|
|
138
|
-
strength_score = 10.0 if dim in strengths else 0.0
|
|
139
|
-
if difficulty == "easy":
|
|
140
|
-
quality *= 0.25
|
|
141
|
-
elif difficulty != "hard":
|
|
142
|
-
# 普通任务兼顾质量、成本与能力匹配;是否真的重排由调用方决定,
|
|
143
|
-
# 因而手工链仍可保持原顺序,自动推荐则能使用这组平衡分。
|
|
144
|
-
quality *= 0.65
|
|
145
|
-
vision_score = 0.0
|
|
146
|
-
if dim == "vision":
|
|
147
|
-
vision_score = 24.0 if meta.get("image_in") else -24.0
|
|
148
|
-
online_score, online_reason = _online_model_bonus(entry, task_type, role)
|
|
149
|
-
total = quality + tier_score + price_score + strength_score + vision_score + online_score
|
|
150
|
-
reason = ("质量 %+.1f,档位 %s %+.1f,%s,能力 %s %+.1f%s%s"
|
|
151
|
-
% (quality, tier, tier_score, price_reason, dim,
|
|
152
|
-
strength_score + vision_score,
|
|
153
|
-
"," if online_reason else "", online_reason))
|
|
154
|
-
return round(total, 2), reason
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
def rank_model_entries(entries, providers, pricing, difficulty,
|
|
158
|
-
task_type="", role="", force=False):
|
|
159
|
-
"""稳定排序模型链并返回脱敏决策明细;default 难度保持人工顺序。"""
|
|
160
|
-
rows = []
|
|
161
|
-
for index, entry in enumerate(entries or []):
|
|
162
|
-
score, reason = score_model_entry(
|
|
163
|
-
entry, providers, pricing, difficulty, task_type, role)
|
|
164
|
-
rows.append((score, index, entry, reason))
|
|
165
|
-
if difficulty in ("easy", "hard") or force:
|
|
166
|
-
rows.sort(key=lambda row: (-row[0], row[1]))
|
|
167
|
-
ranked = [row[2] for row in rows]
|
|
168
|
-
decisions = [{"provider_id": row[2].get("provider_id") or "",
|
|
169
|
-
"provider": (row[2].get("provider") or {}).get("name") or "",
|
|
170
|
-
"model": row[2].get("model") or "",
|
|
171
|
-
"score": row[0], "reason": row[3]}
|
|
172
|
-
for row in rows]
|
|
173
|
-
return ranked, decisions
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""统一调度评分:任务画像、CLI 亲和度与模型链排序。
|
|
3
|
+
|
|
4
|
+
调用方先完成协议、启停、健康、密钥等硬约束过滤,再把可用候选交给这里评分;
|
|
5
|
+
静态能力与近期用量台账只提供软信号,相同分数保持用户原顺序。
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
TYPE_DIMENSIONS = {
|
|
13
|
+
"direct": "reasoning",
|
|
14
|
+
"code": "coding",
|
|
15
|
+
"novel": "writing",
|
|
16
|
+
"serial_novel": "writing",
|
|
17
|
+
"article": "writing",
|
|
18
|
+
"video_script": "writing",
|
|
19
|
+
"doc": "writing",
|
|
20
|
+
"translation": "writing",
|
|
21
|
+
"rank_scan": "reasoning",
|
|
22
|
+
"research": "reasoning",
|
|
23
|
+
"speech": "writing",
|
|
24
|
+
"weekly_report": "writing",
|
|
25
|
+
"email": "writing",
|
|
26
|
+
"tech_proposal": "reasoning",
|
|
27
|
+
"resume": "writing",
|
|
28
|
+
"bid_doc": "writing", # 标书:正文应答写作量大(合规判断由契约规则约束)
|
|
29
|
+
"zentao": "coding",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
_KIND_AFFINITY = {
|
|
33
|
+
"coding": {"codex": 10, "aider": 8, "opencode": 7, "qwen": 6,
|
|
34
|
+
"claude": 5, "generic": 2},
|
|
35
|
+
"writing": {"claude": 10, "qwen": 7, "generic": 5, "codex": 3,
|
|
36
|
+
"opencode": 2, "aider": 0},
|
|
37
|
+
"reasoning": {"claude": 9, "codex": 8, "qwen": 6, "opencode": 4,
|
|
38
|
+
"generic": 3, "aider": 1},
|
|
39
|
+
"vision": {"codex": 10, "claude": 8, "qwen": 5, "opencode": 2,
|
|
40
|
+
"generic": 1, "aider": 0},
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_TIER_SCORE = {
|
|
44
|
+
"easy": {"budget": 18.0, "standard": 8.0, "premium": -6.0},
|
|
45
|
+
"default": {"budget": 2.0, "standard": 6.0, "premium": 5.0},
|
|
46
|
+
"hard": {"budget": -8.0, "standard": 4.0, "premium": 12.0},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def task_dimension(task_type, role=""):
|
|
51
|
+
"""把预置任务与步骤角色归一为 writing/coding/reasoning/vision。"""
|
|
52
|
+
ttype = str(task_type or "").strip().lower()
|
|
53
|
+
role = str(role or "").strip().lower()
|
|
54
|
+
if ttype in ("writing", "coding", "reasoning", "vision"):
|
|
55
|
+
return ttype
|
|
56
|
+
if role in ("plan", "review", "critique", "selector", "qa") \
|
|
57
|
+
or "review" in role or "critique" in role:
|
|
58
|
+
return "reasoning"
|
|
59
|
+
return TYPE_DIMENSIONS.get(ttype, "reasoning")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def agent_affinity(kind, task_type, role=""):
|
|
63
|
+
"""CLI 类型对任务维度的温和偏好;只作加分,不覆盖健康与历史信号。"""
|
|
64
|
+
dim = task_dimension(task_type, role)
|
|
65
|
+
score = float((_KIND_AFFINITY.get(dim) or {}).get(kind, 0))
|
|
66
|
+
if role == "review" or "critique" in str(role or ""):
|
|
67
|
+
score += {"claude": 4, "codex": 3, "qwen": 2}.get(kind, 0)
|
|
68
|
+
return score, "%s 匹配 %+.1f" % (dim, score)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _model_meta(provider, model):
|
|
72
|
+
for item in (provider or {}).get("models") or []:
|
|
73
|
+
if isinstance(item, dict) and item.get("name") == model:
|
|
74
|
+
return item
|
|
75
|
+
return {}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _price_score(pricing, model, difficulty):
|
|
79
|
+
price = (pricing or {}).get(model) or {}
|
|
80
|
+
try:
|
|
81
|
+
# 输出通常比输入贵且更影响整步成本,按 2 倍权重估算。
|
|
82
|
+
blended = max(0.0, float(price.get("in") or 0.0)
|
|
83
|
+
+ 2.0 * float(price.get("out") or 0.0))
|
|
84
|
+
except (TypeError, ValueError):
|
|
85
|
+
return 0.0, "价格未知"
|
|
86
|
+
if blended <= 0:
|
|
87
|
+
return 0.0, "价格未知"
|
|
88
|
+
magnitude = max(0.0, math.log10(blended + 1.0))
|
|
89
|
+
score = -min(18.0, magnitude * (7.0 if difficulty == "easy" else 2.0))
|
|
90
|
+
return score, "估算价 %.3g(%+.1f)" % (blended, score)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _online_model_bonus(entry, task_type, role):
|
|
94
|
+
"""把真实运行指标作为模型链软信号,硬约束仍由调用方负责。"""
|
|
95
|
+
try:
|
|
96
|
+
from . import usage
|
|
97
|
+
metrics = usage.routing_stats(
|
|
98
|
+
task_type=task_type, role=role,
|
|
99
|
+
provider=entry.get("provider_id") or "",
|
|
100
|
+
model=entry.get("model") or "")
|
|
101
|
+
samples = int(metrics.get("samples") or 0)
|
|
102
|
+
if not samples:
|
|
103
|
+
return 0.0, ""
|
|
104
|
+
rate = float(metrics.get("success_rate") or 0.0)
|
|
105
|
+
success_score = max(-6.0, min(6.0, (rate - 0.75) * 18.0))
|
|
106
|
+
p95 = max(0.0, float(metrics.get("p95_duration_s") or 0.0))
|
|
107
|
+
# 模型链也必须让真实延迟影响排序,不能让 P95 数分钟的链靠静态质量分
|
|
108
|
+
# 长期压在十几秒的健康链前面。
|
|
109
|
+
latency_score = -min(12.0, max(0.0, (p95 - 30.0) / 8.0))
|
|
110
|
+
cost = max(0.0, float(metrics.get("avg_cost_usd") or 0.0))
|
|
111
|
+
cost_score = -min(3.0, max(0.0, (cost - 0.01) / 0.01))
|
|
112
|
+
total = round(success_score + latency_score + cost_score, 2)
|
|
113
|
+
success_samples = int(metrics.get("success_samples") or samples)
|
|
114
|
+
reason = ("在线 %d/%d 验收成功(%+.1f),P95 %.1fs(%+.1f),均价 $%.4f(%+.1f)"
|
|
115
|
+
% (int(metrics.get("successes") or 0), success_samples,
|
|
116
|
+
success_score, p95, latency_score, cost, cost_score))
|
|
117
|
+
return total, reason
|
|
118
|
+
except Exception:
|
|
119
|
+
return 0.0, ""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def score_model_entry(entry, providers, pricing, difficulty, task_type="", role=""):
|
|
123
|
+
"""给已通过硬约束的模型链条目评分,返回 (score, explanation)。"""
|
|
124
|
+
provider = (providers or {}).get(entry.get("provider_id")) \
|
|
125
|
+
or entry.get("provider") or {}
|
|
126
|
+
model = entry.get("model") or ""
|
|
127
|
+
meta = _model_meta(provider, model)
|
|
128
|
+
try:
|
|
129
|
+
priority = max(1, int(meta.get("priority") or 99))
|
|
130
|
+
except (TypeError, ValueError):
|
|
131
|
+
priority = 99
|
|
132
|
+
quality = 0.0 if priority == 99 else max(-8.0, 20.0 - (priority - 1) * 4.0)
|
|
133
|
+
tier = meta.get("tier") or provider.get("tier") or "standard"
|
|
134
|
+
tier_score = (_TIER_SCORE.get(difficulty) or {}).get(tier, 0.0)
|
|
135
|
+
price_score, price_reason = _price_score(pricing, model, difficulty)
|
|
136
|
+
dim = task_dimension(task_type, role)
|
|
137
|
+
strengths = provider.get("strengths") if isinstance(provider.get("strengths"), list) else []
|
|
138
|
+
strength_score = 10.0 if dim in strengths else 0.0
|
|
139
|
+
if difficulty == "easy":
|
|
140
|
+
quality *= 0.25
|
|
141
|
+
elif difficulty != "hard":
|
|
142
|
+
# 普通任务兼顾质量、成本与能力匹配;是否真的重排由调用方决定,
|
|
143
|
+
# 因而手工链仍可保持原顺序,自动推荐则能使用这组平衡分。
|
|
144
|
+
quality *= 0.65
|
|
145
|
+
vision_score = 0.0
|
|
146
|
+
if dim == "vision":
|
|
147
|
+
vision_score = 24.0 if meta.get("image_in") else -24.0
|
|
148
|
+
online_score, online_reason = _online_model_bonus(entry, task_type, role)
|
|
149
|
+
total = quality + tier_score + price_score + strength_score + vision_score + online_score
|
|
150
|
+
reason = ("质量 %+.1f,档位 %s %+.1f,%s,能力 %s %+.1f%s%s"
|
|
151
|
+
% (quality, tier, tier_score, price_reason, dim,
|
|
152
|
+
strength_score + vision_score,
|
|
153
|
+
"," if online_reason else "", online_reason))
|
|
154
|
+
return round(total, 2), reason
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def rank_model_entries(entries, providers, pricing, difficulty,
|
|
158
|
+
task_type="", role="", force=False):
|
|
159
|
+
"""稳定排序模型链并返回脱敏决策明细;default 难度保持人工顺序。"""
|
|
160
|
+
rows = []
|
|
161
|
+
for index, entry in enumerate(entries or []):
|
|
162
|
+
score, reason = score_model_entry(
|
|
163
|
+
entry, providers, pricing, difficulty, task_type, role)
|
|
164
|
+
rows.append((score, index, entry, reason))
|
|
165
|
+
if difficulty in ("easy", "hard") or force:
|
|
166
|
+
rows.sort(key=lambda row: (-row[0], row[1]))
|
|
167
|
+
ranked = [row[2] for row in rows]
|
|
168
|
+
decisions = [{"provider_id": row[2].get("provider_id") or "",
|
|
169
|
+
"provider": (row[2].get("provider") or {}).get("name") or "",
|
|
170
|
+
"model": row[2].get("model") or "",
|
|
171
|
+
"score": row[0], "reason": row[3]}
|
|
172
|
+
for row in rows]
|
|
173
|
+
return ranked, decisions
|