dsh-think-effort 0.5.1 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 — 2026-11-26
4
+
5
+ - **自动难度(实验,默认关闭)**:新增 `adaptiveEnabled` 总开关。打开后只对模型选择器里的 `Auto` 生效:
6
+ - **探索阶段降档**(镜像 Reasonix v1.38.1 的 reasoning governor):先按默认档跑一轮;触发条件成立且本轮还没出现写文件/本地执行时,后续请求降到 `adaptiveExplorationLevel`(默认 `low`);第一次写/执行即退出探索、恢复默认档。状态按会话隔离、每轮重置。
7
+ - **触发方式**:`adaptiveTrigger` 默认 `auto`——供应商上报 reasoning tokens 时用阈值(`adaptiveReasoningThreshold`,默认 1500),否则退回轮次(`adaptiveMinRounds`,默认 1)。实测当前网关的 `assistant/message.usage` 不返回 reasoning tokens,若只按阈值会完全失效,因此加入轮次回退;也可强制 `rounds` / `reasoning`。
8
+ - **计划模式映射**:`planMode` 激活时 Auto 落到 `adaptivePlanLevel`(默认 `high`),可关。
9
+ - **优先级写死**:廉价调用 → 固定 `subagentLevel` → 自动策略 → Auto 默认;用户显式选的档位永远原样透传,自动策略不介入;所有自动档位 clamp 到模型已声明词表。
10
+ - **可观测**:调试悬浮窗新增「探索 / 计划」原因徽标,journal 记录 `reason`/`phase`;设置页新增「自动难度(实验)」区块(6 个字段,全部 volatile)。
11
+ - **未做**(按 P1 范围):失败升档、按深度/preset 的多层映射;不按提示词/工具名猜难度。
12
+ - 文档:README / DETAIL(中英)新增自动难度说明与「为什么默认关闭」;`cordis.patch.yml` 与配置表补 6 个字段。
13
+ - 测试:`node --test` **54 项全绿**(新增 8 项自适应状态机、3 项策略/配置归一化、3 项 Host 集成(含 agent 作用域 planMode)、客户端双语文案守卫)。
14
+
3
15
  ## 0.5.1 — 2026-11-25
4
16
 
5
17
  - **修复 Desktop 上悬浮窗一直「读取调试日志失败:Failed to fetch」**:DSH Desktop 的页面从 `dsh-app://app/` 加载,`__DSH_TRANSPORT__.streamBaseUrl` 指向 `http://127.0.0.1:<port>`。上一版把调试路由拼成这个绝对地址,浏览器把它当成跨源请求,而插件路由没有 CORS 响应头,于是被浏览器拒绝(`TypeError: Failed to fetch`),只有浏览器里打开的 Web GUI 能用。
package/README.md CHANGED
@@ -91,6 +91,24 @@ DSH Desktop → **插件市场**搜索 `dsh-think-effort` 安装;或 **插件
91
91
 
92
92
  窗口位置与展开状态记在浏览器本地,刷新页面后保持原样;「设置更新」「能力声明」也会作为事件出现在日志里,方便确认保存是否生效。
93
93
 
94
+ ### 自动难度(实验)
95
+
96
+ 默认**关闭**。打开后只对模型选择器里的 `Auto` 生效,不会覆盖你显式选的 `Low / High / Max`:
97
+
98
+ - **探索阶段降档**:先按默认档跑一轮;若这一轮思考很贵(`reasoningTokens ≥ 1500`,可调)且本轮还没开始写文件/执行命令,**后续请求降到 `Low`**;一旦出现写/执行就恢复默认档。状态按会话隔离,每轮重置。
99
+ 触发方式默认「自动」:供应商上报 reasoning tokens 时按阈值,**不上报时退回按轮次**(默认第一轮后触发)——很多 OpenAI 兼容网关不返回 reasoning tokens,这样才不会失效;也可以强制「按轮次」或「按思考 token」。
100
+ - **计划模式**:计划模式是显式信号,Auto 会落到 `High`(可改为别的档),避免规划时被降档。
101
+ - **不猜难度**:不看提示词、工具名或参数大小;只看“是否在探索”“上一轮思考多贵”“是否计划模式”这些确定性信号。
102
+ - **优先级**:廉价调用 → 固定子代理档位 → 自动策略 → Auto 默认;自动档位一律 clamp 到模型已声明词表。
103
+
104
+ 设置页「自动难度(实验)」:总开关、探索降档开关/档位/触发方式/阈值/轮次、计划模式开关/档位。默认值 `auto / 1500 / 1 / Low / High`,建议先按默认跑几组任务,观察 HUD 里的「探索」标记再调。
105
+
106
+ ![设置页里的自动难度开关](docs/adaptive-settings.png)
107
+
108
+ ![探索阶段降档的实时日志](docs/adaptive-overlay.png)
109
+
110
+ > 这是从 Reasonix 的实验性 reasoning governor 移植过来的机制(其 v1.39.11 已退役 enforcement,只留 shadow 遥测),所以这里也默认关闭、标注实验:纯思考型任务在探索阶段降档可能降低质量。失败升档、按子代理深度/preset 的多层映射不在本版本范围。
111
+
94
112
  ### 本插件的第一次使用
95
113
 
96
114
  装上后不需要额外配置:`Auto` 与档位由插件自动声明。选中 `Auto` 即按默认档运行;选 `Low / High / Max` 即固定该档;不选(原生「提供方默认」)在普通步骤上与 `Auto` 等效。
@@ -138,6 +156,14 @@ DSH Desktop → **插件市场**搜索 `dsh-think-effort` 安装;或 **插件
138
156
  auxLevel: low
139
157
  autoScope: all
140
158
  subagentLevel: inherit
159
+ adaptiveEnabled: false
160
+ adaptiveExploration: true
161
+ adaptiveExplorationLevel: low
162
+ adaptiveTrigger: auto
163
+ adaptiveReasoningThreshold: 1500
164
+ adaptiveMinRounds: 1
165
+ adaptivePlanMode: true
166
+ adaptivePlanLevel: high
141
167
  debugOverlay: false
142
168
  trace: false
