doukui 0.6.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.en.md +85 -18
  2. package/README.md +32 -72
  3. package/bin/commands/help.js +2 -25
  4. package/bin/commands/plan-lint.js +105 -0
  5. package/bin/commands/verify.js +263 -0
  6. package/bin/doukui.js +3 -3
  7. package/package.json +2 -3
  8. package/plugins/core/hook-session-start/index.js +1 -1
  9. package/plugins/core/hook-skill-gate/index.js +64 -15
  10. package/plugins/core/hook-skill-gate/plugin.json +1 -1
  11. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +7 -28
  12. package/plugins/core/skill-agent-dispatcher/monitoring-reference.md +89 -0
  13. package/plugins/core/skill-agent-dispatcher/plugin.json +1 -1
  14. package/plugins/core/skill-agent-dispatcher/recovery-reference.md +132 -0
  15. package/plugins/core/skill-agent-dispatcher/roles-reference.md +9 -22
  16. package/plugins/core/skill-agent-dispatcher/skill.md +124 -796
  17. package/plugins/core/skill-agentic-loop/mirror-rules.md +95 -24
  18. package/plugins/core/skill-agentic-loop/plugin.json +2 -7
  19. package/plugins/core/skill-agentic-loop/skill.md +125 -354
  20. package/plugins/core/skill-batch-task-creator/plugin.json +1 -1
  21. package/plugins/core/skill-checklist/skill.md +15 -141
  22. package/plugins/core/skill-completion-report/plugin.json +1 -1
  23. package/plugins/core/skill-completion-report/skill.md +7 -1
  24. package/plugins/core/skill-doukui-plan/plugin.json +1 -1
  25. package/plugins/core/skill-doukui-plan/skill.md +24 -21
  26. package/plugins/core/skill-experience-logger/plugin.json +1 -1
  27. package/plugins/core/skill-human-checkpoint/skill.md +1 -0
  28. package/plugins/core/skill-split-work-package/plugin.json +1 -1
  29. package/plugins/core/skill-task-creator/plugin.json +1 -1
  30. package/plugins/core/skill-task-creator/skill.md +1 -139
  31. package/plugins/core/skill-workflow-orchestrator/plugin.json +1 -1
  32. package/plugins/plugin-registry.json +0 -48
  33. package/plugins/runtime/harness-build.js +5 -5
  34. package/plugins/runtime/plan-reader.js +54 -21
  35. package/plugins/runtime/resolve-plugin-path.js +2 -2
  36. package/templates/harness-config.yaml +0 -100
  37. package/bin/commands/loop-server.js +0 -357
  38. package/bin/commands/loop.js +0 -1508
  39. package/plugins/contracts/capabilities.js +0 -268
  40. package/plugins/contracts/checkresult-schema.json +0 -75
  41. package/plugins/core/provider-loop-engine/index.js +0 -1411
  42. package/plugins/core/provider-loop-engine/plugin.json +0 -15
  43. package/plugins/core/provider-memory-store/index.js +0 -510
  44. package/plugins/core/provider-memory-store/plugin.json +0 -9
  45. package/plugins/core/provider-state-store/index.js +0 -244
  46. package/plugins/core/provider-state-store/plugin.json +0 -9
  47. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +0 -32
  48. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +0 -676
  49. package/plugins/core/provider-watchdog/assets/watchdog.js +0 -754
  50. package/plugins/core/provider-watchdog/index.js +0 -151
  51. package/plugins/core/provider-watchdog/plugin.json +0 -13
  52. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +0 -249
  53. package/plugins/core/skill-watchdog-manager/plugin.json +0 -10
  54. package/plugins/core/skill-watchdog-manager/skill.md +0 -143
  55. package/plugins/core/validator-doc-sync/index.js +0 -248
  56. package/plugins/core/validator-doc-sync/plugin.json +0 -12
  57. package/plugins/core/validator-work-package/index.js +0 -300
  58. package/plugins/core/validator-work-package/plugin.json +0 -12
  59. package/plugins/runtime/audit-logger.js +0 -311
  60. package/plugins/runtime/build-cli.js +0 -89
  61. package/plugins/runtime/checkresult-validator.js +0 -131
  62. package/plugins/runtime/context-window.js +0 -81
  63. package/plugins/runtime/event-bus.js +0 -207
  64. package/plugins/runtime/executor-claude.js +0 -604
  65. package/plugins/runtime/executor-default.js +0 -448
  66. package/plugins/runtime/executor-local.js +0 -178
  67. package/plugins/runtime/executor-sdk.js +0 -415
  68. package/plugins/runtime/hook-dispatcher.js +0 -315
  69. package/plugins/runtime/loop-actuator.js +0 -292
  70. package/plugins/runtime/loop-coordinator.js +0 -347
  71. package/plugins/runtime/loop-defaults.js +0 -29
  72. package/plugins/runtime/loop-dispatch-batch.js +0 -351
  73. package/plugins/runtime/loop-executor.js +0 -120
  74. package/plugins/runtime/loop-report.js +0 -395
  75. package/plugins/runtime/loop-server-core.js +0 -750
  76. package/plugins/runtime/loop-snapshot.js +0 -581
  77. package/plugins/runtime/loop-trace.js +0 -242
  78. package/plugins/runtime/loop-worktree.js +0 -404
  79. package/plugins/runtime/multi-window-coordinator.js +0 -560
  80. package/plugins/runtime/objective-verifier.js +0 -136
  81. package/plugins/runtime/plan-lint.js +0 -106
  82. package/plugins/runtime/plugin-loader.js +0 -798
  83. package/plugins/runtime/plugin-trust.js +0 -182
  84. package/plugins/runtime/provider-failover.js +0 -114
  85. package/plugins/runtime/provider-resolver.js +0 -342
  86. package/plugins/runtime/reflection-evaluator.js +0 -545
  87. package/plugins/runtime/sandbox-context.js +0 -235
  88. package/plugins/runtime/sandbox-manager.js +0 -609
  89. package/plugins/runtime/sandbox-worker.js +0 -215
  90. package/plugins/runtime/self-rescue-ladder.js +0 -51
  91. package/plugins/runtime/text-tokenize.js +0 -25
  92. package/plugins/runtime/validator-pipeline.js +0 -475
