doukui 0.0.0-stage → 0.3.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 (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1398 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1397 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +572 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +390 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
@@ -0,0 +1,114 @@
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
+ };
@@ -0,0 +1,342 @@
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
+ };