143
169
  ```
@@ -257,6 +283,23 @@ Turn on **Debug → Show the live effort-switch log in the conversation** and a
257
283
 
258
284
  The window's position and open state persist in the browser, so a page refresh keeps them. Settings updates and capability declarations also appear as events, which makes a save's effect easy to confirm.
259
285
 
286
+ ### Automatic difficulty (experimental)
287
+
288
+ Off by default. When on it applies only to the selector's `Auto`; an explicit `Low / High / Max` is never overridden:
289
+
290
+ - **Exploration downgrade**: the first round runs at the default depth; if that round thought expensively (`reasoningTokens ≥ 1500`, configurable) and the turn has not written or executed anything yet, **later requests drop to `Low`**. The first write or local execution restores the default. State is per Session and resets every turn. The trigger defaults to `auto`: the reasoning threshold when the provider reports reasoning tokens, otherwise assistant rounds (most OpenAI-compatible gateways report none); `rounds` and `reasoning` force one rule.
291
+ - **Plan mode**: an explicit signal, so Auto maps to `High` (configurable) instead of being downgraded while planning.
292
+ - **No difficulty guessing**: prompt text, tool names, and argument sizes are never inspected; only deterministic signals (exploring, previous round's reasoning spend, plan mode) are used.
293
+ - **Precedence**: cheap calls → fixed subagent depth → adaptive policy → Auto default; every adaptive depth is clamped to the model's declared vocabulary.
294
+
295
+ Settings → Automatic thinking depth → **Automatic difficulty (experimental)**: master switch, exploration switch/depth/trigger/threshold/rounds, plan-mode switch/depth. Defaults are `auto / 1500 / 1 / Low / High`; run a few tasks with the HUD open and watch the `explore` badge before tuning.
296
+
297
+ ![The automatic-difficulty settings](docs/adaptive-settings.png)
298
+
299
+ ![The exploration downgrade in the live log](docs/adaptive-overlay.png)
300
+
301
+ > This ports Reasonix's experimental reasoning governor (v1.39.11 retired its enforcement path and kept only shadow telemetry), so it stays opt-in and marked experimental: downgrading pure-reasoning tasks during exploration can hurt quality. Failure escalation and depth/preset maps are out of scope for this release.
302
+
260
303
  ### Features
261
304
 
262
305
  - Declares `reasoningEfforts` for DeepSeek models that carry none (gateway aliases included), so the selector finally has levels.
@@ -265,10 +308,11 @@ The window's position and open state persist in the browser, so a page refresh k
265
308
  - Cheap host-owned calls (`session-title`, `compaction`, `auto-review`) drop to `low` only when the model declares it, regardless of the session's own choice.
266
309
  - Idempotent: a second boot writes nothing; unload restores the original adapter registrations and retires a durable `auto`.
267
310
  - **Live debug window**: an opt-in, bounded, in-memory journal served over a Host route and rendered as a movable log over the conversation, subagent decisions included.
311
+ - **Automatic difficulty (experimental)**: an opt-in exploration downgrade and plan-mode elevation for `Auto`, with explicit selections, cheap calls, and fixed subagent depths always taking precedence.
268
312
 
269
313
  ### Configuration
270
314
 
271
- Override the `think-effort` row in the profile's `cordis.patch.yml`; the fields are listed in the Chinese section above. `declareCapability`, `efforts`, `defaultEffort`, `auxPurposes`, `auxLevel`, `autoScope`, `subagentLevel`, `debugOverlay` and `trace` are the ones most often changed. Most users should use the visual settings page instead of editing this file.
315
+ Override the `think-effort` row in the profile's `cordis.patch.yml`; the fields are listed in the Chinese section above. `declareCapability`, `efforts`, `defaultEffort`, `auxPurposes`, `auxLevel`, `autoScope`, `subagentLevel`, `adaptiveEnabled`, `debugOverlay` and `trace` are the ones most often changed. Most users should use the visual settings page instead of editing this file.
272
316
 
273
317
  ### Compatibility
274
318
 
package/client.js CHANGED
@@ -62,6 +62,8 @@ window.__ModuleLoader__.load({
62
62
  unsaved: '有未保存的改动。',
63
63
  invalidPattern: '模型 ID 正则需要是合法的 JavaScript 正则。',
64
64
  invalidEfforts: '至少保留一个档位。',
65
+ adaptiveThresholdInvalid: '触发阈值必须是非负数字。',
66
+ adaptiveRoundsInvalid: '触发轮次必须是至少 1 的整数。',
65
67
  effortPicker: '自动思考档位',
66
68
  sectionPurpose: '档位分配',
67
69
  sectionPurposeHint: '每一类请求各自决定用什么强度;显式选择的具体档位不会被“普通步骤”覆盖。',
@@ -91,6 +93,27 @@ window.__ModuleLoader__.load({
91
93
  patternHint: '网关别名用,例如 ^deepseek;不区分大小写。',
92
94
  declareModelsRow: '额外声明',
93
95
  declareModelsHint: '每行一个 provider/model,或一个模型 ID 正则;用于没有匹配到上面两条规则的网关。',
96
+ sectionAdaptive: '自动难度(实验)',
97
+ adaptiveSectionHint: '默认关闭。只对模型选择器里的 Auto 生效:显式选的档位永远优先,也不会根据提示词或工具名猜难度。',
98
+ adaptiveEnabledRow: '启用自动难度',
99
+ adaptiveEnabledHint: '打开后才按下面的规则升降档;关闭时与原行为完全一致。',
100
+ adaptiveExplorationRow: '探索阶段降档',
101
+ adaptiveExplorationHint: '先按默认档跑一轮;若这一轮思考很贵且还没开始写文件或执行命令,后续请求降到探索档;一旦出现写/执行就恢复默认档。',
102
+ adaptiveExplorationLevelRow: '探索阶段使用的档位',
103
+ adaptiveThresholdRow: '触发阈值(上一轮 reasoning tokens)',
104
+ adaptiveThresholdHint: '默认 1500;仅当触发方式使用思考 token 时生效。',
105
+ adaptiveTriggerRow: '触发方式',
106
+ adaptiveTriggerHint: '自动:供应商上报 reasoning tokens 时按阈值,否则按轮次(多数网关不报 reasoning tokens);轮次:只看本轮助手消息数;思考 token:只按 reasoning tokens。',
107
+ adaptiveTriggerAuto: '自动(优先思考 token)',
108
+ adaptiveTriggerRounds: '按轮次',
109
+ adaptiveTriggerReasoning: '按思考 token',
110
+ adaptiveMinRoundsRow: '触发轮次(本轮助手消息数)',
111
+ adaptiveMinRoundsHint: '默认 1:第一轮之后、仍在探索时降档。',
112
+ adaptivePlanRow: '计划模式使用高档',
113
+ adaptivePlanHint: '计划模式下显式提高档位,避免把“探索”误降;不想要可以关闭。',
114
+ adaptivePlanLevelRow: '计划模式使用的档位',
115
+ debugReasonExploration: '探索',
116
+ debugReasonPlan: '计划',
94
117
  debugSection: '调试',
95
118
  debugSectionHint: '调试只记录、不改变任何请求:打开后,每次模型请求的档位决策都会实时出现在会话界面的悬浮窗里。',
96
119
  debugOverlayRow: '在会话界面显示实时档位切换日志',
@@ -154,6 +177,8 @@ window.__ModuleLoader__.load({
154
177
  unsaved: 'Unsaved changes.',
155
178
  invalidPattern: 'The model-id pattern must be a valid JavaScript regular expression.',
156
179
  invalidEfforts: 'Keep at least one depth.',
180
+ adaptiveThresholdInvalid: 'The trigger threshold must be a non-negative number.',
181
+ adaptiveRoundsInvalid: 'The trigger round must be an integer of at least 1.',
157
182
  effortPicker: 'Automatic thinking depth',
158
183
  sectionPurpose: 'Depth assignment',
159
184
  sectionPurposeHint: 'Each purpose chooses its own depth; an explicit pick is never overridden by the ordinary-step rule.',
@@ -183,6 +208,27 @@ window.__ModuleLoader__.load({
183
208
  patternHint: 'For gateway aliases, such as ^deepseek; case insensitive.',
184
209
  declareModelsRow: 'Extra declarations',
185
210
  declareModelsHint: 'One provider/model per line, or a model-id regular expression, for gateways the rules above miss.',
211
+ sectionAdaptive: 'Automatic difficulty (experimental)',
212
+ adaptiveSectionHint: 'Off by default. Applies only to the selector\'s Auto: an explicit depth always wins, and the policy never guesses from prompt text or tool names.',
213
+ adaptiveEnabledRow: 'Enable automatic difficulty',
214
+ adaptiveEnabledHint: 'When on, the rules below may change the depth; when off, behavior is exactly as before.',
215
+ adaptiveExplorationRow: 'Lower depth during exploration',
216
+ adaptiveExplorationHint: 'Run the first round at the default depth; if that round thought expensively and the turn has not started writing or executing yet, later requests drop to the exploration depth. The first write or local execution restores the default.',
217
+ adaptiveExplorationLevelRow: 'Depth used while exploring',
218
+ adaptiveThresholdRow: 'Trigger threshold (previous round\'s reasoning tokens)',
219
+ adaptiveThresholdHint: '1500 by default; only used when the trigger rule reads reasoning tokens.',
220
+ adaptiveTriggerRow: 'Trigger rule',
221
+ adaptiveTriggerHint: 'auto: use the reasoning threshold when the provider reports reasoning tokens, otherwise count assistant rounds (most gateways report no reasoning tokens); rounds: count rounds only; reasoning: use reasoning tokens only.',
222
+ adaptiveTriggerAuto: 'Auto (reasoning first)',
223
+ adaptiveTriggerRounds: 'By round',
224
+ adaptiveTriggerReasoning: 'By reasoning tokens',
225
+ adaptiveMinRoundsRow: 'Trigger round (assistant messages this turn)',
226
+ adaptiveMinRoundsHint: '1 by default: downgrade after the first round while still exploring.',
227
+ adaptivePlanRow: 'Use a higher depth in plan mode',
228
+ adaptivePlanHint: 'Plan mode raises the depth explicitly so exploration is not downgraded there; turn it off if not wanted.',
229
+ adaptivePlanLevelRow: 'Depth used in plan mode',
230
+ debugReasonExploration: 'explore',
231
+ debugReasonPlan: 'plan',
186
232
  debugSection: 'Debug',
187
233
  debugSectionHint: 'Debugging records but never changes a request: when on, every effort decision appears live in a floating log over the conversation.',
188
234
  debugOverlayRow: 'Show the live effort-switch log in the conversation',
@@ -238,7 +284,11 @@ window.__ModuleLoader__.load({
238
284
  const FIELDS = [
239
285
  'enabled', 'declareCapability', 'deepseekHosts', 'deepseekModelPattern',
240
286
  'declareModels', 'efforts', 'defaultEffort', 'autoLevel', 'autoScope',
241
- 'auxDowngrade', 'auxPurposes', 'auxLevel', 'subagentLevel', 'debugOverlay', 'trace',
287
+ 'auxDowngrade', 'auxPurposes', 'auxLevel', 'subagentLevel',
288
+ 'adaptiveEnabled', 'adaptiveExploration', 'adaptiveExplorationLevel',
289
+ 'adaptiveTrigger', 'adaptiveReasoningThreshold', 'adaptiveMinRounds',
290
+ 'adaptivePlanMode', 'adaptivePlanLevel',
291
+ 'debugOverlay', 'trace',
242
292
  ];
243
293
 
244
294
  function equal(a, b) {
@@ -352,6 +402,9 @@ window.__ModuleLoader__.load({
352
402
  .dte-dbg-levels b { color: var(--dsw-alias-brand-primary); font-weight: 600; }
353
403
  .dte-dbg-meta { display: flex; gap: 8px; margin-top: 1px; font-size: 10px; color: var(--dsw-alias-label-secondary); white-space: nowrap; overflow: hidden; }
354
404
  .dte-dbg-meta span { overflow: hidden; text-overflow: ellipsis; }
405
+ .dte-dbg-reason { flex: none; border-radius: 4px; padding: 0 4px; font-size: 10px; background: color-mix(in srgb, var(--dsw-alias-brand-primary) 14%, transparent); color: var(--dsw-alias-brand-primary); }
406
+ .dte-dbg-reason-plan { background: color-mix(in srgb, var(--dsw-alias-state-success-primary) 16%, transparent); color: var(--dsw-alias-state-success-primary); }
407
+ .dte-input-number { max-width: 180px; }
355
408
  .dte-dbg-empty { padding: 14px 12px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
356
409
  .dte-dbg-note { padding: 8px 12px; font-size: 11px; color: var(--dsw-alias-state-warn-primary); }
357
410
  .dte-dbg-foot { display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-top: 1px solid var(--dsw-alias-border-l1); font-size: 10px; color: var(--dsw-alias-label-secondary); }
@@ -442,6 +495,10 @@ window.__ModuleLoader__.load({
442
495
  const validate = () => {
443
496
  if (asArray(current.efforts).length === 0) return t('invalidEfforts');
444
497
  if (!validPattern(current.deepseekModelPattern)) return t('invalidPattern');
498
+ const threshold = current.adaptiveReasoningThreshold;
499
+ if (typeof threshold !== 'number' || !Number.isFinite(threshold) || threshold < 0) return t('adaptiveThresholdInvalid');
500
+ const rounds = current.adaptiveMinRounds;
501
+ if (typeof rounds !== 'number' || !Number.isFinite(rounds) || rounds < 1) return t('adaptiveRoundsInvalid');
445
502
  for (const entry of asArray(current.declareModels)) {
446
503
  if (entry.includes('/')) continue;
447
504
  if (!validPattern(entry)) return t('invalidPattern');
@@ -707,6 +764,83 @@ window.__ModuleLoader__.load({
707
764
  }),
708
765
  ],
709
766
  }),
767
+ Section({
768
+ title: t('sectionAdaptive'),
769
+ hint: t('adaptiveSectionHint'),
770
+ children: [
771
+ Row({
772
+ key: 'adaptiveEnabled',
773
+ label: t('adaptiveEnabledRow'),
774
+ hint: t('adaptiveEnabledHint'),
775
+ children: Switch({ checked: current.adaptiveEnabled === true, disabled: busy, label: current.adaptiveEnabled === true ? t('on') : t('off'), onChange: (next) => patch('adaptiveEnabled', next) }),
776
+ }),
777
+ Row({
778
+ key: 'adaptiveExploration',
779
+ label: t('adaptiveExplorationRow'),
780
+ hint: t('adaptiveExplorationHint'),
781
+ children: Switch({ checked: current.adaptiveExploration !== false, disabled: busy, label: current.adaptiveExploration === false ? t('off') : t('on'), onChange: (next) => patch('adaptiveExploration', next) }),
782
+ }),
783
+ Row({
784
+ key: 'adaptiveExplorationLevel',
785
+ label: t('adaptiveExplorationLevelRow'),
786
+ children: levelSelect('adaptiveExplorationLevel'),
787
+ }),
788
+ Row({
789
+ key: 'adaptiveTrigger',
790
+ label: t('adaptiveTriggerRow'),
791
+ hint: t('adaptiveTriggerHint'),
792
+ children: Select({
793
+ value: current.adaptiveTrigger ?? 'auto',
794
+ options: [
795
+ { value: 'auto', label: t('adaptiveTriggerAuto') },
796
+ { value: 'rounds', label: t('adaptiveTriggerRounds') },
797
+ { value: 'reasoning', label: t('adaptiveTriggerReasoning') },
798
+ ],
799
+ disabled: busy,
800
+ onChange: (next) => patch('adaptiveTrigger', next),
801
+ }),
802
+ }),
803
+ Row({
804
+ key: 'adaptiveThreshold',
805
+ label: t('adaptiveThresholdRow'),
806
+ hint: t('adaptiveThresholdHint'),
807
+ children: h('input', {
808
+ className: 'dte-input dte-input-number',
809
+ type: 'number',
810
+ min: 0,
811
+ step: 100,
812
+ value: current.adaptiveReasoningThreshold ?? 1500,
813
+ disabled: busy,
814
+ onChange: (event) => patch('adaptiveReasoningThreshold', event.target.value === '' ? 0 : Number(event.target.value)),
815
+ }),
816
+ }),
817
+ Row({
818
+ key: 'adaptiveRounds',
819
+ label: t('adaptiveMinRoundsRow'),
820
+ hint: t('adaptiveMinRoundsHint'),
821
+ children: h('input', {
822
+ className: 'dte-input dte-input-number',
823
+ type: 'number',
824
+ min: 1,
825
+ step: 1,
826
+ value: current.adaptiveMinRounds ?? 1,
827
+ disabled: busy,
828
+ onChange: (event) => patch('adaptiveMinRounds', event.target.value === '' ? 1 : Number(event.target.value)),
829
+ }),
830
+ }),
831
+ Row({
832
+ key: 'adaptivePlan',
833
+ label: t('adaptivePlanRow'),
834
+ hint: t('adaptivePlanHint'),
835
+ children: Switch({ checked: current.adaptivePlanMode !== false, disabled: busy, label: current.adaptivePlanMode === false ? t('off') : t('on'), onChange: (next) => patch('adaptivePlanMode', next) }),
836
+ }),
837
+ Row({
838
+ key: 'adaptivePlanLevel',
839
+ label: t('adaptivePlanLevelRow'),
840
+ children: levelSelect('adaptivePlanLevel'),
841
+ }),
842
+ ],
843
+ }),
710
844
  Section({
711
845
  title: t('debugSection'),
712
846
  hint: t('debugSectionHint'),
@@ -916,6 +1050,11 @@ window.__ModuleLoader__.load({
916
1050
  h('span', { className: 'dte-dbg-time' }, clockOf(entry?.at)),
917
1051
  entry?.subagent === true ? h('span', { className: 'dte-dbg-badge' }, t('debugSubagent')) : null,
918
1052
  h('span', { className: 'dte-dbg-purpose' }, purposeLabel(entry?.purpose, t)),
1053
+ entry?.reason === 'exploration'
1054
+ ? h('span', { className: 'dte-dbg-reason' }, t('debugReasonExploration'))
1055
+ : entry?.reason === 'plan'
1056
+ ? h('span', { className: 'dte-dbg-reason dte-dbg-reason-plan' }, t('debugReasonPlan'))
1057
+ : null,
919
1058
  h('span', { className: 'dte-dbg-levels' }, requested, ' → ', h('b', null, applied)),
920
1059
  entry?.changed === true
921
1060
  ? h('span', { className: 'dte-dbg-purpose', title: `${entry.from ?? '—'} → ${applied}` }, '⇄')
@@ -1027,7 +1166,7 @@ window.__ModuleLoader__.load({
1027
1166
  const copy = () => {
1028
1167
  const text = visible.map((entry) => {
1029
1168
  if (entry?.kind === 'request') {
1030
- return `${clockOf(entry.at)} ${entry.subagent === true ? '[sub]' : '[main]'} ${entry.provider}/${entry.model} ${entry.purpose ?? '-'} ${entry.requested ?? 'default'} -> ${entry.applied ?? 'default'}`;
1169
+ return `${clockOf(entry.at)} ${entry.subagent === true ? '[sub]' : '[main]'} ${entry.provider}/${entry.model} ${entry.purpose ?? '-'} ${entry.requested ?? 'default'} -> ${entry.applied ?? 'default'}${entry.reason ? ` [${entry.reason}]` : ''}`;
1031
1170
  }
1032
1171
  if (entry?.kind === 'capability') return `${clockOf(entry.at)} [capability] ${(entry.declared ?? []).join(', ')}`;
1033
1172
  return `${clockOf(entry.at)} [config] ${configText(entry ?? {}, t)}`;
package/cordis.patch.yml CHANGED
@@ -43,6 +43,23 @@
43
43
  autoScope: all
44
44
  # Subagent calls: inherit | auto | low/high/max. Applies immediately.
45
45
  subagentLevel: inherit
46
+ # Opt-in automatic difficulty (experimental; off by default). Only an
47
+ # Auto selection is considered; explicit levels and a fixed subagent
48
+ # level always win.
49
+ adaptiveEnabled: false
50
+ # Lower the depth after an expensive round while the turn still explores.
51
+ adaptiveExploration: true
52
+ adaptiveExplorationLevel: low
53
+ # Trigger rule: auto (reasoning tokens when the provider reports them,
54
+ # else assistant rounds) | rounds | reasoning.
55
+ adaptiveTrigger: auto
56
+ # Previous round's reasoning tokens that make exploration expensive.
57
+ adaptiveReasoningThreshold: 1500
58
+ # Assistant rounds in the turn before the exploration downgrade engages.
59
+ adaptiveMinRounds: 1
60
+ # Plan mode is an explicit signal: map it to its own depth.
61
+ adaptivePlanMode: true
62
+ adaptivePlanLevel: high
46
63
  # Record every effort decision for the conversation's floating debug
47
64
  # log (Settings -> Automatic thinking depth -> Debug). Off by default;
48
65
  # turning it on never changes a request.
package/docs/DETAIL.en.md CHANGED
@@ -9,6 +9,7 @@ Declarative thinking-depth control for DeepSeek (and other) reasoning models: th
9
9
  3. **Resolves per request.** At the adapter boundary `auto` becomes the declared default; a request whose `purpose` is a cheap host-owned call becomes `low` when the model declares it — regardless of the session's own choice, because those bounded calls never inherit it; a manually picked depth passes through untouched and is validated by DSH itself.
10
10
  4. **Subagent depth.** A subagent effort can be pinned (`inherit` / `auto` / `low`…`max`). `inherit` keeps DSH's native inheritance; a fixed depth overrides the child's own or inherited pick, while a cheap-call downgrade still wins.
11
11
  5. **Live debug log.** An optional floating window shows every request's effort decision (requested → sent), subagent sessions included. It records only; it never changes a request.
12
+ 6. **Automatic difficulty (experimental, off by default).** An exploration-phase downgrade and a plan-mode elevation that apply only to `Auto`; explicit depths, cheap calls, and fixed subagent depths always win.
12
13
 
13
14
  ## Usage
14
15
 
@@ -30,6 +31,18 @@ Turn on **Debug → Show the live effort-switch log in the conversation** and a
30
31
 
31
32
  Two halves: the Host half appends each decision, at the adapter boundary, to an **in-memory ring buffer** (300 records at most, never written to the session log or disk) and serves it through two `webServer` routes — a cursor-based read and a clear; the browser half polls only while the switch is on, and keeps the window's position and open state in browser storage. With the switch off the routes answer `enabled: false`, the window disappears, and recording stops.
32
33
 
34
+ ## Automatic difficulty (experimental)
35
+
36
+ The opt-in `adaptiveEnabled` switch. When on it applies only to the selector's `Auto`:
37
+
38
+ - **Exploration downgrade** (ported from Reasonix v1.38.1's experimental reasoning governor): a turn starts at the default depth. Once the trigger holds and the turn has not written or executed anything yet (`write`, `edit`, `apply_patch`, `bash`, `terminal_send`, …), later requests drop to `adaptiveExplorationLevel` (default `low`). The first write or local execution ends the phase and restores the default.
39
+ The trigger is `adaptiveTrigger`: `auto` (default) uses `adaptiveReasoningThreshold` (1500) when the provider reports `reasoningTokens`, and otherwise falls back to `adaptiveMinRounds` (1 assistant round); `rounds` and `reasoning` force one rule. Most OpenAI-compatible gateways report no reasoning tokens, which is why the round fallback exists.
40
+ - **Plan mode**: while `planMode` is active, Auto maps to `adaptivePlanLevel` (default `high`); the mapping can be turned off.
41
+ - **Precedence**: cheap calls (title/compaction/auto-review) → fixed `subagentLevel` → adaptive policy → Auto's default resolution. An explicit selector depth always passes through untouched; every adaptive suggestion is clamped to the model's declared vocabulary.
42
+ - **State**: per `sessionId` (parallel subagents never share a phase), reset on `turn/end`, exploration again after a Host restart; never written to the session log or disk.
43
+ - **Observability**: the floating log tags these rows `explore` / `plan`, and the journal records `reason`/`phase`.
44
+ - **Scope**: no failure escalation and no depth/preset maps in this release; it never guesses from prompt text or tool names.
45
+
33
46
  ## Where the settings page comes from
34
47
 
35
48
  - The row page registers into the plugin manager's `plugins.row.config`, keyed `dsh-think-effort#think-effort`.