@@ -1,182 +0,0 @@
1
- 'use strict';
2
-
3
- // ---------------------------------------------------------------------------
4
- // Plugin Trust(WP-D8 sandbox 轻量强制化)
5
- // ---------------------------------------------------------------------------
6
- // 背景见 docs/design/sandbox-threat-model.md:真隔离不存在(main-process
7
- // require 全权限),capabilities 声明此前是纯装饰。本模块把「声明」升级为
8
- // 「可检查声明」+「知情记录」,不提供假隔离:
9
- //
10
- // 1. capabilities 扫描:加载前 grep 插件 index.js 的危险 require
11
- // (child_process / fs / net / http / worker_threads),与 plugin.json
12
- // capabilities 声明比对——声明 forbidden 却出现对应 require → violation
13
- // (高亮警告;无法真正阻止 require,但把「声明与行为不符」显式化)
14
- // 2. 信任记录:首次加载的第三方插件记入 {stateDir}/trusted-plugins.json
15
- // (name + sha1(index.js)),重复加载降为一行提示(不刷屏)
16
- // 3. 严格模式:DOUKUI_STRICT_PLUGINS=1 时,未在信任记录中的第三方插件
17
- // 直接拒绝加载(显式 opt-in 的强约束,供安全敏感环境使用)
18
- //
19
- // 边界(诚实声明):源码扫描可被动态 require / 混淆绕过——它是「知情辅助」
20
- // 而非安全边界。真正的隔离仍不可行(见 threat model)。
21
- // ---------------------------------------------------------------------------
22
-
23
- var fs = require('fs');
24
- var path = require('path');
25
- var crypto = require('crypto');
26
-
27
- // 危险模块 → capabilities 键映射(声明 forbidden/deny 却 require → violation)
28
- var DANGEROUS_REQUIRES = [
29
- { re: /require\s*\(\s*['"]child_process['"]\s*\)/g, cap: 'child_process', label: 'child_process' },
30
- { re: /require\s*\(\s*['"]fs['"]\s*\)/g, cap: 'filesystem', label: 'fs' },
31
- { re: /require\s*\(\s*['"](net|dgram|tls)['"]\s*\)/g, cap: 'network', label: 'net/tls/dgram' },
32
- { re: /require\s*\(\s*['"](http|https|http2)['"]\s*\)/g, cap: 'network', label: 'http/https' },
33
- { re: /require\s*\(\s*['"]worker_threads['"]\s*\)/g, cap: 'worker_threads', label: 'worker_threads' },
34
- { re: /require\s*\(\s*['"]process['"]\s*\)|global\.process(?!\w)/g, cap: 'process_env', label: 'process' },
35
- ];
36
-
37
- /**
38
- * 扫描插件入口源码的危险 require,与 capabilities 声明比对。
39
- * @param {string} indexJsPath 插件 index.js 绝对路径
40
- * @param {object|null} pluginJson 插件清单(capabilities 段可省略)
41
- * @returns {{ violations: Array<{module:string,cap:string,declared:string}>, hash: string }}
42
- * violations 空 = 声明与行为一致(或无声明,只报 hash)
43
- */
44
- function scanCapabilities(indexJsPath, pluginJson) {
45
- var src = '';
46
- try {
47
- src = fs.readFileSync(indexJsPath, 'utf8');
48
- } catch (_e) {
49
- return { violations: [], hash: '' };
50
- }
51
- var hash = crypto.createHash('sha1').update(src, 'utf8').digest('hex');
52
- var caps = (pluginJson && pluginJson.capabilities) || {};
53
- var violations = [];
54
- for (var i = 0; i < DANGEROUS_REQUIRES.length; i++) {
55
- var d = DANGEROUS_REQUIRES[i];
56
- var re = new RegExp(d.re.source, 'g'); // 重置 lastIndex
57
- var hits = 0;
58
- var m;
59
- while ((m = re.exec(src)) !== null) { hits++; if (hits > 0) break; }
60
- if (hits === 0) continue;
61
- var declared = caps[d.cap];
62
- var declaredStr = (declared === undefined || declared === null) ? '(未声明)' : String(declared);
63
- // declared 为 forbidden/deny/never/false 之一 → 声明与行为不符
64
- var forbiddenLike = ['forbidden', 'deny', 'denied', 'never', 'false'].indexOf(
65
- String(declared).toLowerCase()) !== -1;
66
- if (forbiddenLike) {
67
- violations.push({ module: d.label, cap: d.cap, declared: declaredStr });
68
- }
69
- }
70
- return { violations: violations, hash: hash };
71
- }
72
-
73
- function trustFilePath(stateDir) {
74
- return path.join(stateDir, 'trusted-plugins.json');
75
- }
76
-
77
- /**
78
- * 读取信任记录。
79
- * @param {string} stateDir 项目 state 目录(.doukui-state 或 .doukui)
80
- * @returns {Object<string, { hash: string, trustedAt: string }>}
81
- */
82
- function readTrust(stateDir) {
83
- try {
84
- var raw = JSON.parse(fs.readFileSync(trustFilePath(stateDir), 'utf8'));
85
- return (raw && typeof raw.plugins === 'object' && raw.plugins) || {};
86
- } catch (_e) {
87
- return {};
88
- }
89
- }
90
-
91
- /**
92
- * 记录信任(首次知情加载后写入;幂等)。
93
- * @param {string} stateDir
94
- * @param {string} pluginName
95
- * @param {string} indexHash scanCapabilities 的 hash
96
- * @returns {boolean} 是否实际写入
97
- */
98
- function recordTrust(stateDir, pluginName, indexHash) {
99
- var file = trustFilePath(stateDir);
100
- var data;
101
- try {
102
- data = JSON.parse(fs.readFileSync(file, 'utf8'));
103
- if (!data || typeof data.plugins !== 'object') data = { plugins: {} };
104
- } catch (_e) {
105
- data = { plugins: {} };
106
- }
107
- if (data.plugins[pluginName] && data.plugins[pluginName].hash === indexHash) {
108
- return false; // 已记录且内容未变
109
- }
110
- data.plugins[pluginName] = { hash: indexHash, trustedAt: new Date().toISOString() };
111
- try {
112
- fs.mkdirSync(path.dirname(file), { recursive: true });
113
- fs.writeFileSync(file, JSON.stringify(data, null, 2), 'utf8');
114
- return true;
115
- } catch (_e) {
116
- return false;
117
- }
118
- }
119
-
120
- /**
121
- * 加载门禁综合评估。
122
- *
123
- * 语义(WP-D8 双跑验证后的裁决):**信任记录只服务两件事——strict 模式的
124
- * 放行/拒绝判定 + 审计痕迹**。非 strict(常规)模式下,第三方插件每次加载
125
- * 都必须发 warn(S3 精神:外部代码跑在主进程,这一事实本身就该始终可见,
126
- * 不能被「曾经信任过」静默掉——信任记录降噪会让披露吞没)。
127
- *
128
- * @param {object} opts
129
- * @param {string} opts.pluginName
130
- * @param {{violations:Array,hash:string}} opts.scan scanCapabilities 产物
131
- * @param {string} opts.stateDir
132
- * @param {boolean} [opts.strict] DOUKUI_STRICT_PLUGINS=1
133
- * @returns {{ allowed: boolean, firstTime: boolean, messages: string[] }}
134
- */
135
- function evaluateLoad(opts) {
136
- opts = opts || {};
137
- var messages = [];
138
- var trust = readTrust(opts.stateDir);
139
- var known = trust[opts.pluginName];
140
- var hashUnchanged = !!(known && known.hash === opts.scan.hash);
141
- var firstTime = !known;
142
-
143
- if (opts.scan.violations.length > 0) {
144
- for (var i = 0; i < opts.scan.violations.length; i++) {
145
- var v = opts.scan.violations[i];
146
- messages.push('⚠ CAPABILITY VIOLATION: plugin "' + opts.pluginName +
147
- '" declares ' + v.cap + '=' + v.declared + ' but requires ' + v.module);
148
- }
149
- }
150
- if (!hashUnchanged) {
151
- // 首次加载 或 代码较上次信任记录已变化 → 完整披露
152
- messages.push('Loading third-party plugin "' + opts.pluginName +
153
- '" — the sandbox is decorative and is NOT enforced; this plugin runs with full ' +
154
- 'main-process privileges.' + (firstTime
155
- ? ' Recorded to ' + trustFilePath(opts.stateDir) + '.'
156
- : ' Code changed since last trust record.') +
157
- ' (see docs/design/sandbox-threat-model.md)');
158
- } else {
159
- // 已信任且未变:常规模式保持一行披露(不静默——S3 精神)
160
- messages.push('Loading trusted third-party plugin "' + opts.pluginName +
161
- '" (hash unchanged) — the sandbox is decorative and is NOT enforced; full main-process privileges');
162
- }
163
-
164
- var strict = opts.strict === true;
165
- var allowed = true;
166
- if (strict && (firstTime || !hashUnchanged)) {
167
- allowed = false;
168
- messages.push('STRICT MODE: plugin "' + opts.pluginName +
169
- '" is not (or no longer) in the trust record. Load it once with strict mode off ' +
170
- '(or remove DOUKUI_STRICT_PLUGINS=1) to record trust.');
171
- }
172
- return { allowed: allowed, firstTime: firstTime, messages: messages };
173
- }
174
-
175
- module.exports = {
176
- scanCapabilities: scanCapabilities,
177
- readTrust: readTrust,
178
- recordTrust: recordTrust,
179
- evaluateLoad: evaluateLoad,
180
- trustFilePath: trustFilePath,
181
- _DANGEROUS_REQUIRES: DANGEROUS_REQUIRES,
182
- };
@@ -1,114 +0,0 @@
1
- 'use strict';
2
-
3
- // ---------------------------------------------------------------------------
4
- // Provider Failover(WP-D3 跨 provider 故障切换)
5
- // ---------------------------------------------------------------------------
6
- // GLM 5h 窗口耗尽(或任何 quota-aware provider 接近上限)时,driver 热切换到
7
- // 备用 provider 的 settings 继续 loop——state 外置已支持断点恢复,这里补齐
8
- // executor 层的切换。
9
- //
10
- // 触发模型(观测驱动,非熔断):
11
- // - 前提:当前 executor 是 quota-aware(executor.quota.windowRatio 可用)
12
- // - 当前 provider 的 loop.providers profile 声明了 `fallback_settings`
13
- // (指向备用 provider 的 claude settings JSON,支持 ~ 展开)
14
- // - windowRatio >= threshold(默认 0.95,复用额度池观测阈值口径)
15
- // - 每个 loop 只切换一次(switched 后不再评估——备用 provider 也耗尽时
16
- // 交给既有的发散/熔断兜底,不做链式切换)
17
- //
18
- // 切换实现:用 fallback settings 重建一个 default executor(spawn CLI 载体,
19
- // 备用端点的兼容性最广);SDK session(若有)作废——切 provider 后 session
20
- // 上下文属于旧模型,续轮语义不成立。
21
- // ---------------------------------------------------------------------------
22
-
23
- var fs = require('fs');
24
- var os = require('os');
25
- var path = require('path');
26
-
27
- var DEFAULT_RATIO_THRESHOLD = 0.95;
28
-
29
- /**
30
- * 展开 settings 路径(支持 ~/ 前缀)。
31
- * @param {string} p
32
- * @returns {string}
33
- */
34
- function expandHomePath(p) {
35
- if (typeof p !== 'string' || !p) return p;
36
- if (p === '~') return os.homedir();
37
- if (p.indexOf('~/') === 0 || p.indexOf('~\\') === 0) {
38
- return path.join(os.homedir(), p.slice(2));
39
- }
40
- return p;
41
- }
42
-
43
- /**
44
- * 评估是否应切换到 fallback provider(纯函数,可测)。
45
- * @param {object} opts
46
- * @param {number|null} [opts.windowRatio] 当前 provider 窗口占用比(无 quota 视图 → null)
47
- * @param {number} [opts.threshold] 触发阈值(默认 0.95)
48
- * @param {string|null} [opts.fallbackSettings] profile.fallback_settings(未配置 → null)
49
- * @param {boolean} [opts.alreadySwitched] 本 loop 已切换过
50
- * @param {boolean} [opts.fallbackFileExists] fallback settings 文件可读(driver 预检)
51
- * @returns {{ should: boolean, reason: string }}
52
- */
53
- function shouldSwitchToFallback(opts) {
54
- opts = opts || {};
55
- if (opts.alreadySwitched) return { should: false, reason: 'already_switched' };
56
- if (!opts.fallbackSettings) return { should: false, reason: 'no_fallback_configured' };
57
- if (opts.fallbackFileExists === false) {
58
- return { should: false, reason: 'fallback_settings_missing' };
59
- }
60
- if (typeof opts.windowRatio !== 'number' || isNaN(opts.windowRatio)) {
61
- return { should: false, reason: 'no_quota_view' };
62
- }
63
- var threshold = typeof opts.threshold === 'number' ? opts.threshold : DEFAULT_RATIO_THRESHOLD;
64
- if (opts.windowRatio < threshold) return { should: false, reason: 'below_threshold' };
65
- return { should: true, reason: 'window_ratio_' + opts.windowRatio.toFixed(2) + '_ge_' + threshold };
66
- }
67
-
68
- /**
69
- * 用 fallback settings 构建备援 executor(default 载体)。
70
- * @param {object} opts
71
- * @param {object} opts.baseOpts 原 executor 的 createExecutor opts(projectRoot/contextWindow 等透传)
72
- * @param {string} opts.fallbackSettings 备用 settings 路径(~ 展开)
73
- * @param {string} [opts.fallbackProvider] 备用 provider 标记(日志/记账)
74
- * @param {Function} [opts.createExecutorFn] DI(默认 loopExecutor.createExecutor)
75
- * @returns {object} 新 executor 实例({ name, run, config, quota })
76
- */
77
- function createFallbackExecutor(opts) {
78
- opts = opts || {};
79
- var createExecutorFn = opts.createExecutorFn || require('./loop-executor').createExecutor;
80
- var baseOpts = opts.baseOpts || {};
81
- var settingsPath = expandHomePath(opts.fallbackSettings);
82
- return createExecutorFn('default', Object.assign({}, baseOpts, {
83
- settingsPath: settingsPath,
84
- provider: opts.fallbackProvider || 'fallback',
85
- model: null, // 备用端点的模型由其 settings 文件决定
86
- quotaConfig: null, // 备用 provider 无额度画像(纯透传)
87
- resumeSessionId: null, // 切 provider 后 session 上下文作废
88
- }));
89
- }
90
-
91
- /**
92
- * 读取 fallback settings 配置并预检文件可读。
93
- * @param {object} [opts] { profile, configManager }
94
- * @returns {{ fallbackSettings: string|null, fallbackFileExists: boolean }}
95
- */
96
- function resolveFallbackConfig(opts) {
97
- opts = opts || {};
98
- var profile = opts.profile || null;
99
- var fb = (profile && typeof profile.fallback_settings === 'string')
100
- ? profile.fallback_settings : null;
101
- if (!fb) return { fallbackSettings: null, fallbackFileExists: false };
102
- var expanded = expandHomePath(fb);
103
- var exists = false;
104
- try { exists = fs.existsSync(expanded); } catch (_e) { exists = false; }
105
- return { fallbackSettings: expanded, fallbackFileExists: exists };
106
- }
107
-
108
- module.exports = {
109
- shouldSwitchToFallback: shouldSwitchToFallback,
110
- createFallbackExecutor: createFallbackExecutor,
111
- resolveFallbackConfig: resolveFallbackConfig,
112
- expandHomePath: expandHomePath,
113
- DEFAULT_RATIO_THRESHOLD: DEFAULT_RATIO_THRESHOLD,
114
- };
@@ -1,342 +0,0 @@
1
- /**
2
- * Provider Resolver — 模型探测 + provider profile 匹配(WP-188 重构:去 glm 死标签)
3
- *
4
- * @module provider-resolver
5
- *
6
- * 职责:在 loop driver 启动时解析"当前实际生效的模型",并按 harness-config.yaml 的
7
- * `loop.providers` 规则匹配到 provider profile,决定 default executor 启用哪些特性
8
- * (目前唯一可启用的是智谱 GLM 的 5h 窗口额度感知)。
9
- *
10
- * 为什么需要(取代原 executor-glm 的硬编码):
11
- * 原 `--executor=glm` 把 provider 名直接焊死成 executor 类型,导致:
12
- * (1) 切 mimo/deepseek 需要新建 executor 模块(违背 provider 解耦初衷);
13
- * (2) 智谱额度参数(5h 窗口/高峰系数)硬编码在 executor-glm.js,改套餐档位要改代码。
14
- * 本模块把"模型名 → provider 归属 → 启用哪些特性"的判定抽成纯函数 + 外置配置:
15
- * default executor 只认 resolveProvider() 的输出,不再 if(provider==='glm')。
16
- *
17
- * 模型探测顺序(resolveEffectiveModel,用户明确要求"配置文件优先于环境变量"):
18
- * 1. --settings 文件的顶层 model 字段
19
- * 2. --settings 文件的 env.ANTHROPIC_DEFAULT_SONNET_MODEL(fallback OPUS / HAIKU)
20
- * 3. 进程环境变量 ANTHROPIC_MODEL
21
- * 4. 进程环境变量 ANTHROPIC_DEFAULT_SONNET_MODEL
22
- * 5. 都没有 → null(纯透传,不启用任何 provider 特性)
23
- *
24
- * 容错(回退安全,绝不阻断 loop 启动):
25
- * - settings 文件读失败 / 坏 JSON / 带 BOM → 当作无 model(strip BOM 后再 parse)
26
- * - harness-config 无 loop.providers 段 → 用内置 DEFAULT_PROVIDERS(开箱即用)
27
- * - 任何 profile 的正则编译失败 → 跳过该 profile(不崩,记 skip)
28
- *
29
- * 可测性(遵循 codebase DI-over-mocking):
30
- * - resolveProvider({ settingsPath, env, fs, providers }) 全部依赖可注入
31
- * - fs 默认 require('fs'),env 默认 process.env,providers 默认从 ConfigManager 读
32
- *
33
- * SECURITY (S4):profile.modelRegex / baseUrlRegex 来自用户配置文件,用 new RegExp 编译。
34
- * 匹配对象(model / baseUrl)已是受信来源(settings 文件/环境变量),无注入风险。
35
- * 拒绝对正则做 eval,只走 RegExp.test;编译失败静默跳过该 profile。
36
- */
37
-
38
- 'use strict';
39
-
40
- var fs = require('fs');
41
-
42
- // ---------------------------------------------------------------------------
43
- // 内置默认 providers(开箱即用,harness-config 无 loop.providers 段时回退)
44
- // 与 templates/harness-config.yaml 的 loop.providers 保持一致(同值的两个表达;
45
- // 改默认值时两处同步)。对齐原 executor-glm.js DEFAULTS 的额度参数。
46
- // ---------------------------------------------------------------------------
47
-
48
- var DEFAULT_PROVIDERS = [
49
- {
50
- key: 'glm',
51
- modelRegex: '^glm[-_]?5(?!\\d)|^glm[-_]?(4\\.[67]|4\\.5-air)',
52
- baseUrlRegex: 'open\\.bigmodel\\.cn',
53
- quota: {
54
- windowPrompts: 400, // 5h 窗口(Pro 档基准)
55
- weeklyPrompts: 2000,
56
- softThreshold: 0.9,
57
- peakStartHour: 14, // UTC+8
58
- peakEndHour: 18,
59
- peakCostFactor: 3,
60
- offpeakCostFactor: 2,
61
- costModelRegex: '^glm[-_]?5(?!\\d)', // 仅 5.x 系列受高峰系数
62
- },
63
- },
64
- {
65
- key: 'mimo',
66
- modelRegex: '^mimo',
67
- },
68
- {
69
- key: 'deepseek',
70
- modelRegex: '^deepseek',
71
- },
72
- ];
73
-
74
- // ---------------------------------------------------------------------------
75
- // 工具函数
76
- // ---------------------------------------------------------------------------
77
-
78
- /**
79
- * strip UTF-8 BOM(0xFEFF)。claude settings 文件常带 BOM,JSON.parse 直接读会失败。
80
- * @param {string} content
81
- * @returns {string}
82
- */
83
- function stripBom(content) {
84
- if (typeof content !== 'string' || content.length === 0) return content;
85
- return content.charCodeAt(0) === 0xFEFF ? content.slice(1) : content;
86
- }
87
-
88
- /**
89
- * 安全 JSON.parse:strip BOM + 容错。坏 JSON 返回 null(调用方当无 model 处理)。
90
- * @param {string} raw
91
- * @returns {object|null}
92
- */
93
- function safeParseJson(raw) {
94
- if (!raw) return null;
95
- try {
96
- var stripped = stripBom(String(raw));
97
- var obj = JSON.parse(stripped);
98
- return (obj && typeof obj === 'object') ? obj : null;
99
- } catch (_e) {
100
- return null;
101
- }
102
- }
103
-
104
- /**
105
- * 从 claude settings 对象提取生效模型名。
106
- * 优先级:顶层 model → env.ANTHROPIC_DEFAULT_SONNET_MODEL → OPUS → HAIKU。
107
- * (claude 的 tier 映射:sonnet=主力模型,opus=复杂任务,haiku=轻量。loop 取主力。)
108
- * @param {object} parsed settings 对象
109
- * @returns {string|null}
110
- */
111
- function extractModelFromSettings(parsed) {
112
- if (!parsed || typeof parsed !== 'object') return null;
113
- if (typeof parsed.model === 'string' && parsed.model.trim()) {
114
- return parsed.model.trim();
115
- }
116
- var env = parsed.env || {};
117
- if (typeof env === 'object') {
118
- var sonnet = env.ANTHROPIC_DEFAULT_SONNET_MODEL;
119
- if (typeof sonnet === 'string' && sonnet.trim()) return sonnet.trim();
120
- var opus = env.ANTHROPIC_DEFAULT_OPUS_MODEL;
121
- if (typeof opus === 'string' && opus.trim()) return opus.trim();
122
- var haiku = env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
123
- if (typeof haiku === 'string' && haiku.trim()) return haiku.trim();
124
- }
125
- return null;
126
- }
127
-
128
- /**
129
- * 从 claude settings 对象提取 ANTHROPIC_BASE_URL(供 baseUrlRegex 二次确认)。
130
- * @param {object} parsed
131
- * @returns {string|null}
132
- */
133
- function extractBaseUrlFromSettings(parsed) {
134
- if (!parsed || typeof parsed !== 'object') return null;
135
- var env = parsed.env || {};
136
- if (env && typeof env.ANTHROPIC_BASE_URL === 'string') {
137
- return env.ANTHROPIC_BASE_URL;
138
- }
139
- return null;
140
- }
141
-
142
- // ---------------------------------------------------------------------------
143
- // 核心探测与匹配
144
- // ---------------------------------------------------------------------------
145
-
146
- /**
147
- * 解析当前生效的模型名(settings 文件优先 → 环境变量)。
148
- *
149
- * @param {object} p
150
- * @param {string|null} p.settingsPath --settings 文件路径(已校验存在)
151
- * @param {object} p.env 进程环境变量(默认 process.env)
152
- * @param {object} [p.fs] fs 实现(测试注入;默认 require('fs'))
153
- * @returns {{ model:string|null, baseUrl:string|null, settingsParsed:object|null }}
154
- * - model: 探测到的模型名,或 null
155
- * - baseUrl: settings 文件携带的 ANTHROPIC_BASE_URL(供 baseUrlRegex 确认),或 null
156
- * - settingsParsed: 解析后的 settings 对象(供调用方诊断),或 null
157
- */
158
- function resolveEffectiveModel(p) {
159
- p = p || {};
160
- var fsImpl = p.fs || fs;
161
- var env = p.env || process.env;
162
- var settingsParsed = null;
163
- var model = null;
164
- var baseUrl = null;
165
-
166
- // 1) settings 文件(优先)
167
- if (p.settingsPath) {
168
- try {
169
- var raw = fsImpl.readFileSync(p.settingsPath, 'utf8');
170
- settingsParsed = safeParseJson(raw);
171
- if (settingsParsed) {
172
- model = extractModelFromSettings(settingsParsed);
173
- baseUrl = extractBaseUrlFromSettings(settingsParsed);
174
- }
175
- } catch (_e) {
176
- // 读失败:降级到环境变量(不阻断)
177
- }
178
- }
179
-
180
- // 2) 环境变量(settings 未提供 model 时回退)
181
- if (!model) {
182
- if (typeof env.ANTHROPIC_MODEL === 'string' && env.ANTHROPIC_MODEL.trim()) {
183
- model = env.ANTHROPIC_MODEL.trim();
184
- } else if (typeof env.ANTHROPIC_DEFAULT_SONNET_MODEL === 'string' &&
185
- env.ANTHROPIC_DEFAULT_SONNET_MODEL.trim()) {
186
- model = env.ANTHROPIC_DEFAULT_SONNET_MODEL.trim();
187
- }
188
- }
189
-
190
- return { model: model, baseUrl: baseUrl, settingsParsed: settingsParsed };
191
- }
192
-
193
- /**
194
- * 安全编译正则(编译失败返回 null,不抛)。
195
- * @param {string} pattern
196
- * @param {string} [flags] 可选正则标志(如 'i');默认空串
197
- * @returns {RegExp|null}
198
- */
199
- function safeCompileRegex(pattern, flags) {
200
- if (typeof pattern !== 'string' || !pattern) return null;
201
- try {
202
- return new RegExp(pattern, typeof flags === 'string' ? flags : '');
203
- } catch (_e) {
204
- return null;
205
- }
206
- }
207
-
208
- /**
209
- * 按 providers 规则匹配 model → provider profile。
210
- * 遍历 providers,第一个 modelRegex 命中的胜出;baseUrlRegex(可选)做二次确认。
211
- *
212
- * @param {string|null} model 生效模型名
213
- * @param {string|null} baseUrl settings 携带的端点 URL(供 baseUrlRegex 确认)
214
- * @param {Array} providers profile 列表(DEFAULT_PROVIDERS 结构)
215
- * @returns {{ provider:string, profile:object|null }}
216
- * - provider: 命中的 key,或 'unknown'
217
- * - profile: 命中的 profile 对象(含 quota 等),或 null
218
- */
219
- function matchProvider(model, baseUrl, providers) {
220
- if (!model) return { provider: 'unknown', profile: null };
221
- var list = Array.isArray(providers) ? providers : DEFAULT_PROVIDERS;
222
- for (var i = 0; i < list.length; i++) {
223
- var prof = list[i];
224
- if (!prof || typeof prof !== 'object' || typeof prof.key !== 'string') continue;
225
-
226
- // modelRegex 用 'i'(模型名大小写不敏感):对齐原 executor-glm 的 /^glm[-_]?5(?!\d)/i,
227
- // 让 GLM-5.2 / GLM5Turbo 等大写变体同样命中(零漂移搬迁承诺)。
228
- var modelRe = safeCompileRegex(prof.modelRegex, 'i');
229
- if (!modelRe) continue; // 正则编译失败 → 跳过该 profile(不崩)
230
- if (!modelRe.test(model)) continue;
231
-
232
- // baseUrlRegex(可选):二次确认端点归属,防模型名撞车。
233
- // 指定了 baseUrlRegex 但 baseUrl 不可得(如纯环境变量场景)→ 放行(不因缺端点误拒);
234
- // 指定了且 baseUrl 可得 → 必须匹配,否则视为撞名,跳过该 profile 继续找下一个。
235
- // 不加 'i':URL 端点 host 大小写敏感(open.bigmodel.cn vs OPEN.BIGMODEL.CN 应区分),避免误放行。
236
- if (prof.baseUrlRegex) {
237
- var urlRe = safeCompileRegex(prof.baseUrlRegex, '');
238
- if (urlRe && baseUrl && !urlRe.test(baseUrl)) {
239
- continue; // 端点不匹配,模型名疑似撞车 → 跳过
240
- }
241
- }
242
-
243
- return { provider: prof.key, profile: prof };
244
- }
245
- return { provider: 'unknown', profile: null };
246
- }
247
-
248
- /**
249
- * 从 profile 提取额度配置(若 profile.quota 存在且字段齐全)。
250
- * 字段不全 → 返回 null(降级为不启用额度感知,不崩)。
251
- * @param {object|null} profile
252
- * @returns {object|null}
253
- */
254
- function extractQuotaConfig(profile) {
255
- if (!profile || !profile.quota || typeof profile.quota !== 'object') return null;
256
- var q = profile.quota;
257
- // 必备数值字段校验;缺任一 → null(避免 executor 拿到半截配置崩溃)
258
- var numFields = ['windowPrompts', 'weeklyPrompts', 'softThreshold',
259
- 'peakStartHour', 'peakEndHour', 'peakCostFactor', 'offpeakCostFactor'];
260
- for (var i = 0; i < numFields.length; i++) {
261
- if (typeof q[numFields[i]] !== 'number') return null;
262
- }
263
- if (typeof q.costModelRegex !== 'string') return null;
264
- // 范围校验(WP-188 评审 P5):NaN/Infinity/越界 → null 降级(不崩)。
265
- // typeof 已确认 number;Number.isFinite 挡 NaN/Infinity,范围比较挡越界。
266
- if (!Number.isFinite(q.peakStartHour) || q.peakStartHour < 0 || q.peakStartHour > 23) return null;
267
- if (!Number.isFinite(q.peakEndHour) || q.peakEndHour < 0 || q.peakEndHour > 23) return null;
268
- if (!Number.isFinite(q.softThreshold) || q.softThreshold <= 0 || q.softThreshold > 1) return null;
269
- if (!Number.isFinite(q.peakCostFactor) || q.peakCostFactor <= 0) return null;
270
- if (!Number.isFinite(q.offpeakCostFactor) || q.offpeakCostFactor <= 0) return null;
271
- if (!Number.isFinite(q.windowPrompts) || q.windowPrompts <= 0) return null;
272
- if (!Number.isFinite(q.weeklyPrompts) || q.weeklyPrompts <= 0) return null;
273
- return {
274
- windowPrompts: q.windowPrompts,
275
- weeklyPrompts: q.weeklyPrompts,
276
- softThreshold: q.softThreshold,
277
- peakStartHour: q.peakStartHour,
278
- peakEndHour: q.peakEndHour,
279
- peakCostFactor: q.peakCostFactor,
280
- offpeakCostFactor: q.offpeakCostFactor,
281
- costModelRegex: q.costModelRegex,
282
- };
283
- }
284
-
285
- // ---------------------------------------------------------------------------
286
- // 公开 API
287
- // ---------------------------------------------------------------------------
288
-
289
- /**
290
- * 解析当前生效模型 + 匹配 provider profile,产出 default executor 行为决策。
291
- *
292
- * @param {object} opts
293
- * @param {string|null} [opts.settingsPath] --settings 文件路径(已校验存在)
294
- * @param {object} [opts.env] 进程环境变量(默认 process.env)
295
- * @param {object} [opts.fs] fs 实现(测试注入;默认 require('fs'))
296
- * @param {Array} [opts.providers] provider profile 列表(默认从 ConfigManager 读;
297
- * 若调用方已知 providers 可直接传入,绕过 ConfigManager)
298
- * @returns {{ model:string|null, provider:string, profile:object|null,
299
- * quotaConfig:object|null, features:{quotaAware:boolean} }}
300
- */
301
- function resolveProvider(opts) {
302
- opts = opts || {};
303
- var providers = Array.isArray(opts.providers) ? opts.providers : DEFAULT_PROVIDERS;
304
-
305
- var resolved = resolveEffectiveModel({
306
- settingsPath: opts.settingsPath || null,
307
- env: opts.env || process.env,
308
- fs: opts.fs || fs,
309
- });
310
-
311
- var matched = matchProvider(resolved.model, resolved.baseUrl, providers);
312
- var quotaConfig = extractQuotaConfig(matched.profile);
313
-
314
- return {
315
- model: resolved.model,
316
- provider: matched.provider,
317
- profile: matched.profile,
318
- quotaConfig: quotaConfig,
319
- features: {
320
- // 唯一可门控的特性:智谱额度感知(5h 窗口 + 高峰系数)。
321
- // 有 quotaConfig 即启用;mimo/deepseek/unknown 的 profile 无 quota 段 → false(纯透传)。
322
- quotaAware: !!quotaConfig,
323
- },
324
- // 诊断字段(非契约,供 loop.js 打日志 + 测试断言)
325
- _baseUrl: resolved.baseUrl,
326
- _settingsParsed: resolved.settingsParsed,
327
- };
328
- }
329
-
330
- module.exports = {
331
- resolveProvider: resolveProvider,
332
- resolveEffectiveModel: resolveEffectiveModel,
333
- matchProvider: matchProvider,
334
- extractQuotaConfig: extractQuotaConfig,
335
- // 暴露内部工具便于单元测试
336
- _stripBom: stripBom,
337
- _safeParseJson: safeParseJson,
338
- _extractModelFromSettings: extractModelFromSettings,
339
- _extractBaseUrlFromSettings: extractBaseUrlFromSettings,
340
- _safeCompileRegex: safeCompileRegex,
341
- _DEFAULT_PROVIDERS: DEFAULT_PROVIDERS,
342
- };