dsh-think-effort 0.0.0-stage → 0.2.1

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 ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## 0.2.1 — 2026-11-24
4
+
5
+ - `package.json` 增加有界宿主声明 `engines.dsh: ">=0.2.0-rc.1 <0.3.0-0"`,插件市场与插件管理器可据此判断兼容性。
6
+ - 发布链路切换到 npm Trusted Publishing(OIDC + provenance),仓库不再保存 npm token。
7
+
8
+ ## 0.2.0 — 2026-11-24
9
+
10
+ 更名:包名与目录改为 **`dsh-think-effort`**,插件行 id 改为 `think-effort`,日志前缀与内部符号同步改名。行为与配置字段不变。
11
+ 安装迁移:旧 bundle 先移除再安装新包;`llm-pi-ai` 里已写入的档位声明无需重做。
12
+
13
+ ## 0.1.0 — 2026-11-24
14
+
15
+ 首个版本:声明式思考档位(Auto / 默认档 / 廉价调用降档)。
16
+
17
+ - 按 endpoint / 模型 ID 自动为 `llm-pi-ai` 的 DeepSeek 模型声明 `reasoningEfforts`(`low / high / max`)与路由默认档 `high`;已有声明(包括 `false`)不覆盖。
18
+ - 模型选择器新增 `Auto`(适配器 `resolveModel` facade 注入)。
19
+ - 适配器边界逐请求解析:`auto` → 声明默认档;`session-title` / `compaction` / `auto-review` → `low`(仅当模型声明);显式档位透传。
20
+ - 卸载时还原适配器注册表,并把仍为 `auto` 的活动会话选择退回默认档。
21
+ - 新增只读诊断工具 `reasoning_effort_status`。
22
+ - 能力声明幂等(第二次启动零写入),并提供 boot 重试、配置冲突重规划与 `trace` 诊断开关。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mhlywxl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,226 @@
1
- # Temporary Holding Version
1
+ # dsh-think-effort
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **中文(默认)** · [English](#english)
4
+
5
+ 给 DeepSeek Harness(DSH)加一套**声明式自动思考档位**:模型选择器里出现 `Auto`,普通步骤落到模型声明的默认档(DeepSeek 为 `high`),会话标题、上下文压缩、自动复审这类由 Harness 自己发起的廉价调用自动用 `low`。
6
+
7
+ ## 快速开始
8
+
9
+ ### 先选运行方式
10
+
11
+ | 方式 | 适用场景 | 插件安装位置 |
12
+ | --- | --- | --- |
13
+ | Web(`dsh web`,浏览器打开) | 浏览器试用、远程机器 | `web` profile |
14
+ | 桌面端 DSH Desktop | 日常使用,推荐 | `desktop` profile,由桌面端独占管理 |
15
+
16
+ ### Web:在线安装
17
+
18
+ ```sh
19
+ dsh plugin --profile web add dsh-think-effort
20
+ dsh --profile web
21
+ ```
22
+
23
+ ### Web:离线安装
24
+
25
+ 在联网机器上取包(任一来源):
26
+
27
+ ```sh
28
+ npm pack dsh-think-effort # 产出 dsh-think-effort-<version>.tgz
29
+ # 或者从 GitHub Release 下载同名 .tgz
30
+ ```
31
+
32
+ 把 `.tgz` 拷到目标机后:
33
+
34
+ ```sh
35
+ dsh plugin --profile web add /abs/path/dsh-think-effort-<version>.tgz
36
+ dsh --profile web
37
+ ```
38
+
39
+ 也可以解压后安装目录:`dsh plugin --profile web add /abs/path/dsh-think-effort`。
40
+
41
+ ### Desktop:在线安装
42
+
43
+ DSH Desktop → **插件市场**搜索 `dsh-think-effort` 安装;或 **插件 → 添加插件 → 安装第三方插件**,填包名 `dsh-think-effort`。
44
+
45
+ > 桌面端的 `desktop` profile 由 Electron 应用独占管理,**不要**执行 `dsh plugin --profile desktop add ...`(会报 “profile desktop is managed exclusively by the Electron application”)。
46
+
47
+ ### Desktop:离线安装
48
+
49
+ 把 `.tgz`(或解压后的目录,根下要有 `package.json`)拷到目标机 → **插件 → 添加插件 → 安装第三方插件** → 填 `.tgz` 的绝对路径(界面会识别为「压缩包」),或填解压后的目录路径。目标机不需要 npm 或 GitHub。
50
+
51
+ ### 启用与验证
52
+
53
+ 1. 安装后打开 **设置 → 插件**,确认 `dsh-think-effort` 已启用;桌面端需**完全退出并重开** DSH,Web 端需重启 `dsh web` 并硬刷新页面。
54
+ 2. 输入框右侧的模型 chip 应从 `deepseek-v4.1-flash-1017` 变成 `deepseek-v4.1-flash-1017 High`(或你模型的默认档)。
55
+ 3. 点开 chip →「推理等级」,应能看到 `Auto / Low / High / Max`。
56
+ 4. 想核对具体模型,可让 Agent 调用只读工具 `reasoning_effort_status`,它会报告该模型声明的档位、默认档、`Auto` 的解析结果与廉价调用档位,不发送任何模型请求。
57
+
58
+ ### 本插件的第一次使用
59
+
60
+ 装上后不需要额外配置:`Auto` 与档位由插件自动声明。选中 `Auto` 即按默认档运行;选 `Low / High / Max` 即固定该档;不选(原生「提供方默认」)在普通步骤上与 `Auto` 等效。
61
+
62
+ ## 为什么需要它
63
+
64
+ 手工在 `llm-pi-ai` 里声明的 DeepSeek 网关模型(例如走自建网关的 `deepseek-v4.1-flash-1017`)在 pi-ai 的已安装目录里查不到,profile 里也没写 `reasoningEfforts`,于是:
65
+
66
+ - 模型选择器只有模型名,没有任何思考档位;
67
+ - 任何 `reasoningEffort` 都会在请求前被 `UNSUPPORTED_REASONING_EFFORT` 拒绝。
68
+
69
+ 同类插件通常只在模型**已经有**推理元数据时才追加 `Auto`,所以在这些网关上什么都不会出现。本插件先把能力声明补上,再谈切换。
70
+
71
+ ## 它怎么工作
72
+
73
+ | 步骤 | 实现 |
74
+ | --- | --- |
75
+ | 识别 | host 后缀(`deepseek.com`)或模型 ID 正则(`^deepseek`,可用 `declareModels` 扩展) |
76
+ | 声明 | 向 `llm-pi-ai` 的 `providers.<route>.models[].reasoningEfforts` 写入 `{low, high, max}`,并在路由上写 `reasoning: high`;已有声明不覆盖;幂等 |
77
+ | `Auto` | 包装适配器的 `resolveModel`,在 `reasoning.efforts` 最前面插入 `{id:'auto',name:'Auto'}`,模型选择器即可显示 |
78
+ | 解析 | 包装 `prepareCall().stream`:`auto` → 声明默认档;`purpose ∈ auxPurposes` → `auxLevel`(未声明则回落默认档,且与会话选择无关);显式档位不动 |
79
+ | 卸载 | 还原被替换的注册表条目,并把仍为 `auto` 的活动会话选择退回默认档 |
80
+
81
+ 决策放在**适配器边界**,是因为 DSH 在插件看到这一步之前就固定了 `modelSelection`,而 `llm/stream` waterfall 的 `next()` 不接受新参数——只有适配器 facade 能改到「提供商真正收到的 options」。
82
+
83
+ ## 配置
84
+
85
+ 在 profile 的 `cordis.patch.yml` 里覆盖 `think-effort` 行(会完整替换 `config`,请写全要保留的字段):
86
+
87
+ ```yaml
88
+ - id: think-effort
89
+ config:
90
+ enabled: true
91
+ declareCapability: true
92
+ deepseekHosts: [deepseek.com]
93
+ deepseekModelPattern: '^deepseek'
94
+ declareModels: []
95
+ efforts: [low, high, max]
96
+ defaultEffort: high
97
+ autoLevel: model-default
98
+ auxDowngrade: true
99
+ auxPurposes: [session-title, compaction, auto-review]
100
+ auxLevel: low
101
+ autoScope: all
102
+ trace: false
103
+ ```
104
+
105
+ | 字段 | 默认 | 说明 |
106
+ | --- | --- | --- |
107
+ | `enabled` | `true` | 总开关 |
108
+ | `declareCapability` | `true` | 是否写 `reasoningEfforts` |
109
+ | `deepseekHosts` | `['deepseek.com']` | 视为官方 DeepSeek 的 host 后缀 |
110
+ | `deepseekModelPattern` | `^deepseek` | 模型 ID 正则(网关别名用) |
111
+ | `declareModels` | `[]` | 额外要声明的 `provider/model` 或模型 ID 正则 |
112
+ | `efforts` | `low, high, max` | 声明给 DeepSeek 的档位 |
113
+ | `defaultEffort` | `high` | 路由默认档,`Auto` 落在这里 |
114
+ | `autoLevel` | `model-default` | 也可指定固定档位 |
115
+ | `auxDowngrade` | `true` | 廉价调用是否降档 |
116
+ | `auxPurposes` | `session-title, compaction, auto-review` | 视为廉价调用的 `purpose` |
117
+ | `auxLevel` | `low` | 廉价调用用的档位 |
118
+ | `autoScope` | `all` | `all` / `declared` / `off` |
119
+ | `trace` | `false` | 把决策写到 stderr(排查用) |
120
+
121
+ ## 兼容性
122
+
123
+ - 只对 `llm-pi-ai` 路由声明能力;其他适配器(例如官方 DeepSeek 账户路由)本来就自带元数据,插件只补 `Auto`。
124
+ - 声明写进 profile 的用户层配置(与设置页编辑同一层)。若该行被更高层配置压住,写入会被拒绝并记录警告,此时手动在「设置 → 模型」里填写 `reasoningEfforts`(`low/high/max`)与默认档 `high` 即可。
125
+ - 不按工具名、参数大小或对话内容猜档位:这些信号不携带难度信息,一次猜低会被后续步骤继承。
126
+
127
+ ## 许可
128
+
129
+ MIT。
130
+
131
+ ---
132
+
133
+ ## English
134
+
135
+ **中文简介**:给 DeepSeek Harness 加一套声明式自动思考档位——`Auto` 落到模型声明的默认档,廉价调用自动用低档。
136
+
137
+ Declarative automatic thinking depth for DeepSeek Harness: the model selector gains `Auto`, normal steps use the model's declared default depth (`high` on DeepSeek), and cheap host-owned calls — session titles, compaction, auto-review — drop to `low`.
138
+
139
+ ### Quick start
140
+
141
+ ### Choose how you run DSH
142
+
143
+ | Mode | Use it for | Plugin location |
144
+ | --- | --- | --- |
145
+ | Web (`dsh web` in a browser) | Trying it out, remote machines | `web` profile |
146
+ | DSH Desktop | Daily use (recommended) | `desktop` profile, managed by the app |
147
+
148
+ ### Web: online install
149
+
150
+ ```sh
151
+ dsh plugin --profile web add dsh-think-effort
152
+ dsh --profile web
153
+ ```
154
+
155
+ ### Web: offline install
156
+
157
+ On a connected machine run `npm pack dsh-think-effort` (or download the `.tgz` from the GitHub release), copy it over, then:
158
+
159
+ ```sh
160
+ dsh plugin --profile web add /abs/path/dsh-think-effort-<version>.tgz
161
+ ```
162
+
163
+ An unpacked directory works too: `dsh plugin --profile web add /abs/path/dsh-think-effort`.
164
+
165
+ ### Desktop: online install
166
+
167
+ DSH Desktop → **Plugin market** → search `dsh-think-effort`; or **Plugins → Add plugin → Install third-party plugin** and enter the package name.
168
+
169
+ > The `desktop` profile is managed exclusively by the Electron app. Do **not** run `dsh plugin --profile desktop add ...` — DSH rejects it.
170
+
171
+ ### Desktop: offline install
172
+
173
+ Copy the `.tgz` (or an unpacked directory with `package.json` at its root) to the target machine, then **Plugins → Add plugin → Install third-party plugin** and enter the absolute path. The target machine needs neither npm nor GitHub.
174
+
175
+ ### Enable and verify
176
+
177
+ 1. Settings → Plugins: confirm `dsh-think-effort` is enabled. Desktop needs a full quit and relaunch; Web needs `dsh web` restarted and a hard refresh.
178
+ 2. The model chip next to the composer reads `<model> High` (the model's default depth) instead of the bare model id.
179
+ 3. Open the chip → "Reasoning level": `Auto / Low / High / Max` are listed.
180
+ 4. For a specific model, ask the agent to call the read-only `reasoning_effort_status` tool: it reports the declared depths, the default, what `Auto` resolves to and the cheap-call depth, without sending a model request.
181
+
182
+ ### Features
183
+
184
+ - Declares `reasoningEfforts` for DeepSeek models that carry none (gateway aliases included), so the selector finally has levels.
185
+ - `Auto` resolves to the declared default depth on every request; an explicit pick passes through untouched.
186
+ - 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.
187
+ - Idempotent: a second boot writes nothing; unload restores the original adapter registrations and retires a durable `auto`.
188
+
189
+ ### Configuration
190
+
191
+ 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` and `trace` are the ones most often changed.
192
+
193
+ ### Compatibility
194
+
195
+ - Capability declaration targets `llm-pi-ai` routes; other adapters already carry metadata and only gain `Auto`.
196
+ - When a higher configuration layer overrides `llm-pi-ai`, the write is refused with a logged warning — fill `reasoningEfforts` (`low/high/max`) and default depth `high` by hand under Settings → Models.
197
+ - It never guesses a depth from tool names, argument sizes or conversation text.
198
+
199
+ ### License
200
+
201
+ MIT.
202
+
203
+ <!-- author-tools:start -->
204
+
205
+ <!-- generated by scripts/sync-readmes.mjs from projects.json -->
206
+
207
+ ## 同作者的其他插件 · More plugins by the same author
208
+
209
+ - **[DSH 声音与提醒](https://github.com/mhlywxl/dsh-coding-sound)**(`dsh-coding-sound`)— 用声音盯住 Agent:按输出文字演奏生成式背景音乐,完成、等待审批与工具执行各有可配置的提示音。
210
+ <br />*[DSH coding sound](https://github.com/mhlywxl/dsh-coding-sound)* (`dsh-coding-sound`) — Generative background music and notification chimes for DeepSeek Harness: hear whether the agent is thinking, still working, or waiting for you.
211
+ - **[DSH 分屏工作区](https://github.com/mhlywxl/dsh-split-workspace)**(`dsh-split-workspace`)— 把 DSH 会话区拆成任意数量的原生窗格:左右、上下、田字 2×2 与自动网格,每个窗格都是独立会话。
212
+ <br />*[DSH split workspace](https://github.com/mhlywxl/dsh-split-workspace)* (`dsh-split-workspace`) — Split the DSH conversation area into unlimited native panes — side by side, stacked, 2×2 and an automatic grid — each a real session with its own composer and streaming.
213
+
214
+ ## 支持作者 · Support the author
215
+
216
+ 如果这个项目帮你省下了盯屏幕的时间,欢迎请作者喝杯咖啡 ☕,或者给作者「充充电」⚡。金额随意,心意最重要。
217
+
218
+ *If this project saved you some screen time, you can buy the author a coffee ☕ or top up the author's battery ⚡. Any amount is welcome — the thought counts.*
219
+
220
+ <p align="center">
221
+ <img src="https://raw.githubusercontent.com/mhlywxl/dsh-think-effort/main/sponsor/alipay.jpg" alt="支付宝收款码 / Alipay QR code" width="180" />
222
+ <img src="https://raw.githubusercontent.com/mhlywxl/dsh-think-effort/main/sponsor/wechat.png" alt="微信收款码 / WeChat Pay QR code" width="180" />
223
+ </p>
224
+ <p align="center"><sub>支付宝 · 微信支付 / Alipay · WeChat Pay</sub></p>
225
+
226
+ <!-- author-tools:end -->
@@ -0,0 +1,43 @@
1
+ # dsh-think-effort bundle: one Host row that owns the effort policy.
2
+ #
3
+ # The row's `config` is the complete tuning surface. Every field may be omitted;
4
+ # the plugin merges the row over its own defaults. Tune a value by adding an
5
+ # override row for `think-effort` to the profile's cordis.patch.yml:
6
+ #
7
+ # - id: think-effort
8
+ # config:
9
+ # auxLevel: low
10
+ # defaultEffort: high
11
+ #
12
+ - insert:
13
+ - id: think-effort
14
+ name: 'dsh-think-effort'
15
+ config:
16
+ enabled: true
17
+ # Declare `reasoningEfforts` for DeepSeek models that carry none.
18
+ declareCapability: true
19
+ # Endpoint suffixes treated as official DeepSeek.
20
+ deepseekHosts:
21
+ - deepseek.com
22
+ # Model-id test for hand-declared gateways (deepseek-v4.1-flash-1017, ...).
23
+ deepseekModelPattern: '^deepseek'
24
+ # Extra `provider/model` keys or model-id regular expressions to declare.
25
+ declareModels: []
26
+ # Declared vocabulary, escalation-ordered (DeepSeek: low/high/max).
27
+ efforts:
28
+ - low
29
+ - high
30
+ - max
31
+ # Route default depth; `auto` resolves here (DeepSeek: high).
32
+ defaultEffort: high
33
+ # What Auto resolves to, or a fixed level.
34
+ autoLevel: model-default
35
+ # Cheap host-owned calls drop to `auxLevel` when the model declares it.
36
+ auxDowngrade: true
37
+ auxPurposes:
38
+ - session-title
39
+ - compaction
40
+ - auto-review
41
+ auxLevel: low
42
+ # Which models offer Auto: all | declared | off.
43
+ autoScope: all
@@ -0,0 +1,43 @@
1
+ # Automatic thinking depth
2
+
3
+ Declarative thinking-depth control for DeepSeek (and other) reasoning models: the model selector gains `Auto`, `Auto` resolves to the model's declared default depth on every request (DeepSeek V4: `high`), and cheap host-owned calls — session titles, compaction, auto-review — drop to `low`.
4
+
5
+ ## What it does
6
+
7
+ 1. **Declares the capability (on by default).** A hand-declared DeepSeek gateway model under `llm-pi-ai` usually carries no reasoning metadata: the selector offers no depth, and any depth is refused. The plugin recognizes DeepSeek models by endpoint and model id and writes `reasoningEfforts` (default `low / high / max`) plus the route default depth (`high`) into the `llm-pi-ai` settings surface. A model that already declares `reasoningEfforts` — including an explicit `false` — is never touched.
8
+ 2. **Offers `Auto`.** One `Auto` entry is prepended to the model's depth list.
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
+
11
+ ## Usage
12
+
13
+ - Pick `Auto` in the model selector to state "use the default depth", or a concrete depth to pin it.
14
+ - Leaving the depth unset (the native "provider default" row) behaves like `Auto` on ordinary steps — both land on the declared default; `Auto` only records the intent in the session. The cheap-call downgrade applies either way.
15
+ - The recognized models, default depth and cheap-call list live in the plugin row's config (`think-effort` in `cordis.patch.yml`).
16
+
17
+ ## Limitations
18
+
19
+ - Capability declaration targets `llm-pi-ai` routes. Other adapters (for example the official DeepSeek account route) already carry metadata; the plugin only adds `Auto` there.
20
+ - The declaration is written into the profile's user layer, the same layer the Settings page edits. When that row is overridden by a higher layer (a `--patch` or home-patch override), the write is refused with a logged warning and `reasoningEfforts` has to be filled in by hand under Settings → Models.
21
+ - It never guesses a depth from tool names, argument sizes or conversation text: those signals carry no difficulty information, and a low guess is inherited by every later step.
22
+
23
+ ## Configuration
24
+
25
+ | Field | Default | Meaning |
26
+ |---|---|---|
27
+ | `enabled` | `true` | Master switch |
28
+ | `declareCapability` | `true` | Write `reasoningEfforts` |
29
+ | `deepseekHosts` | `['deepseek.com']` | Host suffixes treated as official DeepSeek |
30
+ | `deepseekModelPattern` | `^deepseek` | Model-id test for gateway aliases |
31
+ | `declareModels` | `[]` | Extra `provider/model` keys or model-id tests |
32
+ | `efforts` | `low, high, max` | Declared DeepSeek depth vocabulary |
33
+ | `defaultEffort` | `high` | Route default depth; where `Auto` lands |
34
+ | `autoLevel` | `model-default` | Or a fixed depth |
35
+ | `auxDowngrade` | `true` | Downgrade cheap host-owned calls |
36
+ | `auxPurposes` | `session-title, compaction, auto-review` | Purposes treated as cheap |
37
+ | `auxLevel` | `low` | Depth those calls request |
38
+ | `autoScope` | `all` | `all` / `declared` / `off` |
39
+ | `trace` | `false` | Write decisions to stderr for diagnosis |
40
+
41
+ ## Diagnostic tool
42
+
43
+ An Agent can call `reasoning_effort_status` for a provider/model: it reports the declared depths, the default, what `Auto` resolves to and the cheap-call depth, without sending any model request.
@@ -0,0 +1,43 @@
1
+ # 自动思考档位
2
+
3
+ 给 DeepSeek 等推理模型补上一套声明式的思考档位控制:模型选择器里出现 `Auto`,`Auto` 在每次请求落到模型声明的默认档(DeepSeek V4 = `high`),而会话标题、压缩、自动复审这类 Harness 自己发起的廉价调用自动用 `low`。
4
+
5
+ ## 它做什么
6
+
7
+ 1. **声明能力(默认开启)**:手工在 `llm-pi-ai` 里声明的 DeepSeek 网关模型通常没有推理元数据——选择器里没有任何档位,任何档位也会被拒绝。插件按 endpoint 与模型 ID 识别 DeepSeek 模型,把 `reasoningEfforts`(默认 `low / high / max`)与路由默认档(`high`)写进 `llm-pi-ai` 的设置面。已经有 `reasoningEfforts`(包括显式 `false`)的模型不会被改动。
8
+ 2. **提供 `Auto`**:在模型目录的档位列表最前面补一个 `Auto`。
9
+ 3. **逐请求解析**:在适配器边界把 `auto` 换成声明默认档;`purpose` 属于廉价调用时换成 `low`(仅当模型声明了它,且**与会话选了什么都无关**——会话标题/图片摘要本来就不继承会话档位);手动选的档位一律原样透传,由 DSH 自己校验。
10
+
11
+ ## 使用
12
+
13
+ - 在模型选择器里选 `Auto` 即声明「按默认档走」;选具体档位即固定该档位。
14
+ - 不选任何档位(原生“提供方默认”)在普通步骤上与 `Auto` 等效,都会落到声明默认档;差别只是 `Auto` 把意图记录进会话。廉价调用的降档在任何情况下都生效。
15
+ - 识别范围、默认档、廉价调用清单都在插件配置里(`cordis.patch.yml` 的 `think-effort` 行)。
16
+
17
+ ## 限制
18
+
19
+ - 只对 `llm-pi-ai` 路由声明能力:其他适配器(例如官方 DeepSeek 账户路由)本来就自带元数据,插件只补 `Auto`。
20
+ - 声明会写进 profile 的用户层配置(与设置页编辑同一层)。若该行被更高层(`--patch` 覆盖、home patch 覆盖)压住,写入会被拒绝并记录警告,此时需要手动在「设置 → 模型」里填写 `reasoningEfforts`。
21
+ - 不按工具名、参数大小或对话内容猜档位:这些信号不携带难度信息,一次猜低会被后续步骤继承。
22
+
23
+ ## 配置项
24
+
25
+ | 字段 | 默认 | 说明 |
26
+ |---|---|---|
27
+ | `enabled` | `true` | 总开关 |
28
+ | `declareCapability` | `true` | 是否写 `reasoningEfforts` |
29
+ | `deepseekHosts` | `['deepseek.com']` | 视为官方 DeepSeek 的 host 后缀 |
30
+ | `deepseekModelPattern` | `^deepseek` | 模型 ID 正则(网关别名用) |
31
+ | `declareModels` | `[]` | 额外要声明的 `provider/model` 或模型 ID 正则 |
32
+ | `efforts` | `low, high, max` | 声明给 DeepSeek 的档位 |
33
+ | `defaultEffort` | `high` | 路由默认档,`Auto` 落在这里 |
34
+ | `autoLevel` | `model-default` | 也可指定固定档位 |
35
+ | `auxDowngrade` | `true` | 廉价调用是否降档 |
36
+ | `auxPurposes` | `session-title, compaction, auto-review` | 视为廉价调用的 `purpose` |
37
+ | `auxLevel` | `low` | 廉价调用用的档位 |
38
+ | `autoScope` | `all` | `all` / `declared` / `off` |
39
+ | `trace` | `false` | 把决策写到 stderr(排查用) |
40
+
41
+ ## 诊断工具
42
+
43
+ 会话里可以让 Agent 调 `reasoning_effort_status`:它报告某模型声明的档位、默认档、`Auto` 解析结果与廉价调用档位,不发任何模型请求。
package/icon.svg ADDED
@@ -0,0 +1,16 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Automatic thinking depth">
2
+ <defs>
3
+ <linearGradient id="arc" x1="8" y1="48" x2="56" y2="16" gradientUnits="userSpaceOnUse">
4
+ <stop offset="0" stop-color="#3b82f6"/>
5
+ <stop offset="0.55" stop-color="#6366f1"/>
6
+ <stop offset="1" stop-color="#a855f7"/>
7
+ </linearGradient>
8
+ </defs>
9
+ <rect x="2" y="2" width="60" height="60" rx="16" fill="#101828"/>
10
+ <path d="M14 44a18 18 0 1 1 36 0" fill="none" stroke="url(#arc)" stroke-width="5" stroke-linecap="round"/>
11
+ <path d="M20 44a12 12 0 1 1 24 0" fill="none" stroke="#334155" stroke-width="3" stroke-linecap="round"/>
12
+ <circle cx="32" cy="44" r="3.4" fill="#f8fafc"/>
13
+ <path d="M32 44 44 30" stroke="#f8fafc" stroke-width="3.4" stroke-linecap="round"/>
14
+ <circle cx="32" cy="44" r="8" fill="none" stroke="#f8fafc" stroke-opacity="0.16" stroke-width="2"/>
15
+ <text x="32" y="58" text-anchor="middle" font-family="ui-sans-serif, system-ui, sans-serif" font-size="9" font-weight="600" fill="#94a3b8">AUTO</text>
16
+ </svg>
package/index.js ADDED
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Host half of `dsh-think-effort` — declarative automatic thinking depth for
3
+ * DeepSeek routes in DeepSeek Harness.
4
+ *
5
+ * <h2>What this half does</h2>
6
+ *
7
+ * 1. **Declares the DeepSeek capability** (opt-in, idempotent). A gateway model
8
+ * such as `deepseek-v4.1-flash-1017` reaches DSH through a hand-declared
9
+ * `llm-pi-ai` route, so pi-ai's installed catalog has no reasoning metadata
10
+ * for it: no level control appears, and any level DSH tried to send would be
11
+ * refused. This half therefore writes the declaration the endpoint and model
12
+ * imply (`low | high | max`, default `high`) into the route's own settings
13
+ * surface. A model that already carries `reasoningEfforts` — including an
14
+ * explicit `false` — is never touched.
15
+ * 2. **Advertises `auto`** in the model selector by wrapping each registered
16
+ * adapter's `resolveModel`, so the switcher lists `auto` before the declared
17
+ * levels.
18
+ * 3. **Resolves the request's effort** just before dispatch, inside the same
19
+ * adapter facade: `auto` becomes the declared default (`high` for DeepSeek),
20
+ * a cheap host-owned call (session title, compaction, auto-review) becomes
21
+ * `low` when the model declares it, and an explicit user pick is passed
22
+ * through untouched.
23
+ *
24
+ * <h2>Why the adapter facade</h2>
25
+ *
26
+ * DSH fixes the step's model selection before any plugin waterfall sees it, and
27
+ * `llm/stream` listeners cannot replace `GenerateOptions` (`next()` takes no
28
+ * arguments and the options are frozen). The adapter registry entry is the one
29
+ * seam that sees the very options the provider will receive, so the facade is
30
+ * where a per-request effort decision belongs. It also keeps the durable
31
+ * selection honest: a session that selected `auto` keeps saying `auto`, and the
32
+ * concrete depth is applied per request, which is what makes the choice survive
33
+ * retries and compaction unchanged.
34
+ *
35
+ * The facade writes nothing into a third party's adapter object: it replaces
36
+ * the registry entry and forwards every other member bound to the inner
37
+ * adapter.
38
+ *
39
+ * @module dsh-think-effort
40
+ */
41
+
42
+ import {
43
+ normalizeConfig,
44
+ planCapabilitySection,
45
+ resolveCallEffort,
46
+ shouldDeclare,
47
+ withAutoEffort,
48
+ } from './src/policy.js';
49
+
50
+ /** The llm-pi-ai settings entry id in a composed profile. */
51
+ const PI_AI_NAMESPACE = 'llm-pi-ai';
52
+
53
+ /**
54
+ * Marks one facade so a re-run can tell "this registration already carries my
55
+ * wrapper" from "this is a third party's adapter". Not enumerable: it must not
56
+ * leak into an `Object.keys` sweep.
57
+ */
58
+ const FACADE = Symbol('dsh-think-effort/adapter-facade');
59
+
60
+ /** Every adapter member the facade forwards; `resolveModel`/`prepareCall` are handled here. */
61
+ const FORWARDED = [
62
+ 'providerInfo',
63
+ 'providerRetryPolicy',
64
+ 'imageRequestPricing',
65
+ 'imageRequestTarget',
66
+ 'listModels',
67
+ 'stream',
68
+ ];
69
+
70
+ /** One facade per inner adapter: one identity however many routes it serves. */
71
+ const facades = new WeakMap();
72
+
73
+ /**
74
+ * Build a forwarding facade over one adapter.
75
+ * @param {object} inner the adapter a third party registered; never mutated.
76
+ * @param {object} deps decoration and translation hooks.
77
+ * @returns {object} the facade to place in the registry entry.
78
+ */
79
+ function adapterFacade(inner, deps) {
80
+ const facade = {
81
+ async resolveModel(provider, model, signal) {
82
+ const info = await inner.resolveModel.call(inner, provider, model, signal);
83
+ return deps.decorate(info, provider, model);
84
+ },
85
+ async prepareCall(provider, model, signal) {
86
+ const prepared = await inner.prepareCall.call(inner, provider, model, signal);
87
+ const info = deps.decorate(prepared.model, provider, model);
88
+ return {
89
+ model: info,
90
+ stream: (options) => prepared.stream.call(prepared, deps.translate(provider, model, options, info)),
91
+ };
92
+ },
93
+ };
94
+ // Forwarded members keep `this` bound to the inner adapter and a stable
95
+ // function identity, so a downstream cache keyed on identity keeps working.
96
+ for (const member of FORWARDED) {
97
+ const value = inner[member];
98
+ if (typeof value !== 'function') continue;
99
+ facade[member] = value.bind(inner);
100
+ }
101
+ Object.defineProperty(facade, FACADE, { value: true, enumerable: false });
102
+ return facade;
103
+ }
104
+
105
+ /** `setTimeout` in a Host keeps the process alive; this one must not. */
106
+ function unrefTimer(timer) {
107
+ try {
108
+ timer?.unref?.();
109
+ } catch {
110
+ /* a non-Node timer has nothing to unref */
111
+ }
112
+ }
113
+
114
+ /** Read the live `llm-pi-ai` section, if the settings service is mounted. */
115
+ function readPiAiSection(ctx) {
116
+ try {
117
+ const settings = ctx.get('settings');
118
+ if (settings === null || settings === undefined || typeof settings.describe !== 'function') return undefined;
119
+ const descriptors = settings.describe();
120
+ if (!Array.isArray(descriptors)) return undefined;
121
+ const hit = descriptors.find((entry) => entry !== null && typeof entry === 'object' && entry.ns === PI_AI_NAMESPACE);
122
+ if (hit === undefined) return undefined;
123
+ return { value: hit.value, revision: hit.revision };
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Plugin body.
131
+ * @param {import('@deepseek-ai/cordis').Context} ctx the owning Host context.
132
+ * @param {object} [rawConfig] this row's config from the profile patch.
133
+ */
134
+ export function apply(ctx, rawConfig) {
135
+ const config = normalizeConfig(rawConfig);
136
+ /** Diagnostic channel: opt-in stderr trace for a profile that hides the Host log. */
137
+ const trace = (message, ...rest) => {
138
+ if (config.trace !== true) return;
139
+ try {
140
+ let index = 0;
141
+ const text = String(message).replace(/%s/g, () => String(rest[index++]));
142
+ process.stderr.write(`[think-effort] ${text}${index < rest.length ? ' ' + rest.slice(index).map(String).join(' ') : ''}\n`);
143
+ } catch {
144
+ /* a trace must never break the turn */
145
+ }
146
+ };
147
+ trace('apply: enabled=%s declareCapability=%s', config.enabled, config.declareCapability);
148
+ if (config.enabled === false) {
149
+ ctx.logger?.info?.('[think-effort] disabled by config; no capability declaration or effort policy installed');
150
+ return;
151
+ }
152
+
153
+ /** Models this plugin declared, keyed `provider/model` (used by `autoScope: declared`). */
154
+ const declaredModels = new Set();
155
+ /** Log de-duplication for per-request decisions. */
156
+ const logged = new Set();
157
+
158
+ // ── capability declaration ───────────────────────────────────────────────
159
+ /** Serialize settings writes; a boot burst must not stack whole-section updates. */
160
+ let syncTail = Promise.resolve();
161
+ let syncAgain = false;
162
+ const syncCapabilities = () => {
163
+ if (!config.declareCapability) return;
164
+ if (syncAgain) return;
165
+ syncAgain = true;
166
+ syncTail = syncTail.then(async () => {
167
+ syncAgain = false;
168
+ const section = readPiAiSection(ctx);
169
+ trace('capability sync: section=%s', section === undefined ? 'missing' : 'found');
170
+ if (section === undefined) return;
171
+ const plan = planCapabilitySection(section.value, config);
172
+ trace('capability sync: changed=%s declared=%s', plan.changed, plan.declared.map((entry) => `${entry.provider}/${entry.model}`).join(','));
173
+ for (const entry of plan.declared) declaredModels.add(`${entry.provider}/${entry.model}`);
174
+ if (!plan.changed) return;
175
+ const settings = ctx.get('settings');
176
+ if (settings === null || settings === undefined || typeof settings.update !== 'function') return;
177
+ try {
178
+ await settings.update(PI_AI_NAMESPACE, { providers: plan.section.providers }, section.revision);
179
+ trace('capability sync: section written');
180
+ void selfCheck();
181
+ ctx.logger?.info?.(
182
+ '[think-effort] declared DeepSeek effort capabilities in %s: %s',
183
+ PI_AI_NAMESPACE,
184
+ plan.declared.map((entry) => `${entry.provider}/${entry.model} (${entry.reason})`).join(', ') || 'none',
185
+ );
186
+ } catch (error) {
187
+ trace('capability sync: write rejected: %s', error instanceof Error ? error.message : String(error));
188
+ // A schema gate (older llm-pi-ai without the field) keeps the previous
189
+ // section: report it instead of pretending the model gained levels.
190
+ ctx.logger?.warn?.('[think-effort] capability declaration rejected by the llm-pi-ai schema; kept the previous section', error);
191
+ }
192
+ }).catch((error) => {
193
+ syncAgain = false;
194
+ ctx.logger?.warn?.('[think-effort] capability sync failed', error);
195
+ });
196
+ };
197
+
198
+ const policyDeps = {
199
+ decorate(info, provider, model) {
200
+ if (info === null || typeof info !== 'object') return info;
201
+ const key = `${provider}/${model}`;
202
+ const declared = declaredModels.has(key) || shouldDeclare({ provider, modelId: model }, config).declared;
203
+ return withAutoEffort(info, config, { declared });
204
+ },
205
+ translate(provider, model, options, info) {
206
+ if (options === null || typeof options !== 'object') return options;
207
+ const reasoning = info !== null && typeof info === 'object' ? info.reasoning : undefined;
208
+ const level = resolveCallEffort({
209
+ requested: options.reasoningEffort,
210
+ purpose: options.purpose,
211
+ efforts: reasoning !== null && typeof reasoning === 'object' ? reasoning.efforts : undefined,
212
+ defaultEffort: reasoning !== null && typeof reasoning === 'object' ? reasoning.defaultEffort : undefined,
213
+ }, config);
214
+ if (level === undefined || level === options.reasoningEffort) return options;
215
+ const key = `${provider}/${model}/${String(options.purpose ?? '-')}/${level}`;
216
+ trace('translate: %s/%s purpose=%s requested=%s -> %s', provider, model, String(options.purpose ?? '-'), String(options.reasoningEffort), level);
217
+ if (!logged.has(key)) {
218
+ logged.add(key);
219
+ ctx.logger?.info?.(
220
+ '[think-effort] %s/%s purpose=%s auto -> %s',
221
+ provider,
222
+ model,
223
+ String(options.purpose ?? '-'),
224
+ level,
225
+ );
226
+ }
227
+ return { ...options, reasoningEffort: level };
228
+ },
229
+ };
230
+
231
+ /** Route registrations replaced by this plugin, so unload can put them back. */
232
+ /** @type {Array<{route: string, facade: object, registration: object}>} */
233
+ const installed = [];
234
+
235
+ const install = () => {
236
+ const llm = ctx.get('llm');
237
+ const adapters = llm?.adapters;
238
+ if (adapters === undefined || typeof adapters.get !== 'function' || typeof adapters.set !== 'function') return;
239
+ // Snapshot first: the loop replaces entries and a live iterator would revisit them.
240
+ for (const [route, registration] of [...adapters]) {
241
+ const inner = registration?.adapter;
242
+ if (inner === null || inner === undefined || inner[FACADE] === true) continue;
243
+ let facade = facades.get(inner);
244
+ if (facade === undefined) {
245
+ facade = adapterFacade(inner, policyDeps);
246
+ facades.set(inner, facade);
247
+ }
248
+ try {
249
+ adapters.set(route, { ...registration, adapter: facade });
250
+ installed.push({ route, facade, registration });
251
+ } catch (error) {
252
+ ctx.logger?.warn?.('[think-effort] could not wrap adapter for route %s', route, error);
253
+ }
254
+ }
255
+ };
256
+
257
+ /**
258
+ * Boot-time self check (trace only): report what the model now advertises and
259
+ * what the policy resolves, without sending a model request. It is the only
260
+ * way to see the whole pipeline in a profile whose Host log is not visible.
261
+ * @returns {Promise<void>} fulfillment after the report is traced.
262
+ */
263
+ const selfCheck = async () => {
264
+ if (config.trace !== true) return;
265
+ try {
266
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.();
267
+ const provider = selection?.provider;
268
+ const model = selection?.model;
269
+ if (typeof provider !== 'string' || typeof model !== 'string') {
270
+ trace('self check: no default selection');
271
+ return;
272
+ }
273
+ const info = await ctx.get('llm')?.resolveModelInfo?.(provider, model);
274
+ const reasoning = info?.reasoning;
275
+ const efforts = Array.isArray(reasoning?.efforts) ? reasoning.efforts.map((effort) => effort.id) : [];
276
+ const auto = resolveCallEffort({ requested: 'auto', efforts: reasoning?.efforts, defaultEffort: reasoning?.defaultEffort, purpose: 'agent' }, config);
277
+ const aux = resolveCallEffort({ requested: 'auto', efforts: reasoning?.efforts, defaultEffort: reasoning?.defaultEffort, purpose: config.auxPurposes[0] ?? 'session-title' }, config);
278
+ trace('self check: %s/%s efforts=[%s] default=%s auto=%s aux=%s', provider, model, efforts.join(' '), String(reasoning?.defaultEffort), String(auto), String(aux));
279
+ } catch (error) {
280
+ trace('self check failed: %s', error instanceof Error ? error.message : String(error));
281
+ }
282
+ };
283
+
284
+ install();
285
+ syncCapabilities();
286
+
287
+ ctx.on('llm/adapters-updated', () => {
288
+ install();
289
+ syncCapabilities();
290
+ });
291
+ ctx.on('settings/document-updated', (ns) => {
292
+ if (ns === PI_AI_NAMESPACE) syncCapabilities();
293
+ });
294
+ ctx.on('app-boot/config-reload', () => syncCapabilities());
295
+ // Delayed retries cover the boot order where this plugin applies before the
296
+ // settings service has described the llm-pi-ai entry, and no later commit
297
+ // touches that namespace. The second beat also covers a bundle installed
298
+ // into an already-running Host, where no boot-time describe chain follows.
299
+ const retries = [2500, 10000].map((delay) => {
300
+ const timer = setTimeout(() => syncCapabilities(), delay);
301
+ unrefTimer(timer);
302
+ return timer;
303
+ });
304
+ ctx.effect(() => () => {
305
+ for (const timer of retries) clearTimeout(timer);
306
+ }, 'think-effort: capability retries');
307
+
308
+ /**
309
+ * Wait for a queued capability declaration, so a reader that runs right after
310
+ * boot (the status tool, the first model catalog load) sees the declaration
311
+ * rather than the section it replaced.
312
+ * @returns {Promise<void>} settlement of the current write chain.
313
+ */
314
+ const flushCapabilities = async () => {
315
+ syncCapabilities();
316
+ await syncTail.catch(() => undefined);
317
+ };
318
+
319
+ // ── status tool ──────────────────────────────────────────────────────────
320
+ // The Host has no read-only surface for "what depth will this model take and
321
+ // what does Auto resolve to", and the answer depends on a settings write that
322
+ // may still be in flight. One small tool answers it for the user and for a
323
+ // reviewer of this plugin, without sending any model request.
324
+ const statusTool = {
325
+ name: 'reasoning_effort_status',
326
+ description:
327
+ 'Report the reasoning depths one provider/model declares, the route default, and what Auto resolves to for a normal step and for a cheap host-owned call. Read-only: sends no model request.',
328
+ parameters: {
329
+ type: 'object',
330
+ properties: {
331
+ provider: { type: 'string', description: 'Provider route; defaults to the current default selection.' },
332
+ model: { type: 'string', description: 'Model id; defaults to the current default selection.' },
333
+ },
334
+ additionalProperties: false,
335
+ },
336
+ output: {
337
+ schema: { type: 'object' },
338
+ render: (_args, value) => [{
339
+ type: 'text',
340
+ text: typeof value?.summary === 'string' ? value.summary : 'reasoning effort status unavailable',
341
+ }],
342
+ },
343
+ async execute(args) {
344
+ await flushCapabilities();
345
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.();
346
+ const provider = typeof args?.provider === 'string' && args.provider !== '' ? args.provider : selection?.provider;
347
+ const model = typeof args?.model === 'string' && args.model !== '' ? args.model : selection?.model;
348
+ if (typeof provider !== 'string' || typeof model !== 'string') {
349
+ return { ok: false, summary: 'No provider/model given and no default selection is recorded.' };
350
+ }
351
+ const llm = ctx.get('llm');
352
+ if (llm === null || llm === undefined || typeof llm.resolveModelInfo !== 'function') {
353
+ return { ok: false, summary: 'The llm service is not available in this profile.' };
354
+ }
355
+ let info;
356
+ try {
357
+ info = await llm.resolveModelInfo(provider, model);
358
+ } catch (error) {
359
+ return { ok: false, provider, model, summary: `Cannot resolve ${provider}/${model}: ${error instanceof Error ? error.message : String(error)}` };
360
+ }
361
+ const reasoning = info?.reasoning;
362
+ const efforts = Array.isArray(reasoning?.efforts) ? reasoning.efforts.map((effort) => effort.id) : [];
363
+ const defaultEffort = reasoning?.defaultEffort;
364
+ const auto = resolveCallEffort({ requested: 'auto', efforts: reasoning?.efforts, defaultEffort, purpose: 'agent' }, config);
365
+ const auxPurpose = config.auxPurposes[0] ?? 'session-title';
366
+ const aux = resolveCallEffort({ requested: 'auto', efforts: reasoning?.efforts, defaultEffort, purpose: auxPurpose }, config);
367
+ const summary = efforts.length === 0
368
+ ? `${provider}/${model} declares no reasoning depths; the selector offers only the provider default.`
369
+ : `${provider}/${model}: ${efforts.join(' | ')}; default=${defaultEffort ?? '(none)'}; Auto -> ${auto ?? '(adapter default)'} for a normal step -> ${aux ?? '(adapter default)'} for ${auxPurpose}.`;
370
+ return { ok: true, provider, model, efforts, defaultEffort: defaultEffort ?? null, auto: auto ?? null, aux: aux ?? null, auxPurpose, summary };
371
+ },
372
+ };
373
+ ctx.inject?.(['tools'], (scope) => {
374
+ scope.effect(() => scope.tools.register(statusTool), 'think-effort: status tool');
375
+ });
376
+
377
+ // Unload: put every registry entry we replaced back, then retire a durable
378
+ // `auto` selection so a session cannot keep a mask that no longer resolves
379
+ // (DSH validates the selection against the model's efforts on every request).
380
+ ctx.effect(() => () => {
381
+ const llm = ctx.get('llm');
382
+ const adapters = llm?.adapters;
383
+ for (const { route, facade, registration } of installed) {
384
+ try {
385
+ const current = adapters?.get?.(route);
386
+ if (current?.adapter === facade) adapters.set(route, registration);
387
+ } catch {
388
+ /* a torn-down registry is already gone */
389
+ }
390
+ }
391
+ installed.length = 0;
392
+ try {
393
+ const agents = ctx.get('agents');
394
+ const live = typeof agents?.list === 'function' ? agents.list() : [];
395
+ for (const agent of live) {
396
+ const current = agent?.model?.current?.();
397
+ if (current === undefined || current.reasoningEffort !== 'auto') continue;
398
+ const { provider, model } = current;
399
+ const { reasoningEffort: _drop, ...rest } = current;
400
+ agent.model.select(rest);
401
+ ctx.logger?.info?.('[think-effort] retired auto selection on %s/%s at unload', provider, model);
402
+ }
403
+ } catch {
404
+ /* unload must not throw */
405
+ }
406
+ }, 'think-effort: adapters and auto selections');
407
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Automatic thinking depth",
4
+ "description": "Adds Auto to the model selector for reasoning models and resolves it per request: the declared default depth for normal steps (high on DeepSeek), Low for cheap host-owned calls such as session titles and compaction, and the model's own declared vocabulary everywhere else.",
5
+ "detail": "docs/DETAIL.en.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "自动思考档位",
4
+ "description": "为推理模型在模型选择器里加上 Auto,并逐请求解析:普通步骤用模型声明的默认档位(DeepSeek 为 high),会话标题/压缩等由 Harness 自己发起的廉价调用用 low,其余情况只用模型自己声明的档位。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "dsh-think-effort",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
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, and drop cheap host-owned calls to Low.",
6
+ "icon": "./icon.svg",
7
+ "license": "MIT",
8
+ "author": "mhlywxl",
9
+ "keywords": [
10
+ "dsh",
11
+ "dsh-plugin",
12
+ "deepseek-harness",
13
+ "reasoning-effort",
14
+ "thinking-level",
15
+ "deepseek"
16
+ ],
17
+ "exports": {
18
+ ".": "./index.js",
19
+ "./locale/*.json": "./locale/*.json",
20
+ "./icon": "./icon.svg",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "index.js",
25
+ "src/**",
26
+ "cordis.patch.yml",
27
+ "locale/*.json",
28
+ "icon.svg",
29
+ "docs",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "engines": {
35
+ "node": ">=20",
36
+ "dsh": ">=0.2.0-rc.1 <0.3.0-0"
37
+ },
38
+ "scripts": {
39
+ "test": "node --test \"test/*.test.mjs\"",
40
+ "check": "node --check index.js && node --check src/policy.js && node --test \"test/*.test.mjs\""
41
+ },
42
+ "dsh": {
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ }
46
+ },
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "git+https://github.com/mhlywxl/dsh-think-effort.git"
50
+ },
51
+ "homepage": "https://github.com/mhlywxl/dsh-think-effort#readme",
52
+ "bugs": {
53
+ "url": "https://github.com/mhlywxl/dsh-think-effort/issues"
54
+ }
55
+ }
package/src/policy.js ADDED
@@ -0,0 +1,417 @@
1
+ /**
2
+ * Declarative thinking-depth policy (pure functions, no Host access).
3
+ *
4
+ * <h2>The four rules</h2>
5
+ *
6
+ * 1. **Capability is declared, never guessed.** A model declares its depth
7
+ * vocabulary and its default depth (DeepSeek V4: `low | high | max`, default
8
+ * `high`). A model with no declaration has no levels at all, and the selector
9
+ * then offers only the provider default.
10
+ * 2. **`auto` means "use the declared default", not "schedule something".** It
11
+ * is resolved to a concrete depth before the adapter builds the request.
12
+ * 3. **Cheap host-owned calls drop to `low` only when the model declares it.**
13
+ * Session titles, compaction and auto-review are bounded auxiliary requests
14
+ * that never inherit the session's own depth; a model without `low` keeps its
15
+ * own default instead.
16
+ * 4. **Never send a depth the endpoint does not declare.** An unsupported
17
+ * explicit choice is refused upstream by DSH instead of being silently
18
+ * adjusted, so this module only ever computes depths the vocabulary contains.
19
+ *
20
+ * <h2>What this module deliberately does NOT do</h2>
21
+ *
22
+ * It never derives a depth from tool names, argument sizes or conversation
23
+ * text. Those signals carry no difficulty information, a wrong low guess is
24
+ * inherited by every later step, and a guessed level may not even exist on the
25
+ * target model — the failure mode this policy is meant to remove.
26
+ *
27
+ * `<h2>Where the rules come from</h2>`
28
+ *
29
+ * The reference behaviour was established by reading an external desktop
30
+ * agent's source; the findings, with citations, live outside this package (see
31
+ * the workspace research note). This package states only the resulting rules so
32
+ * its code and commits stay self-contained.
33
+ */
34
+
35
+ /** Escalation-ordered effort levels every adapter vocabulary is drawn from. */
36
+ export const EFFORT_ORDER = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
37
+
38
+ /** Scheduler sentinel: never sent to a provider, always resolved first. */
39
+ export const AUTO_EFFORT = 'auto';
40
+
41
+ /** Display metadata for the levels this plugin can introduce. */
42
+ export const EFFORT_NAMES = {
43
+ auto: 'Auto',
44
+ off: 'Off',
45
+ minimal: 'Minimal',
46
+ low: 'Low',
47
+ medium: 'Medium',
48
+ high: 'High',
49
+ xhigh: 'Extra high',
50
+ max: 'Max',
51
+ };
52
+
53
+ /**
54
+ * DeepSeek V4 declaration used when a model carries none: the depth levels
55
+ * `low | high | max` with a default of `high`. Turning thinking off entirely is
56
+ * expressed through the provider's thinking knob rather than a depth, and the
57
+ * pi-ai thinking map has no portable spelling for it, so the plugin declares
58
+ * only the three depths it can serialize.
59
+ */
60
+ export const DEEPSEEK_DEFAULT_EFFORTS = ['low', 'high', 'max'];
61
+ /** The official DeepSeek default depth. */
62
+ export const DEEPSEEK_DEFAULT_EFFORT = 'high';
63
+
64
+ /** Config defaults, mirrored by the bundle patch row. */
65
+ export const DEFAULT_CONFIG = {
66
+ enabled: true,
67
+ /** Declare DeepSeek V4 capabilities into `llm-pi-ai` when a model carries none. */
68
+ declareCapability: true,
69
+ /** Host suffixes that identify an official DeepSeek endpoint. */
70
+ deepseekHosts: ['deepseek.com'],
71
+ /** Model-id test for hand-declared gateways (`deepseek-v4.1-flash-1017`, ...). */
72
+ deepseekModelPattern: '^deepseek',
73
+ /** Extra `provider/model` keys or model-id tests to declare. */
74
+ declareModels: [],
75
+ /** Levels declared for a matched model, in escalation order. */
76
+ efforts: DEEPSEEK_DEFAULT_EFFORTS,
77
+ /** Route-level default depth (`auto` resolves here). */
78
+ defaultEffort: DEEPSEEK_DEFAULT_EFFORT,
79
+ /** What `auto` resolves to: `model-default` keeps the declared default. */
80
+ autoLevel: 'model-default',
81
+ /** Downgrade cheap host-owned calls to `auxLevel` when the model declares it. */
82
+ auxDowngrade: true,
83
+ /** LLM request purposes that are host-owned cheap calls. */
84
+ auxPurposes: ['session-title', 'compaction', 'auto-review'],
85
+ /** Level those calls request. */
86
+ auxLevel: 'low',
87
+ /** Which models get the `auto` mask in the model selector: `all` | `declared` | `off`. */
88
+ autoScope: 'all',
89
+ };
90
+
91
+ /** Merge a patch row over the defaults without validating types yet. */
92
+ export function normalizeConfig(raw) {
93
+ const config = { ...DEFAULT_CONFIG, ...(raw !== null && typeof raw === 'object' ? raw : {}) };
94
+ if (!Array.isArray(config.efforts) || config.efforts.length === 0) config.efforts = [...DEEPSEEK_DEFAULT_EFFORTS];
95
+ if (!Array.isArray(config.auxPurposes)) config.auxPurposes = [...DEFAULT_CONFIG.auxPurposes];
96
+ if (!Array.isArray(config.deepseekHosts)) config.deepseekHosts = [...DEFAULT_CONFIG.deepseekHosts];
97
+ if (!Array.isArray(config.declareModels)) config.declareModels = [];
98
+ return config;
99
+ }
100
+
101
+ /**
102
+ * Whether one level id belongs to the standard vocabulary.
103
+ * @param {unknown} value level id.
104
+ * @returns {boolean} true for a known level or `auto`.
105
+ */
106
+ export function isEffortId(value) {
107
+ return value === AUTO_EFFORT || EFFORT_ORDER.includes(value);
108
+ }
109
+
110
+ /** Escalation index of a level, or `-1` when it is not a depth level. */
111
+ function rankOf(level) {
112
+ return EFFORT_ORDER.indexOf(level);
113
+ }
114
+
115
+ /**
116
+ * Whether a route's base URL points at an official DeepSeek endpoint.
117
+ * Matching is host-exact (plus subdomains), never a substring test
118
+ * (`internal/provider/openai/host.go`); a substring test would accept
119
+ * `notdeepseek.com`, so this compares host suffixes.
120
+ * @param {string} baseURL route endpoint.
121
+ * @param {readonly string[]} [hosts] accepted host suffixes.
122
+ * @returns {boolean} true when the host belongs to one of the suffixes.
123
+ */
124
+ export function isDeepSeekHost(baseURL, hosts = DEFAULT_CONFIG.deepseekHosts) {
125
+ if (typeof baseURL !== 'string' || baseURL.length === 0) return false;
126
+ let host;
127
+ try {
128
+ host = new URL(baseURL).hostname.toLowerCase();
129
+ } catch {
130
+ return false;
131
+ }
132
+ return hosts.some((suffix) => {
133
+ const clean = String(suffix ?? '').trim().toLowerCase().replace(/^\./, '');
134
+ if (clean === '') return false;
135
+ return host === clean || host.endsWith(`.${clean}`);
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Whether a model id names the DeepSeek family.
141
+ * Catalog ids are exact (`deepseek-v4-flash`, `deepseek-v4-pro`); a gateway
142
+ * alias such as `deepseek-v4.1-flash-1017` is matched by the configured prefix
143
+ * test, which the profile author owns.
144
+ * @param {string} modelId provider-owned model id.
145
+ * @param {string} [pattern] JavaScript source for the id test.
146
+ * @returns {boolean} true when the id matches.
147
+ */
148
+ export function isDeepSeekModel(modelId, pattern = DEFAULT_CONFIG.deepseekModelPattern) {
149
+ if (typeof modelId !== 'string' || modelId.length === 0) return false;
150
+ if (typeof pattern !== 'string' || pattern.trim() === '') return false;
151
+ try {
152
+ return new RegExp(pattern, 'i').test(modelId);
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Whether one model needs a DeepSeek capability declaration, and why.
160
+ * @param {object} input route facts.
161
+ * @param {string} input.provider route key.
162
+ * @param {string} input.modelId model id.
163
+ * @param {string} [input.baseURL] route endpoint.
164
+ * @param {object} cfg normalized plugin config.
165
+ * @returns {{declared: boolean, reason: string}} the decision.
166
+ */
167
+ export function shouldDeclare({ provider, modelId, baseURL }, cfg) {
168
+ const key = `${provider}/${modelId}`;
169
+ const extras = cfg.declareModels.filter((entry) => typeof entry === 'string' && entry.trim() !== '');
170
+ for (const extra of extras) {
171
+ if (extra.includes('/')) {
172
+ if (extra === key) return { declared: true, reason: 'declaredModels' };
173
+ continue;
174
+ }
175
+ try {
176
+ if (new RegExp(extra, 'i').test(modelId)) return { declared: true, reason: 'declaredModels' };
177
+ } catch {
178
+ /* an unusable user pattern must not match anything */
179
+ }
180
+ }
181
+ if (isDeepSeekHost(baseURL, cfg.deepseekHosts)) return { declared: true, reason: 'deepseek-host' };
182
+ if (isDeepSeekModel(modelId, cfg.deepseekModelPattern)) return { declared: true, reason: 'deepseek-model' };
183
+ return { declared: false, reason: '' };
184
+ }
185
+
186
+ /** Build the `reasoningEfforts` map a declared model carries, or `undefined`. */
187
+ export function effortsMap(cfg) {
188
+ const levels = cfg.efforts.filter((level) => typeof level === 'string' && level !== AUTO_EFFORT && level !== 'off');
189
+ if (levels.length === 0) return undefined;
190
+ /** @type {Record<string, string>} */
191
+ const map = {};
192
+ for (const level of levels) map[level] = level;
193
+ return map;
194
+ }
195
+
196
+ /**
197
+ * Whether a model entry already answers the capability question.
198
+ * `reasoningEfforts: false` is an explicit "this endpoint has no levels"; a
199
+ * non-empty dict is an explicit vocabulary. Neither may be overwritten.
200
+ */
201
+ function hasExplicitReasoning(row) {
202
+ if (row === null || typeof row !== 'object') return false;
203
+ return row.reasoningEfforts !== undefined;
204
+ }
205
+
206
+ /** Assign a declared model's effort fields, returning the same object when it already answers. */
207
+ function declareRow(row, cfg) {
208
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) return row;
209
+ if (hasExplicitReasoning(row)) return row;
210
+ const efforts = effortsMap(cfg);
211
+ if (efforts === undefined) return row;
212
+ return { ...row, reasoningEfforts: efforts };
213
+ }
214
+
215
+ /**
216
+ * Plan the `llm-pi-ai` providers patch that declares DeepSeek capabilities.
217
+ *
218
+ * Pure: returns the *same* section reference when nothing needs to change, so a
219
+ * caller can skip the settings write by identity (which is what keeps this
220
+ * idempotent across boots and `settings/document-updated` events).
221
+ *
222
+ * Only models that carry no `reasoningEfforts` are touched. A user who declared
223
+ * their own vocabulary keeps it; a user who set `reasoningEfforts: false` keeps
224
+ * that too.
225
+ *
226
+ * @param {unknown} section the live `llm-pi-ai` section value.
227
+ * @param {object} rawCfg plugin config.
228
+ * @returns {{section: unknown, changed: boolean, declared: Array<{provider: string, model: string, reason: string}>}} the plan.
229
+ */
230
+ export function planCapabilitySection(section, rawCfg) {
231
+ const cfg = normalizeConfig(rawCfg);
232
+ const declared = [];
233
+ if (section === null || typeof section !== 'object') return { section, changed: false, declared };
234
+ const providers = section.providers;
235
+ if (providers === null || typeof providers !== 'object' || Array.isArray(providers)) {
236
+ return { section, changed: false, declared };
237
+ }
238
+ /** @type {Record<string, unknown>} */
239
+ let nextProviders;
240
+ for (const [provider, profile] of Object.entries(providers)) {
241
+ if (profile === null || typeof profile !== 'object' || Array.isArray(profile)) continue;
242
+ const baseURL = typeof profile.baseURL === 'string' ? profile.baseURL : '';
243
+ let nextProfile = profile;
244
+ let routeDeclared = false;
245
+
246
+ if (Array.isArray(profile.models)) {
247
+ let nextModels;
248
+ profile.models.forEach((row, index) => {
249
+ const modelId = row !== null && typeof row === 'object' ? row.id : undefined;
250
+ if (typeof modelId !== 'string' || modelId.length === 0) return;
251
+ const decision = shouldDeclare({ provider, modelId, baseURL }, cfg);
252
+ if (!decision.declared) return;
253
+ const fixed = declareRow(row, cfg);
254
+ if (fixed === row) return;
255
+ routeDeclared = true;
256
+ declared.push({ provider, model: modelId, reason: decision.reason });
257
+ nextModels ??= [...profile.models];
258
+ nextModels[index] = fixed;
259
+ });
260
+ if (nextModels !== undefined) nextProfile = { ...nextProfile, models: nextModels };
261
+ }
262
+
263
+ if (profile.modelOverrides !== null && typeof profile.modelOverrides === 'object' && !Array.isArray(profile.modelOverrides)) {
264
+ let nextOverrides;
265
+ for (const [modelId, row] of Object.entries(profile.modelOverrides)) {
266
+ const decision = shouldDeclare({ provider, modelId, baseURL }, cfg);
267
+ if (!decision.declared) continue;
268
+ const fixed = declareRow(row, cfg);
269
+ if (fixed === row) continue;
270
+ routeDeclared = true;
271
+ declared.push({ provider, model: modelId, reason: decision.reason });
272
+ nextOverrides ??= { ...profile.modelOverrides };
273
+ nextOverrides[modelId] = fixed;
274
+ }
275
+ if (nextOverrides !== undefined) nextProfile = { ...nextProfile, modelOverrides: nextOverrides };
276
+ }
277
+
278
+ // Route-level default depth: the depth `auto` resolves to.
279
+ // pi-ai carries it per route, and an undeclared route keeps its own value.
280
+ if (routeDeclared && nextProfile.reasoning === undefined && cfg.defaultEffort !== undefined) {
281
+ nextProfile = { ...nextProfile, reasoning: cfg.defaultEffort };
282
+ }
283
+
284
+ if (nextProfile !== profile) {
285
+ nextProviders ??= { ...providers };
286
+ nextProviders[provider] = nextProfile;
287
+ }
288
+ }
289
+ if (nextProviders === undefined) return { section, changed: false, declared };
290
+ return { section: { ...section, providers: nextProviders }, changed: true, declared };
291
+ }
292
+
293
+ /**
294
+ * Add the `auto` mask to one resolved model's reasoning metadata.
295
+ *
296
+ * A switcher lists `auto` first and the declared levels after it. The mask is a
297
+ * UI value only: this plugin resolves it before the adapter sees it.
298
+ *
299
+ * @param {unknown} info `LlmResolvedModelInfo`-shaped metadata.
300
+ * @param {object} rawCfg plugin config.
301
+ * @param {{declared?: boolean}} [scope] whether this model was declared by us.
302
+ * @returns {unknown} the same reference when no mask is needed.
303
+ */
304
+ export function withAutoEffort(info, rawCfg, scope = {}) {
305
+ const cfg = normalizeConfig(rawCfg);
306
+ if (cfg.autoScope === 'off') return info;
307
+ if (cfg.autoScope === 'declared' && scope.declared !== true) return info;
308
+ if (info === null || typeof info !== 'object') return info;
309
+ const reasoning = info.reasoning;
310
+ if (reasoning === null || typeof reasoning !== 'object') return info;
311
+ const efforts = Array.isArray(reasoning.efforts) ? reasoning.efforts : [];
312
+ if (efforts.some((effort) => effort !== null && typeof effort === 'object' && effort.id === AUTO_EFFORT)) return info;
313
+ return {
314
+ ...info,
315
+ reasoning: {
316
+ ...reasoning,
317
+ efforts: [{ id: AUTO_EFFORT, name: EFFORT_NAMES[AUTO_EFFORT] }, ...efforts],
318
+ },
319
+ };
320
+ }
321
+
322
+ /** The depth levels of one vocabulary, `auto`/`off` excluded, in escalation order. */
323
+ export function depthLevels(efforts) {
324
+ if (!Array.isArray(efforts)) return [];
325
+ return efforts
326
+ .map((effort) => (effort !== null && typeof effort === 'object' ? effort.id : effort))
327
+ .filter((id) => typeof id === 'string' && id !== AUTO_EFFORT && id !== 'off')
328
+ .sort((left, right) => {
329
+ const a = rankOf(left);
330
+ const b = rankOf(right);
331
+ return (a < 0 ? Number.MAX_SAFE_INTEGER : a) - (b < 0 ? Number.MAX_SAFE_INTEGER : b);
332
+ });
333
+ }
334
+
335
+ /**
336
+ * Clamp one level onto a declared vocabulary.
337
+ *
338
+ * An undeclared level is never sent: DSH rejects an explicit user choice that
339
+ * the model does not advertise. A policy-computed level (rather than a user
340
+ * pick) therefore clamps to the nearest declared depth, preferring the stronger
341
+ * level on a tie: under-thinking a task is the failure this plugin exists to
342
+ * remove, so an unrepresentable `medium` becomes `high`, not `low`.
343
+ *
344
+ * @param {string | undefined} level wanted level.
345
+ * @param {readonly object[]} efforts declared vocabulary.
346
+ * @param {string} [whenEmpty] level to use when the vocabulary is empty.
347
+ * @returns {string | undefined} a declared level, or undefined.
348
+ */
349
+ export function clampEffort(level, efforts, whenEmpty) {
350
+ const depths = depthLevels(efforts);
351
+ if (depths.length === 0) return whenEmpty;
352
+ if (typeof level === 'string' && depths.includes(level)) return level;
353
+ const wanted = rankOf(level);
354
+ if (wanted < 0) return depths[0];
355
+ let best = depths[0];
356
+ let bestDistance = Number.POSITIVE_INFINITY;
357
+ for (const candidate of depths) {
358
+ const distance = Math.abs(rankOf(candidate) - wanted);
359
+ // `<=` resolves a tie upward: `depths` is escalation-ordered, so the later
360
+ // candidate at the same distance is the stronger level.
361
+ if (distance <= bestDistance) {
362
+ bestDistance = distance;
363
+ best = candidate;
364
+ }
365
+ }
366
+ return best;
367
+ }
368
+
369
+ /** Whether a request purpose is a host-owned cheap call. */
370
+ export function isAuxPurpose(purpose, rawCfg) {
371
+ const cfg = normalizeConfig(rawCfg);
372
+ if (!cfg.auxDowngrade) return false;
373
+ return typeof purpose === 'string' && cfg.auxPurposes.includes(purpose);
374
+ }
375
+
376
+ /**
377
+ * Decide the effort one model request should carry.
378
+ *
379
+ * The rules, in order:
380
+ * 1. A cheap host-owned call (session title, compaction, auto-review) →
381
+ * `auxLevel` when the model declares a level at or near it. This holds even
382
+ * with no explicit selection either: those calls are applied
383
+ * unconditionally, because a session's own depth never applies to a bounded
384
+ * summary request.
385
+ * 2. An explicit level → `undefined`: a user pick is passed through untouched
386
+ * (DSH validates it against the same vocabulary, so an undeclared pick never
387
+ * reaches the wire).
388
+ * 3. No explicit selection on an ordinary call → `undefined`: the adapter's own
389
+ * default stands (with the declaration above, that is `high`).
390
+ * 4. `auto` → the declared route default (DeepSeek: `high`), or the
391
+ * highest declared depth when the route names none.
392
+ *
393
+ * @param {object} input decision inputs.
394
+ * @param {string} [input.requested] the selection's effort.
395
+ * @param {string} [input.purpose] LLM request purpose.
396
+ * @param {readonly object[]} [input.efforts] declared vocabulary.
397
+ * @param {string} [input.defaultEffort] route/model default depth.
398
+ * @param {object} rawCfg plugin config.
399
+ * @returns {string | undefined} the level to send, or undefined to leave the request alone.
400
+ */
401
+ export function resolveCallEffort({ requested, purpose, efforts, defaultEffort }, rawCfg) {
402
+ const cfg = normalizeConfig(rawCfg);
403
+ if (requested !== undefined && requested !== AUTO_EFFORT) return undefined;
404
+ const depths = depthLevels(efforts);
405
+ if (depths.length === 0) return undefined;
406
+ if (isAuxPurpose(purpose, cfg)) {
407
+ const aux = clampEffort(cfg.auxLevel, efforts);
408
+ if (aux !== undefined) return aux;
409
+ }
410
+ if (requested === undefined) return undefined;
411
+ const target = cfg.autoLevel === 'model-default' || cfg.autoLevel === undefined
412
+ ? defaultEffort
413
+ : cfg.autoLevel;
414
+ if (typeof target === 'string' && depths.includes(target)) return target;
415
+ if (typeof target === 'string') return clampEffort(target, efforts);
416
+ return clampEffort('high', efforts, depths[depths.length - 1]);
417
+ }