@@ -60,6 +73,14 @@ Two halves: the Host half appends each decision, at the adapter boundary, to an
60
73
  | `auxLevel` | `low` | Depth those calls request |
61
74
  | `autoScope` | `all` | `all` / `declared` / `off` |
62
75
  | `subagentLevel` | `inherit` | Subagent depth: `inherit` / `auto` / a fixed depth; a fixed depth overrides the child's own or inherited pick |
76
+ | `adaptiveEnabled` | `false` | Automatic difficulty master switch (experimental; Auto only) |
77
+ | `adaptiveExploration` | `true` | Downgrade during exploration |
78
+ | `adaptiveExplorationLevel` | `low` | Depth used while exploring |
79
+ | `adaptiveTrigger` | `auto` | `auto` / `rounds` / `reasoning` |
80
+ | `adaptiveReasoningThreshold` | `1500` | Threshold for the reasoning rule |
81
+ | `adaptiveMinRounds` | `1` | Round count for the rounds rule |
82
+ | `adaptivePlanMode` | `true` | Map plan mode to a higher depth |
83
+ | `adaptivePlanLevel` | `high` | Depth used in plan mode |
63
84
  | `debugOverlay` | `false` | Live effort-switch log over the conversation (records only, never rewrites; 300 records in Host memory) |
64
85
  | `trace` | `false` | Write decisions to stderr for diagnosis |
65
86
 
package/docs/DETAIL.zh.md CHANGED
@@ -9,6 +9,7 @@
9
9
  3. **逐请求解析**:在适配器边界把 `auto` 换成声明默认档;`purpose` 属于廉价调用时换成 `low`(仅当模型声明了它,且**与会话选了什么都无关**——会话标题/图片摘要本来就不继承会话档位);手动选的档位一律原样透传,由 DSH 自己校验。
10
10
  4. **子代理档位**:可给子代理统一指定强度(`inherit` / `auto` / `low`…`max`)。`inherit` 保持 DSH 原生继承;固定档会覆盖子代理自身或从父代理继承的选择,廉价调用的降档仍然优先。
11
11
  5. **实时调试日志**:可选的悬浮窗,展示每次请求的档位决策(请求档位 → 实际档位),包括子代理会话;只记录,不改变任何请求。
12
+ 6. **自动难度(实验,默认关闭)**:只对 `Auto` 生效的探索阶段降档与计划模式映射;显式档位、廉价调用与固定子代理档位始终优先。
12
13
 
13
14
  ## 使用
14
15
 
@@ -30,6 +31,18 @@
30
31
 
31
32
  实现分两半:Host 半边在适配器边界把每条决策写入一个**内存环形缓冲**(最多 300 条,不写会话日志、不落盘),并通过两条 `webServer` 路由提供增量读取与清空;浏览器半边按开关状态轮询,只在打开时请求,窗口位置与展开状态存在浏览器本地。关掉开关后路由返回 `enabled: false`,窗口消失、记录停止。
32
33
 
34
+ ## 自动难度(实验)
35
+
36
+ 默认关闭的 `adaptiveEnabled` 总开关。打开后只对模型选择器里的 `Auto` 生效:
37
+
38
+ - **探索阶段降档**(移植自 Reasonix v1.38.1 的实验性 reasoning governor):一轮开始时按默认档;触发条件成立且本轮还没出现写文件/本地执行(`write`、`edit`、`apply_patch`、`bash`、`terminal_send` 等)时,后续请求降到 `adaptiveExplorationLevel`(默认 `low`);第一次写/执行即退出探索并恢复默认档。
39
+ 触发条件由 `adaptiveTrigger` 决定:`auto`(默认)在供应商上报 `reasoningTokens` 时用阈值 `adaptiveReasoningThreshold`(默认 1500),否则退回按轮次 `adaptiveMinRounds`(默认 1,即第一轮之后);`rounds` / `reasoning` 可强制其中一种。多数 OpenAI 兼容网关不返回 reasoning tokens,因此默认需要轮次回退。
40
+ - **计划模式**:`planMode` 激活时 Auto 落到 `adaptivePlanLevel`(默认 `high`),可关闭该映射。
41
+ - **优先级**:廉价调用(标题/压缩/复核)→ 固定 `subagentLevel` → 自动策略 → `Auto` 默认解析。用户显式选择的档位永远原样透传;自动建议一律 clamp 到模型已声明词表,不会发明档位。
42
+ - **状态**:按 `sessionId` 隔离(并行子代理互不影响),`turn/end` 重置,Host 重启后从探索态开始;不写会话日志、不落盘。
43
+ - **可观测**:调试悬浮窗给这类行加「探索 / 计划」标记,journal 记录 `reason`/`phase`。
44
+ - **范围**:本版本不含失败升档、按深度/preset 的多层映射,也不按提示词/工具名猜难度。
45
+
33
46
  ## 设置页从哪里来
34
47
 
35
48
  - 插件行页面注册进插件管理器的 `plugins.row.config`,键为 `dsh-think-effort#think-effort`;
@@ -60,6 +73,14 @@
60
73
  | `auxLevel` | `low` | 廉价调用用的档位 |
61
74
  | `autoScope` | `all` | `all` / `declared` / `off` |
62
75
  | `subagentLevel` | `inherit` | 子代理档位:`inherit` / `auto` / 固定档;固定档覆盖子代理自身或继承的选择 |
76
+ | `adaptiveEnabled` | `false` | 自动难度总开关(实验;只对 Auto 生效) |
77
+ | `adaptiveExploration` | `true` | 探索阶段降档 |
78
+ | `adaptiveExplorationLevel` | `low` | 探索阶段档位 |
79
+ | `adaptiveTrigger` | `auto` | `auto` / `rounds` / `reasoning` |
80
+ | `adaptiveReasoningThreshold` | `1500` | reasoning 规则的触发阈值 |
81
+ | `adaptiveMinRounds` | `1` | rounds 规则的触发轮次 |
82
+ | `adaptivePlanMode` | `true` | 计划模式映射高档 |
83
+ | `adaptivePlanLevel` | `high` | 计划模式档位 |
63
84
  | `debugOverlay` | `false` | 会话界面的实时档位切换日志(只记录,不改请求;Host 内存最多 300 条) |
64
85
  | `trace` | `false` | 把决策写到 stderr(排查用) |
65
86
 
Binary file
Binary file
package/index.js CHANGED
@@ -43,12 +43,14 @@ import z from '@deepseek-ai/schemastery';
43
43
 
44
44
  import {
45
45
  DEFAULT_CONFIG,
46
+ isAuxPurpose,
46
47
  normalizeConfig,
47
48
  planCapabilitySection,
48
49
  resolveCallEffort,
49
50
  shouldDeclare,
50
51
  withAutoEffort,
51
52
  } from './src/policy.js';
53
+ import { createAdaptivePolicy } from './src/adaptive.js';
52
54
  import { createDebugJournal, registerDebugRoutes } from './src/debug.js';
53
55
 
54
56
  /** The llm-pi-ai settings entry id in a composed profile. */
@@ -89,6 +91,22 @@ export const Config = z.object({
89
91
  auxLevel: z.string().default(DEFAULT_CONFIG.auxLevel).volatile(),
90
92
  /** Subagent-owned calls: `inherit`, `auto`, or a fixed level. */
91
93
  subagentLevel: z.string().default(DEFAULT_CONFIG.subagentLevel).volatile(),
94
+ /** Opt-in automatic difficulty policy; off by default. */
95
+ adaptiveEnabled: z.boolean().default(DEFAULT_CONFIG.adaptiveEnabled).volatile(),
96
+ /** Lower the depth while a turn is still exploring after an expensive round. */
97
+ adaptiveExploration: z.boolean().default(DEFAULT_CONFIG.adaptiveExploration).volatile(),
98
+ /** Depth used during the exploration phase. */
99
+ adaptiveExplorationLevel: z.string().default(DEFAULT_CONFIG.adaptiveExplorationLevel).volatile(),
100
+ /** Previous round's reasoning tokens that make exploration expensive. */
101
+ adaptiveReasoningThreshold: z.number().default(DEFAULT_CONFIG.adaptiveReasoningThreshold).volatile(),
102
+ /** Trigger rule: `auto` (reasoning when reported, else rounds), `rounds`, `reasoning`. */
103
+ adaptiveTrigger: z.union([z.const('auto'), z.const('rounds'), z.const('reasoning')]).default(DEFAULT_CONFIG.adaptiveTrigger).volatile(),
104
+ /** Assistant rounds in the turn before the exploration downgrade engages. */
105
+ adaptiveMinRounds: z.number().default(DEFAULT_CONFIG.adaptiveMinRounds).volatile(),
106
+ /** Explicit plan mode maps to a higher depth. */
107
+ adaptivePlanMode: z.boolean().default(DEFAULT_CONFIG.adaptivePlanMode).volatile(),
108
+ /** Depth used while plan mode is active. */
109
+ adaptivePlanLevel: z.string().default(DEFAULT_CONFIG.adaptivePlanLevel).volatile(),
92
110
  /**
93
111
  * Record every effort decision in a bounded in-memory journal and serve it to
94
112
  * the conversation's floating debug log. Off by default; when off the journal
@@ -354,8 +372,9 @@ export function apply(ctx, rawConfig) {
354
372
  * @param {string} input.model model id.
355
373
  * @param {object} input.options the request options the adapter receives.
356
374
  * @param {string} [input.level] the level the plugin applied, if any.
375
+ * @param {object} [input.adaptive] the automatic-difficulty decision.
357
376
  */
358
- const debugRequest = ({ provider, model, options, level }) => {
377
+ const debugRequest = ({ provider, model, options, level, adaptive = {} }) => {
359
378
  if (debugOn() !== true) return;
360
379
  // An ordinary agent step usually carries no purpose; name it explicitly so
361
380
  // the browser half can label it instead of showing "unknown".
@@ -377,9 +396,73 @@ export function apply(ctx, rawConfig) {
377
396
  switched: level !== undefined && level !== requested,
378
397
  from: previous,
379
398
  changed: previous !== null && previous !== applied,
399
+ reason: adaptive.reason ?? null,
400
+ phase: adaptive.phase ?? null,
380
401
  });
381
402
  };
382
403
 
404
+ // ── adaptive difficulty ──────────────────────────────────────────────────
405
+ // Opt-in policy: the phase state is folded from committed Session events and
406
+ // only consulted for `auto` requests. Every state is per Session, so parallel
407
+ // subagents never inherit each other's phase.
408
+ const adaptive = createAdaptivePolicy();
409
+ ctx.on('session/event', (session, event) => {
410
+ if (config.adaptiveEnabled !== true) return;
411
+ const sessionId = session?.id ?? session?.header?.id;
412
+ if (typeof sessionId !== 'string' || sessionId === '') return;
413
+ try {
414
+ adaptive.observe(sessionId, event);
415
+ } catch {
416
+ /* a malformed event must not affect a turn */
417
+ }
418
+ });
419
+
420
+ /** Whether plan mode is active for one live Session. */
421
+ const planStateOf = (sessionId) => {
422
+ if (typeof sessionId !== 'string' || sessionId === '') return { active: false, why: 'no-session' };
423
+ try {
424
+ const agent = ctx.get('agents')?.get?.(sessionId);
425
+ if (agent === undefined) return { active: false, why: 'no-agent' };
426
+ // Plan mode is composed per agent preset, so its service may live in the
427
+ // agent's own context rather than the profile root; ask the preset
428
+ // registry for the agent-scoped face first and keep a root fallback for
429
+ // compositions that mount it globally.
430
+ const planMode = ctx.get('agentPresets')?.serviceFor?.(agent, 'planMode') ?? ctx.get('planMode');
431
+ if (planMode === undefined) return { active: false, why: 'no-service' };
432
+ const state = planMode.get(agent);
433
+ return { active: state?.active === true, why: `state:${String(state?.active)}:${String(state?.pending)}` };
434
+ } catch (error) {
435
+ return { active: false, why: `error:${error instanceof Error ? error.message : String(error)}` };
436
+ }
437
+ };
438
+
439
+ /**
440
+ * Ask the adaptive policy for one request's suggestion.
441
+ *
442
+ * Cheap calls and a fixed `subagentLevel` keep their precedence: the policy
443
+ * is not consulted for them at all, so a journal reason always describes a
444
+ * decision that could actually apply.
445
+ * @param {object} input request facts.
446
+ * @param {string} [input.requested] the selection's effort.
447
+ * @param {string} [input.purpose] LLM request purpose.
448
+ * @param {boolean} input.isSubagent whether the call belongs to a subagent.
449
+ * @param {string} [input.sessionId] stamped session identity.
450
+ * @returns {object} the policy decision.
451
+ */
452
+ const adaptiveDecisionFor = ({ requested, purpose, isSubagent, sessionId }) => {
453
+ const none = { level: undefined, reason: null, phase: null };
454
+ if (config.adaptiveEnabled !== true) return none;
455
+ if (requested !== 'auto') return none;
456
+ if (isAuxPurpose(purpose, config)) return none;
457
+ if (isSubagent === true && config.subagentLevel !== 'inherit' && config.subagentLevel !== 'auto') return none;
458
+ const planState = planStateOf(sessionId);
459
+ const decision = adaptive.decide(sessionId, { requested, planActive: planState.active, config });
460
+ if (config.trace === true) {
461
+ trace('adaptive: session=%s plan=%s (%s) level=%s reason=%s', String(sessionId), planState.active, planState.why, String(decision.level), String(decision.reason));
462
+ }
463
+ return decision;
464
+ };
465
+
383
466
  // ── capability declaration ───────────────────────────────────────────────
384
467
  /** Serialize settings writes; a boot burst must not stack whole-section updates. */
385
468
  let syncTail = Promise.resolve();
@@ -437,14 +520,22 @@ export function apply(ctx, rawConfig) {
437
520
  if (config.enabled === false) return options;
438
521
  if (options === null || typeof options !== 'object') return options;
439
522
  const reasoning = info !== null && typeof info === 'object' ? info.reasoning : undefined;
523
+ const subagent = isSubagentSession(options.sessionId);
524
+ const adaptiveDecision = adaptiveDecisionFor({
525
+ requested: options.reasoningEffort,
526
+ purpose: options.purpose,
527
+ isSubagent: subagent,
528
+ sessionId: options.sessionId,
529
+ });
440
530
  const level = resolveCallEffort({
441
531
  requested: options.reasoningEffort,
442
532
  purpose: options.purpose,
443
- isSubagent: isSubagentSession(options.sessionId),
533
+ isSubagent: subagent,
444
534
  efforts: reasoning !== null && typeof reasoning === 'object' ? reasoning.efforts : undefined,
445
535
  defaultEffort: reasoning !== null && typeof reasoning === 'object' ? reasoning.defaultEffort : undefined,
536
+ adaptiveLevel: adaptiveDecision.level,
446
537
  }, config);
447
- debugRequest({ provider, model, options, level });
538
+ debugRequest({ provider, model, options, level, adaptive: adaptiveDecision });
448
539
  if (level === undefined || level === options.reasoningEffort) return options;
449
540
  const key = `${provider}/${model}/${String(options.purpose ?? '-')}/${level}`;
450
541
  trace('translate: %s/%s purpose=%s requested=%s -> %s', provider, model, String(options.purpose ?? '-'), String(options.reasoningEffort), level);
@@ -534,6 +625,7 @@ export function apply(ctx, rawConfig) {
534
625
  trace('volatile update: enabled=%s subagentLevel=%s', config.enabled, config.subagentLevel);
535
626
  debugRecord('config', {
536
627
  enabled: config.enabled,
628
+ adaptiveEnabled: config.adaptiveEnabled,
537
629
  debugOverlay: config.debugOverlay,
538
630
  autoLevel: config.autoLevel,
539
631
  defaultEffort: config.defaultEffort,
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Automatic thinking depth",
4
- "description": "Adds Auto to the model selector for reasoning models and resolves it per request: the declared default for normal steps (high on DeepSeek), Low for cheap host-owned calls, and an optional depth just for subagents — all editable on a live visual settings page. A debug switch shows every request's effort decision (subagents included) in a floating log over the conversation.",
4
+ "description": "Adds Auto to the model selector for reasoning models and resolves it per request: the declared default for normal steps (high on DeepSeek), Low for cheap host-owned calls, and an optional depth just for subagents — all editable on a live visual settings page. A debug switch shows every request's effort decision (subagents included) in a floating log over the conversation, and an experimental opt-in automatic difficulty lowers depth during exploration and raises it in plan mode (Auto only).",
5
5
  "detail": "docs/DETAIL.en.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "自动思考档位",
4
- "description": "为推理模型在模型选择器里加上 Auto,并逐请求解析:普通步骤用声明的默认档(DeepSeek 为 high),廉价调用用 low,子代理可单独指定强度;全部规则都能在可视化设置页即时调整。打开调试开关后,每次请求的档位决策(含子代理)会实时显示在会话界面的悬浮窗里。",
4
+ "description": "为推理模型在模型选择器里加上 Auto,并逐请求解析:普通步骤用声明的默认档(DeepSeek 为 high),廉价调用用 low,子代理可单独指定强度;全部规则都能在可视化设置页即时调整。打开调试开关后,每次请求的档位决策(含子代理)会实时显示在会话界面的悬浮窗里。另有一个默认关闭的实验性自动难度:探索阶段降档、计划模式用高档,只对 Auto 生效。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-think-effort",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
- "description": "Automatic thinking depth for DeepSeek routes in DeepSeek Harness: declare the model's effort vocabulary, add Auto to the model selector, resolve it to the declared default, give subagents their own depth, drop cheap host-owned calls to Low, edit every rule on a live visual settings page, and watch each request's effort decision live in a floating debug log over the conversation.",
5
+ "description": "Automatic thinking depth for DeepSeek routes in DeepSeek Harness: declare the model's effort vocabulary, add Auto to the model selector, resolve it to the declared default, give subagents their own depth, drop cheap host-owned calls to Low, edit every rule on a live visual settings page, watch each request's effort decision in a floating debug log, and optionally lower depth during exploration with the experimental adaptive policy.",
6
6
  "icon": "./icon.svg",
7
7
  "license": "MIT",
8
8
  "author": "mhlywxl",
@@ -16,7 +16,9 @@
16
16
  "subagent",
17
17
  "settings-page",
18
18
  "debug-overlay",
19
- "live-log"
19
+ "live-log",
20
+ "adaptive-effort",
21
+ "exploration"
20
22
  ],
21
23
  "exports": {
22
24
  ".": "./index.js",
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Opt-in automatic difficulty policy: the exploration-phase downgrade ported
3
+ * from Reasonix's retired reasoning governor, adapted to DSH's session events.
4
+ *
5
+ * <h2>What it does</h2>
6
+ *
7
+ * With `adaptiveEnabled` on and the selector on `Auto`, a turn starts at the
8
+ * normal default depth. Once the turn is still exploring — no mutating or local
9
+ * execution tool has run — and the trigger condition holds, later requests in
10
+ * that turn drop to `adaptiveExplorationLevel`. The first write or local
11
+ * execution ends the exploration phase and the default depth returns. Plan mode
12
+ * is an explicit user signal and maps to `adaptivePlanLevel` instead.
13
+ *
14
+ * The trigger is deliberately configurable because not every gateway reports
15
+ * reasoning tokens. `adaptiveTrigger: 'auto'` uses the reasoning-token threshold
16
+ * when the provider reports `usage.reasoningTokens`, and otherwise falls back to
17
+ * the number of assistant rounds (`adaptiveMinRounds`, default 1). `'rounds'`
18
+ * and `'reasoning'` force one rule.
19
+ *
20
+ * <h2>What it deliberately does NOT do</h2>
21
+ *
22
+ * It never inspects prompt text, tool names for difficulty, or argument sizes.
23
+ * It never overrides an explicit selector choice, a fixed `subagentLevel`, or a
24
+ * cheap-call downgrade; those decisions happen in `src/policy.js` before this
25
+ * policy is consulted. It is off by default and resets every turn.
26
+ *
27
+ * The reference implementation is Reasonix v1.38.1 `internal/agent/governor.go`
28
+ * (`govReasoningThreshold = 1500`, exploration cell, env-gated enforcement);
29
+ * that experiment was retired in Reasonix v1.39.11, which is why this is an
30
+ * opt-in experiment rather than default behavior.
31
+ *
32
+ * @module dsh-think-effort/adaptive
33
+ */
34
+
35
+ /** Journal reason for an exploration-phase downgrade. */
36
+ export const REASON_EXPLORATION = 'exploration';
37
+ /** Journal reason for a plan-mode elevation. */
38
+ export const REASON_PLAN = 'plan';
39
+
40
+ /** Tool names whose call means local execution has started. */
41
+ export const LOCAL_EXEC_TOOLS = new Set([
42
+ 'bash',
43
+ 'pwsh',
44
+ 'run_code',
45
+ 'cordis_run',
46
+ 'terminal_send',
47
+ 'terminal_signal',
48
+ ]);
49
+
50
+ /** Tool names whose call mutates the workspace. */
51
+ export const MUTATING_TOOLS = new Set([
52
+ 'write',
53
+ 'edit',
54
+ 'apply_patch',
55
+ 'multi_edit',
56
+ 'str_replace_editor',
57
+ 'notebook_edit',
58
+ ]);
59
+
60
+ /**
61
+ * Classify one tool name for the exploration phase.
62
+ * @param {unknown} name tool name.
63
+ * @returns {'exec'|'mutate'|'other'} the classification.
64
+ */
65
+ export function classifyTool(name) {
66
+ if (typeof name !== 'string' || name === '') return 'other';
67
+ if (LOCAL_EXEC_TOOLS.has(name)) return 'exec';
68
+ if (MUTATING_TOOLS.has(name)) return 'mutate';
69
+ return 'other';
70
+ }
71
+
72
+ /**
73
+ * Create the per-session adaptive policy.
74
+ *
75
+ * One instance is owned by `apply()`; states are keyed by Session id, so
76
+ * parallel main sessions and subagents never share a phase. Nothing is
77
+ * persisted: a Host restart simply starts every session in exploration again.
78
+ *
79
+ * @returns {object} the policy.
80
+ */
81
+ export function createAdaptivePolicy() {
82
+ /** @type {Map<string, {exploring: boolean, lastReasoning: number, rounds: number, reasoningReported: boolean}>} */
83
+ const states = new Map();
84
+
85
+ const fresh = () => ({ exploring: true, lastReasoning: 0, rounds: 0, reasoningReported: false });
86
+ const stateOf = (sessionId) => {
87
+ const existing = states.get(sessionId);
88
+ if (existing !== undefined) return existing;
89
+ const state = fresh();
90
+ states.set(sessionId, state);
91
+ return state;
92
+ };
93
+
94
+ return {
95
+ /** Number of tracked sessions (tests and diagnostics). */
96
+ get size() {
97
+ return states.size;
98
+ },
99
+
100
+ /**
101
+ * Fold one committed Session event into the phase state.
102
+ * @param {string} sessionId Session identity.
103
+ * @param {object} event committed `SessionEvent`.
104
+ */
105
+ observe(sessionId, event) {
106
+ if (typeof sessionId !== 'string' || sessionId === '') return;
107
+ if (event === null || typeof event !== 'object') return;
108
+ switch (event.type) {
109
+ case 'turn/start':
110
+ states.set(sessionId, fresh());
111
+ return;
112
+ case 'turn/end':
113
+ states.delete(sessionId);
114
+ return;
115
+ case 'assistant/message': {
116
+ const state = stateOf(sessionId);
117
+ state.rounds += 1;
118
+ const tokens = event.data?.usage?.reasoningTokens;
119
+ if (typeof tokens === 'number' && Number.isFinite(tokens)) {
120
+ state.lastReasoning = tokens;
121
+ state.reasoningReported = true;
122
+ }
123
+ return;
124
+ }
125
+ case 'tool/call':
126
+ if (classifyTool(event.data?.name) !== 'other') {
127
+ stateOf(sessionId).exploring = false;
128
+ }
129
+ return;
130
+ default:
131
+ return;
132
+ }
133
+ },
134
+
135
+ /**
136
+ * Decide the adaptive depth for one request.
137
+ *
138
+ * Only an `auto` request is considered; explicit selections belong to the
139
+ * caller. The returned level is a *suggestion*: the policy resolver clamps
140
+ * it to the model's declared vocabulary and applies the precedence rules.
141
+ *
142
+ * @param {string} sessionId Session identity.
143
+ * @param {object} input decision inputs.
144
+ * @param {string} [input.requested] the selection's effort.
145
+ * @param {boolean} [input.planActive] whether plan mode is active.
146
+ * @param {object} input.config normalized plugin config.
147
+ * @returns {{level: string|undefined, reason: string|null, phase: string|null, lastReasoning: number}} the decision.
148
+ */
149
+ decide(sessionId, { requested, planActive, config }) {
150
+ const none = { level: undefined, reason: null, phase: null, lastReasoning: 0, rounds: 0 };
151
+ if (config?.adaptiveEnabled !== true) return none;
152
+ if (requested !== 'auto') return none;
153
+ if (planActive === true && config.adaptivePlanMode !== false) {
154
+ const planState = stateOf(sessionId);
155
+ return {
156
+ level: config.adaptivePlanLevel,
157
+ reason: REASON_PLAN,
158
+ phase: 'plan',
159
+ lastReasoning: planState.lastReasoning,
160
+ rounds: planState.rounds,
161
+ };
162
+ }
163
+ if (config.adaptiveExploration === false) return none;
164
+ const state = stateOf(sessionId);
165
+ if (state.exploring !== true) {
166
+ return { level: undefined, reason: null, phase: 'executing', lastReasoning: state.lastReasoning, rounds: state.rounds };
167
+ }
168
+ const threshold = Number.isFinite(config.adaptiveReasoningThreshold)
169
+ ? Number(config.adaptiveReasoningThreshold)
170
+ : 1500;
171
+ const minRounds = Number.isFinite(config.adaptiveMinRounds) ? Number(config.adaptiveMinRounds) : 1;
172
+ const trigger = config.adaptiveTrigger;
173
+ const reasoningRule = trigger === 'reasoning' || (trigger !== 'rounds' && state.reasoningReported);
174
+ const engaged = reasoningRule
175
+ ? state.reasoningReported && state.lastReasoning >= threshold
176
+ : state.rounds >= minRounds;
177
+ if (engaged) {
178
+ return {
179
+ level: config.adaptiveExplorationLevel,
180
+ reason: REASON_EXPLORATION,
181
+ phase: 'exploring',
182
+ lastReasoning: state.lastReasoning,
183
+ rounds: state.rounds,
184
+ };
185
+ }
186
+ return {
187
+ level: undefined,
188
+ reason: null,
189
+ phase: 'exploring',
190
+ lastReasoning: state.lastReasoning,
191
+ rounds: state.rounds,
192
+ };
193
+ },
194
+
195
+ /** Forget one session (tests and disposal). */
196
+ reset(sessionId) {
197
+ states.delete(sessionId);
198
+ },
199
+
200
+ /** Forget every session; a Host teardown needs no replay. */
201
+ clear() {
202
+ states.clear();
203
+ },
204
+ };
205
+ }
package/src/policy.js CHANGED
@@ -92,6 +92,22 @@ export const DEFAULT_CONFIG = {
92
92
  * id forces that depth (clamped to the model's declared vocabulary).
93
93
  */
94
94
  subagentLevel: 'inherit',
95
+ /** Opt-in automatic difficulty policy (off by default). */
96
+ adaptiveEnabled: false,
97
+ /** Lower the depth while a turn is still exploring after an expensive round. */
98
+ adaptiveExploration: true,
99
+ /** Depth used during the exploration phase. */
100
+ adaptiveExplorationLevel: 'low',
101
+ /** Previous round's reasoning tokens that make exploration expensive. */
102
+ adaptiveReasoningThreshold: 1500,
103
+ /** Trigger rule: `auto` (reasoning when reported, else rounds), `rounds`, `reasoning`. */
104
+ adaptiveTrigger: 'auto',
105
+ /** Assistant rounds in the turn before the exploration downgrade engages. */
106
+ adaptiveMinRounds: 1,
107
+ /** Explicit plan mode maps to a higher depth. */
108
+ adaptivePlanMode: true,
109
+ /** Depth used while plan mode is active. */
110
+ adaptivePlanLevel: 'high',
95
111
  /** Record every effort decision for the conversation's floating debug log. */
96
112
  debugOverlay: false,
97
113
  /** Diagnostic stderr trace of each decision. */
@@ -105,6 +121,21 @@ export function normalizeConfig(raw) {
105
121
  if (!Array.isArray(config.auxPurposes)) config.auxPurposes = [...DEFAULT_CONFIG.auxPurposes];
106
122
  if (!Array.isArray(config.deepseekHosts)) config.deepseekHosts = [...DEFAULT_CONFIG.deepseekHosts];
107
123
  if (!Array.isArray(config.declareModels)) config.declareModels = [];
124
+ // A threshold is a non-negative token count; a broken value must not make the
125
+ // policy behave as "always zero".
126
+ if (typeof config.adaptiveReasoningThreshold !== 'number'
127
+ || !Number.isFinite(config.adaptiveReasoningThreshold)
128
+ || config.adaptiveReasoningThreshold < 0) {
129
+ config.adaptiveReasoningThreshold = DEFAULT_CONFIG.adaptiveReasoningThreshold;
130
+ }
131
+ if (config.adaptiveTrigger !== 'rounds' && config.adaptiveTrigger !== 'reasoning') {
132
+ config.adaptiveTrigger = 'auto';
133
+ }
134
+ if (typeof config.adaptiveMinRounds !== 'number'
135
+ || !Number.isFinite(config.adaptiveMinRounds)
136
+ || config.adaptiveMinRounds < 1) {
137
+ config.adaptiveMinRounds = DEFAULT_CONFIG.adaptiveMinRounds;
138
+ }
108
139
  return config;
109
140
  }
110
141
 
@@ -411,15 +442,17 @@ function autoTarget(cfg, efforts, defaultEffort) {
411
442
  * unconditionally, because a session's own depth never applies to a bounded
412
443
  * summary request.
413
444
  * 2. A subagent-owned call with `subagentLevel` set → that level, or the
414
- * plugin's `auto` resolution for `auto`. The child's own selection and
445
+ * plugin's `auto` resolution for `auto`. A fixed pin outranks the adaptive
446
+ * suggestion; `auto` lets it through. The child's own selection and
415
447
  * inherited parent selection are overridden only when the user opted in.
416
448
  * 3. An explicit level → `undefined`: a user pick is passed through untouched
417
449
  * (DSH validates it against the same vocabulary, so an undeclared pick never
418
450
  * reaches the wire).
419
451
  * 4. No explicit selection on an ordinary call → `undefined`: the adapter's own
420
452
  * default stands (with the declaration above, that is `high`).
421
- * 5. `auto` → the declared route default (DeepSeek: `high`), or the
422
- * highest declared depth when the route names none.
453
+ * 5. `auto` → the adaptive suggestion when the opt-in policy produced one,
454
+ * otherwise the declared route default (DeepSeek: `high`), or the highest
455
+ * declared depth when the route names none.
423
456
  *
424
457
  * @param {object} input decision inputs.
425
458
  * @param {string} [input.requested] the selection's effort.
@@ -427,10 +460,12 @@ function autoTarget(cfg, efforts, defaultEffort) {
427
460
  * @param {boolean} [input.isSubagent] whether the call belongs to a subagent session.
428
461
  * @param {readonly object[]} [input.efforts] declared vocabulary.
429
462
  * @param {string} [input.defaultEffort] route/model default depth.
463
+ * @param {string} [input.adaptiveLevel] the automatic-difficulty suggestion for
464
+ * an `auto` request, already limited to the request's session and phase.
430
465
  * @param {object} rawCfg plugin config.
431
466
  * @returns {string | undefined} the level to send, or undefined to leave the request alone.
432
467
  */
433
- export function resolveCallEffort({ requested, purpose, isSubagent, efforts, defaultEffort }, rawCfg) {
468
+ export function resolveCallEffort({ requested, purpose, isSubagent, efforts, defaultEffort, adaptiveLevel }, rawCfg) {
434
469
  const cfg = normalizeConfig(rawCfg);
435
470
  const depths = depthLevels(efforts);
436
471
  if (depths.length === 0) return undefined;
@@ -441,12 +476,16 @@ export function resolveCallEffort({ requested, purpose, isSubagent, efforts, def
441
476
  // still win, because a summary request has no task difficulty to describe.
442
477
  if (isSubagent === true && cfg.subagentLevel !== undefined && cfg.subagentLevel !== 'inherit') {
443
478
  if (aux !== undefined) return aux;
444
- return cfg.subagentLevel === AUTO_EFFORT
445
- ? autoTarget(cfg, efforts, defaultEffort)
446
- : clampEffort(cfg.subagentLevel, efforts);
479
+ if (cfg.subagentLevel !== AUTO_EFFORT) return clampEffort(cfg.subagentLevel, efforts);
480
+ // `auto` for subagents is the same Auto the selector offers, so the
481
+ // adaptive policy may suggest a depth for it as well.
482
+ return adaptiveLevel !== undefined
483
+ ? clampEffort(adaptiveLevel, efforts)
484
+ : autoTarget(cfg, efforts, defaultEffort);
447
485
  }
448
486
  if (requested !== undefined && requested !== AUTO_EFFORT) return undefined;
449
487
  if (aux !== undefined) return aux;
450
488
  if (requested === undefined) return undefined;
489
+ if (adaptiveLevel !== undefined) return clampEffort(adaptiveLevel, efforts);
451
490
  return autoTarget(cfg, efforts, defaultEffort);
452
491
  }