dsh-auto-effort 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +106 -2
- package/config.js +85 -0
- package/cordis.patch.yml +17 -0
- package/docs/DETAIL.md +23 -0
- package/docs/DETAIL.zh.md +23 -0
- package/docs/preview.svg +17 -0
- package/icon.svg +6 -0
- package/index.js +308 -0
- package/judge.js +118 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +42 -4
- package/state.js +73 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-auto-effort contributors
|
|
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,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-auto-effort
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
DeepSeek Harness(DSH)插件:按你这一句话自动选推理档位(`off` / `low` / `high` / `max`)。
|
|
4
|
+
每条消息发出前用一次很小的模型调用做判定,判定结果只作用于**这一轮**。
|
|
5
|
+
|
|
6
|
+
Per-turn reasoning effort for DeepSeek Harness: one small judge call per user message,
|
|
7
|
+
applied to that same turn.
|
|
8
|
+
|
|
9
|
+
## 它做什么
|
|
10
|
+
|
|
11
|
+
1. 你发一条消息 → 插件把它单独发给判定模型(默认 `deepseek-flash`,只喂这一句,不带历史/工具结果)→ 得到 `off|low|high|max`。
|
|
12
|
+
2. 在消息入队之前调用宿主的 `agent.model.select()`,所以这一轮请求就用该档位。
|
|
13
|
+
3. 判定超时(默认 3 秒)或失败 → 退回你手动选的档位;连续 3 次失败 → 该会话切手动,不再自动改。
|
|
14
|
+
4. 出现 `content[].thinking` 回传错误 → 立刻回退手动并停止自动切换。
|
|
15
|
+
5. 子会话(subagent)完全跳过,不延迟、不判定。
|
|
16
|
+
|
|
17
|
+
## 安装
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
plugin_manager install_bundle dsh-auto-effort
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
或把本目录(绝对路径)交给 `install_bundle`,用本地链接方式安装。
|
|
24
|
+
|
|
25
|
+
## 配置
|
|
26
|
+
|
|
27
|
+
在 bundle 的 `cordis.patch.yml` / profile 配置里覆盖:
|
|
28
|
+
|
|
29
|
+
| 键 | 默认 | 说明 |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| `enabled` | `true` | 总开关 |
|
|
32
|
+
| `levels` | `[off, low, high, max]` | 参与判定的档位 |
|
|
33
|
+
| `judgeModel` | `deepseek-flash` | 判定用的模型 |
|
|
34
|
+
| `timeoutMs` | `3000` | 判定超时,超时即回退 |
|
|
35
|
+
| `defaultLevel` | `null` | `null` = 跟随手动档位 |
|
|
36
|
+
| `minDwellRounds` | `1` | 防抖:档位至少保持几轮 |
|
|
37
|
+
| `requireMaxForUpgrade` | `false` | `true` 时自动最多升到 `high`,`max` 只能手动 |
|
|
38
|
+
| `debug` | `false` | 写 `~/.dsh/auto-effort.log` |
|
|
39
|
+
| `logFile` | `null` | 自定义日志路径 |
|
|
40
|
+
|
|
41
|
+
## 重要限制(请先读)
|
|
42
|
+
|
|
43
|
+
- 与 npm 上的 `dsh-thinking-levels` **没有任何关系**:本包是独立实现,不走它的 pre-step/build 方案。
|
|
44
|
+
- **不是官方 `agent/pre-step` 方案。** brief 原方案要求在 `agent/pre-step` 里 `agent.model.select()`,但宿主在调用该钩子**之前**就已取好档位,所以那里改只能影响下一条消息。本插件改为在 `agent/created` 时包装该 agent 的 `followup`/`steer`:先判定、再 `select()`、再入队,因此能作用于当前这一轮。它**不修改** `agent/request`,不会触发 thinking 回传报错。
|
|
45
|
+
- 判定质量有限:偏“查资料/闲聊”的问题有时判成 `low` 而不是 `off`。
|
|
46
|
+
- 当前版本没有输入框旁的档位/理由界面(宿主原本的档位选择器会反映插件选中的档位)。
|
|
47
|
+
|
|
48
|
+
## 生效范围:哪些对话会被自动调档
|
|
49
|
+
|
|
50
|
+
插件在对话的 agent **创建的那一刻**接管它的“发送消息”动作。所以规则很简单:
|
|
51
|
+
|
|
52
|
+
| 对话是什么时候的 | 会不会自动调档 |
|
|
53
|
+
|---|---|
|
|
54
|
+
| 装好插件**之后**新建的对话 | ✅ 会 |
|
|
55
|
+
| 装好插件**之前**就已经打开、正在用的对话 | ❌ 本次不会(它的 agent 早就创建好了,插件拿不到) |
|
|
56
|
+
| 上面那种老对话,**重启 DSH 后重新打开** | ✅ 会(重新打开会为它新建 agent) |
|
|
57
|
+
| 子会话(subagent 跑的活) | ❌ 不判定、不延迟 |
|
|
58
|
+
|
|
59
|
+
一句话:**新对话立刻生效;老对话重启 DSH 再打开就生效;只有“安装那一刻正开着的会话”这一种情况本次不生效。**
|
|
60
|
+
|
|
61
|
+
## 开销:每判定一次花多少 token、多少钱
|
|
62
|
+
|
|
63
|
+
每条**用户消息**判定一次,工具调用回合不重复判定。
|
|
64
|
+
|
|
65
|
+
| 项 | 数量 |
|
|
66
|
+
|---|---|
|
|
67
|
+
| 额外请求数 | 每条用户消息 1 次 |
|
|
68
|
+
| 输入 token | 固定说明约 257 个汉字(≈ 150–200 token)+ 你这条消息本身 |
|
|
69
|
+
| 输出 token | 上限 8 token,实际通常 1 个词(如 `low`) |
|
|
70
|
+
| 思考 token | 0(判定请求以 `off` 档运行,不产生思考内容) |
|
|
71
|
+
|
|
72
|
+
成本就是一次很小请求的钱,公式:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
单条成本 ≈ (150~200 + 你的消息字数 × 0.6) × 输入单价 + 1 × 输出单价
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
按 2026-11 官方价(`deepseek-flash`:输入 $0.15/M 闲时、$0.30/M 忙时;输出 $0.60/M 闲时、$1.20/M 忙时;1 美元≈7.1 元)代入,**实际花多少**:
|
|
79
|
+
|
|
80
|
+
| 用量 | 大概成本 |
|
|
81
|
+
|---|---|
|
|
82
|
+
| 一条普通消息 | **¥0.0002 – ¥0.001**(大约千分之几毛,通常 0.0003 元左右) |
|
|
83
|
+
| 100 条消息 | ¥0.03 – ¥0.1(几分钱) |
|
|
84
|
+
|
|
85
|
+
长消息会略高(输入按字数涨),输出永远只有几个 token,可以忽略。价格随官方调整,以 platform.deepseek.com 定价页为准;前缀命中缓存时还会更便宜。
|
|
86
|
+
|
|
87
|
+
代价还有一点延迟:判定要先做完才把消息入队,所以每条消息会比平时晚约 0.3–1 秒发出(超时上限 `timeoutMs`,默认 3 秒,超时即退回手动档位,不阻塞)。
|
|
88
|
+
|
|
89
|
+
想完全不花这笔钱:`enabled: false`(完全停止),或把 `levels` 收窄。
|
|
90
|
+
|
|
91
|
+
- 判定质量有限:偏“查资料/闲聊”的问题有时判成 `low` 而不是 `off`。
|
|
92
|
+
|
|
93
|
+
## 卸载
|
|
94
|
+
|
|
95
|
+
```
|
|
96
|
+
plugin_manager remove_bundle dsh-auto-effort
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
卸载会同时清掉 profile 里 `dsh.profile.bundles` 的记录,不残留 override。
|
|
100
|
+
|
|
101
|
+
## 开发
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
node --test # 或分别运行 tools/test-think-level*.mjs
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
采用 MIT 许可。
|
package/config.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plugin configuration. The brief allows schemastery or zod; this bundle ships
|
|
3
|
+
* without dependencies (a linked local bundle cannot resolve the profile's
|
|
4
|
+
* node_modules), so the schema is validated by hand and every error names the
|
|
5
|
+
* offending key instead of silently coercing it.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const LEVELS = Object.freeze(['off', 'low', 'high', 'max'])
|
|
9
|
+
|
|
10
|
+
/** Config exactly as the brief §3.5 prescribes. */
|
|
11
|
+
export const DEFAULT_CONFIG = Object.freeze({
|
|
12
|
+
enabled: true,
|
|
13
|
+
levels: LEVELS,
|
|
14
|
+
judgeModel: 'deepseek-flash',
|
|
15
|
+
timeoutMs: 3000,
|
|
16
|
+
defaultLevel: null,
|
|
17
|
+
minDwellRounds: 1,
|
|
18
|
+
requireMaxForUpgrade: false,
|
|
19
|
+
// One line per judged turn in `~/.dsh/auto-effort.log` when enabled. Off by
|
|
20
|
+
// default for a published bundle; set `debug: true` or `logFile` to inspect.
|
|
21
|
+
debug: false,
|
|
22
|
+
logFile: null,
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
function fail(message) {
|
|
26
|
+
throw new Error(`[auto-effort] invalid config: ${message}`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Merge defaults with the patch/profiles config and validate every field.
|
|
31
|
+
* @param {unknown} raw - value handed to `apply` by the Cordis loader.
|
|
32
|
+
* @returns {Readonly<typeof DEFAULT_CONFIG>} validated config.
|
|
33
|
+
*/
|
|
34
|
+
export function resolveConfig(raw) {
|
|
35
|
+
const input = raw === undefined || raw === null ? {} : raw
|
|
36
|
+
if (typeof input !== 'object' || Array.isArray(input)) fail('expected an object')
|
|
37
|
+
|
|
38
|
+
const enabled = input.enabled ?? DEFAULT_CONFIG.enabled
|
|
39
|
+
if (typeof enabled !== 'boolean') fail('enabled must be a boolean')
|
|
40
|
+
|
|
41
|
+
const levelsInput = input.levels ?? DEFAULT_CONFIG.levels
|
|
42
|
+
if (!Array.isArray(levelsInput) || levelsInput.length === 0) fail('levels must be a non-empty array')
|
|
43
|
+
const levels = []
|
|
44
|
+
for (const level of levelsInput) {
|
|
45
|
+
if (!LEVELS.includes(level)) fail(`levels contains "${String(level)}"; allowed: ${LEVELS.join(', ')}`)
|
|
46
|
+
if (!levels.includes(level)) levels.push(level)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const judgeModel = input.judgeModel ?? DEFAULT_CONFIG.judgeModel
|
|
50
|
+
if (typeof judgeModel !== 'string' || judgeModel.trim() === '') fail('judgeModel must be a non-empty string')
|
|
51
|
+
|
|
52
|
+
const timeoutMs = input.timeoutMs ?? DEFAULT_CONFIG.timeoutMs
|
|
53
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 60_000) {
|
|
54
|
+
fail('timeoutMs must be an integer between 100 and 60000')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const defaultLevel = input.defaultLevel ?? DEFAULT_CONFIG.defaultLevel
|
|
58
|
+
if (defaultLevel !== null && !LEVELS.includes(defaultLevel)) {
|
|
59
|
+
fail(`defaultLevel must be null or one of ${LEVELS.join(', ')}`)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const minDwellRounds = input.minDwellRounds ?? DEFAULT_CONFIG.minDwellRounds
|
|
63
|
+
if (!Number.isInteger(minDwellRounds) || minDwellRounds < 1) fail('minDwellRounds must be an integer >= 1')
|
|
64
|
+
|
|
65
|
+
const requireMaxForUpgrade = input.requireMaxForUpgrade ?? DEFAULT_CONFIG.requireMaxForUpgrade
|
|
66
|
+
if (typeof requireMaxForUpgrade !== 'boolean') fail('requireMaxForUpgrade must be a boolean')
|
|
67
|
+
|
|
68
|
+
const debug = input.debug ?? DEFAULT_CONFIG.debug
|
|
69
|
+
if (typeof debug !== 'boolean') fail('debug must be a boolean')
|
|
70
|
+
|
|
71
|
+
const logFile = input.logFile ?? DEFAULT_CONFIG.logFile
|
|
72
|
+
if (logFile !== null && typeof logFile !== 'string') fail('logFile must be null or a path string')
|
|
73
|
+
|
|
74
|
+
return Object.freeze({
|
|
75
|
+
enabled,
|
|
76
|
+
levels: Object.freeze(levels),
|
|
77
|
+
judgeModel,
|
|
78
|
+
timeoutMs,
|
|
79
|
+
defaultLevel,
|
|
80
|
+
minDwellRounds,
|
|
81
|
+
requireMaxForUpgrade,
|
|
82
|
+
debug,
|
|
83
|
+
logFile,
|
|
84
|
+
})
|
|
85
|
+
}
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
- insert:
|
|
2
|
+
- id: auto-effort
|
|
3
|
+
name: 'dsh-auto-effort'
|
|
4
|
+
config:
|
|
5
|
+
enabled: true
|
|
6
|
+
levels:
|
|
7
|
+
- off
|
|
8
|
+
- low
|
|
9
|
+
- high
|
|
10
|
+
- max
|
|
11
|
+
judgeModel: deepseek-flash
|
|
12
|
+
timeoutMs: 3000
|
|
13
|
+
defaultLevel: null
|
|
14
|
+
minDwellRounds: 1
|
|
15
|
+
requireMaxForUpgrade: false
|
|
16
|
+
debug: false
|
|
17
|
+
logFile: null
|
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
## Which conversations it affects
|
|
4
|
+
|
|
5
|
+
The bundle takes over an agent the moment that agent is created. So:
|
|
6
|
+
|
|
7
|
+
- A conversation started **after** the bundle loads is judged from its first message.
|
|
8
|
+
- A conversation that was **already open** when the bundle loaded is **not** judged in that run: its agent already existed and never emits `agent/created` again. Reopen it after restarting DSH and it is judged from then on.
|
|
9
|
+
- Subagent runs are never judged and never delayed.
|
|
10
|
+
|
|
11
|
+
## What each judgement costs
|
|
12
|
+
|
|
13
|
+
One extra, very small request per **user message** (tool rounds are not re-judged):
|
|
14
|
+
|
|
15
|
+
- input: a fixed instruction of about 257 Chinese characters (roughly 150–200 tokens) plus the user message itself;
|
|
16
|
+
- output: at most 8 tokens, in practice a single word such as `low`;
|
|
17
|
+
- reasoning tokens: none — the judge call runs with `off`.
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
cost per message ≈ (150–200 + message characters × 0.6) × input price + 1 × output price
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
At the November 2026 `deepseek-flash` list price (input $0.15/M off-peak, $0.30/M peak; output $0.60/M off-peak, $1.20/M peak) that is about **$0.00003–$0.00015 per message** (¥0.0002–¥0.001), or ¥0.03–¥0.1 per 100 messages. Long messages cost a little more; the output is always a few tokens. Fill in your provider's current prices if they differ. Each judgement also delays the message by roughly 0.3–1 s (bounded by `timeoutMs`, 3 s by default, after which the manual level is used and the turn is not blocked). Set `enabled: false` to stop spending entirely.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
## 哪些对话会被自动调档
|
|
4
|
+
|
|
5
|
+
插件在 agent 创建的那一刻接管它的发送动作。所以:
|
|
6
|
+
|
|
7
|
+
- 插件加载**之后**新建的对话,从第一条消息起就会被判定;
|
|
8
|
+
- 插件加载时**已经开着**的对话,本次不会被判定(它的 agent 早已创建,不会再触发 `agent/created`);**重启 DSH 后重新打开**它,就开始生效;
|
|
9
|
+
- 子会话(subagent)不判定、不延迟。
|
|
10
|
+
|
|
11
|
+
## 每次判定花多少
|
|
12
|
+
|
|
13
|
+
每条**用户消息**额外一次很小的请求(工具回合不重复判定):
|
|
14
|
+
|
|
15
|
+
- 输入:约 257 个汉字的固定说明(大致 150–200 token)+ 你这条消息本身;
|
|
16
|
+
- 输出:最多 8 token,实际通常只有一个词(如 `low`);
|
|
17
|
+
- 思考 token:0(判定以 `off` 档运行)。
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
单条成本 ≈ (150~200 + 消息字数 × 0.6) × 输入单价 + 1 × 输出单价
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
按 2026 年 11 月 `deepseek-flash` 官方价(输入 $0.15/M 闲时、$0.30/M 忙时;输出 $0.60/M 闲时、$1.20/M 忙时)代入,约为 **每条消息 ¥0.0002 – ¥0.001**,100 条消息约 ¥0.03 – ¥0.1。长消息略高;输出只有几个 token,可以忽略。单价以 platform.deepseek.com 为准。判定还会让消息晚约 0.3–1 秒发出(上限 `timeoutMs`,默认 3 秒,超时退回手动档位、不阻塞)。把 `enabled` 设为 `false` 就完全不花这笔钱。
|
package/docs/preview.svg
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" role="img" aria-label="A message is graded into one of four thinking levels before it is sent">
|
|
2
|
+
<g fill="none" stroke="#8b95a5" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
|
|
3
|
+
<path d="M64 96 h176 a20 20 0 0 1 20 20 v64 a20 20 0 0 1 -20 20 h-132 l-24 24 v-24 h-20 a20 20 0 0 1 -20 -20 v-64 a20 20 0 0 1 20 -20 z"/>
|
|
4
|
+
<path d="M96 148 h6 M136 148 h6 M176 148 h6"/>
|
|
5
|
+
<path d="M300 150 h52"/>
|
|
6
|
+
<path d="M336 134 l18 16 -18 16"/>
|
|
7
|
+
<path d="M376 210 h176" stroke="#5b6472"/>
|
|
8
|
+
<path d="M392 210 v-42"/>
|
|
9
|
+
<path d="M440 210 v-72"/>
|
|
10
|
+
<path d="M488 210 v-104"/>
|
|
11
|
+
<path d="M536 210 v-138"/>
|
|
12
|
+
</g>
|
|
13
|
+
<rect x="526" y="62" width="20" height="148" rx="8" fill="#3b82f6" fill-opacity="0.22"/>
|
|
14
|
+
<path d="M530 62 h12 a8 8 0 0 1 8 8 v8 h-28 v-8 a8 8 0 0 1 8 -8 z" fill="#3b82f6"/>
|
|
15
|
+
<circle cx="536" cy="238" r="14" fill="none" stroke="#3b82f6" stroke-width="3"/>
|
|
16
|
+
<path d="M529 238 l5 5 9 -10" fill="none" stroke="#3b82f6" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
|
17
|
+
</svg>
|
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Think level">
|
|
2
|
+
<rect x="8" y="40" width="10" height="16" rx="3" fill="currentColor" opacity="0.35"/>
|
|
3
|
+
<rect x="22" y="30" width="10" height="26" rx="3" fill="currentColor" opacity="0.55"/>
|
|
4
|
+
<rect x="36" y="20" width="10" height="36" rx="3" fill="currentColor" opacity="0.75"/>
|
|
5
|
+
<rect x="50" y="8" width="10" height="48" rx="3" fill="currentColor"/>
|
|
6
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-auto-effort — choose the reasoning effort for every user turn.
|
|
3
|
+
*
|
|
4
|
+
* Why this hooks `agent.followup` instead of `agent/pre-step`
|
|
5
|
+
* ----------------------------------------------------------
|
|
6
|
+
* The brief asks for a per-turn level, changed only through the Agent's own
|
|
7
|
+
* model selection (`agent.model.select()`), never by rewriting
|
|
8
|
+
* `agent/request.reasoningEffort` (that is what crashed
|
|
9
|
+
* `dsh-thinking-levels@4.4.16` with
|
|
10
|
+
* "The `content[].thinking` in the thinking mode must be passed back to the API").
|
|
11
|
+
*
|
|
12
|
+
* `dsh-agent-loop` captures the selection *before* it runs the `agent/pre-step`
|
|
13
|
+
* waterfall:
|
|
14
|
+
*
|
|
15
|
+
* const selection = this.model.current() // ← captured here
|
|
16
|
+
* const decision = await this.dispatch.waterfall('agent/pre-step', …)
|
|
17
|
+
* return { ...decision, selection, … } // ← our select() arrives too late
|
|
18
|
+
*
|
|
19
|
+
* so a select() made inside `agent/pre-step` only applies to the *next* step.
|
|
20
|
+
* A one-step user turn would therefore always run one message behind.
|
|
21
|
+
*
|
|
22
|
+
* The probe run in this workspace proved the earlier seam: the desktop
|
|
23
|
+
* controller calls `agent.followup(message)` (and `agent.steer`) without
|
|
24
|
+
* awaiting it, *after* the prompt has been accepted and *before* the message is
|
|
25
|
+
* queued. Wrapping that call lets us judge the prompt and record the selection
|
|
26
|
+
* first, so the turn the user just sent really runs at the judged level.
|
|
27
|
+
* Only `agent.model.select()` is used, so the host stays in charge of assembly.
|
|
28
|
+
*
|
|
29
|
+
* Costs and limits (documented, not hidden):
|
|
30
|
+
* - the user's message is inserted after the judge answers, bounded by
|
|
31
|
+
* `timeoutMs` (3 s default); a slow or offline judge never blocks the turn
|
|
32
|
+
* forever and never swallows it;
|
|
33
|
+
* - every user turn costs one extra tiny LLM call (a few output tokens);
|
|
34
|
+
* - only Agents created after the plugin loads are wrapped, so start a new
|
|
35
|
+
* session (or restart the app) after installing/updating.
|
|
36
|
+
*/
|
|
37
|
+
import { appendFileSync } from 'node:fs'
|
|
38
|
+
import { homedir } from 'node:os'
|
|
39
|
+
import { join } from 'node:path'
|
|
40
|
+
import { resolveConfig } from './config.js'
|
|
41
|
+
import { judgeLevel } from './judge.js'
|
|
42
|
+
import { publish, stateOf } from './state.js'
|
|
43
|
+
|
|
44
|
+
const WRAPPED = new WeakSet()
|
|
45
|
+
|
|
46
|
+
/** The judge needs the host LLM runtime; Cordis only exposes it when declared. */
|
|
47
|
+
export const inject = ['llm']
|
|
48
|
+
|
|
49
|
+
/** The exact host-side failure this plugin must never cause. */
|
|
50
|
+
const THINKING_ERROR = /content\[\]\.thinking|thinking mode must be passed back/i
|
|
51
|
+
|
|
52
|
+
const FAILURES_BEFORE_MANUAL = 3
|
|
53
|
+
|
|
54
|
+
function makeLogger(ctx, config) {
|
|
55
|
+
let logger = null
|
|
56
|
+
try {
|
|
57
|
+
logger = typeof ctx.logger === 'function' ? ctx.logger('auto-effort') : null
|
|
58
|
+
} catch {
|
|
59
|
+
logger = null
|
|
60
|
+
}
|
|
61
|
+
const file = config.debug
|
|
62
|
+
? (config.logFile ?? join(homedir(), '.dsh', 'auto-effort.log'))
|
|
63
|
+
: null
|
|
64
|
+
const write = (level, message) => {
|
|
65
|
+
try {
|
|
66
|
+
const fn = logger?.[level]
|
|
67
|
+
if (typeof fn === 'function') fn.call(logger, message)
|
|
68
|
+
} catch {
|
|
69
|
+
/* logging must never break a turn */
|
|
70
|
+
}
|
|
71
|
+
if (file !== null) {
|
|
72
|
+
try {
|
|
73
|
+
appendFileSync(file, `${new Date().toISOString()} ${level.toUpperCase()} ${message}\n`)
|
|
74
|
+
} catch {
|
|
75
|
+
/* a log file problem must never break a turn */
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
debug: message => write('debug', message),
|
|
81
|
+
info: message => write('info', message),
|
|
82
|
+
warn: message => write('warn', message),
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The text of a message, or null when it carries no prose (images only, empty). */
|
|
87
|
+
function promptText(message) {
|
|
88
|
+
const content = message?.content
|
|
89
|
+
if (!Array.isArray(content)) return null
|
|
90
|
+
const parts = []
|
|
91
|
+
for (const block of content) {
|
|
92
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') parts.push(block.text)
|
|
93
|
+
}
|
|
94
|
+
if (parts.length === 0) return null
|
|
95
|
+
return parts.join('\n')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Only a real user turn is judged: retries, goal continuation, notices and
|
|
100
|
+
* tool-delivered messages must never spend a judge call or move the level.
|
|
101
|
+
*/
|
|
102
|
+
function isUserTurn(message) {
|
|
103
|
+
if (message?.source?.kind !== 'user') return false
|
|
104
|
+
if (message?.source?.form === 'notice') return false
|
|
105
|
+
return promptText(message) !== null
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** `judgeModel` may be "model" (current provider) or "provider/model". */
|
|
109
|
+
function judgeRoute(judgeModel, provider) {
|
|
110
|
+
const slash = judgeModel.indexOf('/')
|
|
111
|
+
if (slash > 0) return { provider: judgeModel.slice(0, slash), model: judgeModel.slice(slash + 1) }
|
|
112
|
+
return { provider, model: judgeModel }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function recordFailure(state, config, logger, agent, error) {
|
|
116
|
+
state.failures += 1
|
|
117
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
118
|
+
logger.warn(`judge failed (${state.failures}x): ${detail}`)
|
|
119
|
+
if (state.failures >= FAILURES_BEFORE_MANUAL) {
|
|
120
|
+
// Brief §2.4: stop trying after three consecutive failures and say so.
|
|
121
|
+
state.auto = false
|
|
122
|
+
state.tripped = true
|
|
123
|
+
state.source = 'manual'
|
|
124
|
+
state.reason = `连续 ${FAILURES_BEFORE_MANUAL} 次判断失败(${detail}),已切换到手动模式`
|
|
125
|
+
publish(agent, state)
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
if (config.defaultLevel !== null) {
|
|
129
|
+
// A configured fallback still beats silently keeping the old level.
|
|
130
|
+
const current = agent.model.current()
|
|
131
|
+
if (current?.provider && current?.model) {
|
|
132
|
+
try {
|
|
133
|
+
agent.model.select({ ...current, reasoningEffort: config.defaultLevel })
|
|
134
|
+
state.level = config.defaultLevel
|
|
135
|
+
state.source = 'auto'
|
|
136
|
+
state.reason = `判断失败(${detail}),回退到 defaultLevel=${config.defaultLevel}`
|
|
137
|
+
publish(agent, state)
|
|
138
|
+
return
|
|
139
|
+
} catch {
|
|
140
|
+
/* fall through to the plain "keep manual" reason */
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
state.reason = `判断失败,沿用手动档位(${detail})`
|
|
145
|
+
publish(agent, state)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Judge one prompt and record the level the turn should run at.
|
|
150
|
+
* Never throws: a judge problem must never block the conversation.
|
|
151
|
+
*/
|
|
152
|
+
async function decide(ctx, agent, state, config, logger, message) {
|
|
153
|
+
const current = agent.model.current()
|
|
154
|
+
if (current === undefined || current?.provider === undefined || current?.model === undefined) {
|
|
155
|
+
state.reason = '当前会话没有可用的模型选择,未参与自动判断'
|
|
156
|
+
publish(agent, state)
|
|
157
|
+
return
|
|
158
|
+
}
|
|
159
|
+
const text = promptText(message)
|
|
160
|
+
if (text === null) return
|
|
161
|
+
|
|
162
|
+
state.judgedTurns += 1
|
|
163
|
+
logger.info(`turn ${state.judgedTurns} judging (${text.length} chars): ${text.slice(0, 60).replace(/\s+/g, ' ')}`)
|
|
164
|
+
const route = judgeRoute(config.judgeModel, current.provider)
|
|
165
|
+
const judged = await judgeLevel({
|
|
166
|
+
llm: ctx.llm,
|
|
167
|
+
provider: route.provider,
|
|
168
|
+
model: route.model,
|
|
169
|
+
text,
|
|
170
|
+
timeoutMs: config.timeoutMs,
|
|
171
|
+
signal: agent.lifetimeSignal ?? undefined,
|
|
172
|
+
debug: config.debug === true ? logger.debug : undefined,
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
// Brief §2.2: the adapter only knows these four. Anything else is a judge bug.
|
|
176
|
+
if (!config.levels.includes(judged)) {
|
|
177
|
+
throw new Error(`judge returned "${judged}", which is not enabled in config.levels`)
|
|
178
|
+
}
|
|
179
|
+
// Brief §3.3: optional cap so an automatic run never escalates to maximum.
|
|
180
|
+
const target = config.requireMaxForUpgrade && judged === 'max' ? 'high' : judged
|
|
181
|
+
|
|
182
|
+
if (current.reasoningEffort === target) {
|
|
183
|
+
state.level = target
|
|
184
|
+
state.source = 'auto'
|
|
185
|
+
state.reason = `判断为 ${judged},与当前档位相同,未切换`
|
|
186
|
+
publish(agent, state)
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Brief §3.3: anti-flap. The current level must survive minDwellRounds turns.
|
|
191
|
+
if (state.judgedTurns - state.lastChangeTurn < config.minDwellRounds) {
|
|
192
|
+
state.level = current.reasoningEffort ?? state.level
|
|
193
|
+
state.source = state.level === null ? 'manual' : 'auto'
|
|
194
|
+
state.reason = `判断为 ${judged},但为防抖动本轮保持上一档(${state.level ?? '手动'})`
|
|
195
|
+
publish(agent, state)
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// The only sanctioned way to move the level: the Agent's own selection, which
|
|
200
|
+
// the host folds into the projection the step preparation reads.
|
|
201
|
+
agent.model.select({ provider: current.provider, model: current.model, reasoningEffort: target })
|
|
202
|
+
state.level = target
|
|
203
|
+
state.source = 'auto'
|
|
204
|
+
state.reason = `判断为 ${judged},切换到 ${target}`
|
|
205
|
+
state.failures = 0
|
|
206
|
+
state.lastChangeTurn = state.judgedTurns
|
|
207
|
+
publish(agent, state)
|
|
208
|
+
logger.info(`turn ${state.judgedTurns}: ${judged} -> ${target}`)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function attach(ctx, agent, config, logger) {
|
|
212
|
+
if (agent === null || typeof agent !== 'object' || WRAPPED.has(agent)) return
|
|
213
|
+
// Subagent sessions are not user turns: judging them would spend a call on
|
|
214
|
+
// every delegated task and, because the subagent manager disposes a child that
|
|
215
|
+
// has not started a step yet, delaying their prompt breaks the run. The
|
|
216
|
+
// marker lives on the session header (`session.header.origin`), not on the
|
|
217
|
+
// session object itself.
|
|
218
|
+
const origin = agent.session?.header?.origin ?? agent.session?.origin
|
|
219
|
+
if (origin === 'subagent') {
|
|
220
|
+
logger.debug(`skipped subagent session ${String(agent.session?.header?.id)}`)
|
|
221
|
+
return
|
|
222
|
+
}
|
|
223
|
+
const state = stateOf(agent, config)
|
|
224
|
+
if (!config.enabled) state.auto = false
|
|
225
|
+
let wrappedAny = false
|
|
226
|
+
for (const method of ['followup', 'steer']) {
|
|
227
|
+
const original = agent[method]
|
|
228
|
+
if (typeof original !== 'function') continue
|
|
229
|
+
let assigned = false
|
|
230
|
+
try {
|
|
231
|
+
const previous = agent[method]
|
|
232
|
+
agent[method] = function thinkLevelDispatch(message, ...rest) {
|
|
233
|
+
if (!state.auto || state.tripped || !isUserTurn(message)) {
|
|
234
|
+
logger.debug(`${method} skipped (auto=${state.auto}, tripped=${state.tripped}, kind=${String(message?.source?.kind)})`)
|
|
235
|
+
return original.call(agent, message, ...rest)
|
|
236
|
+
}
|
|
237
|
+
// The controller does not await followup/steer, so returning a promise is
|
|
238
|
+
// fine: judge first, then queue exactly the message the user sent.
|
|
239
|
+
return (async () => {
|
|
240
|
+
try {
|
|
241
|
+
await decide(ctx, agent, state, config, logger, message)
|
|
242
|
+
} catch (error) {
|
|
243
|
+
recordFailure(state, config, logger, agent, error)
|
|
244
|
+
}
|
|
245
|
+
return original.call(agent, message, ...rest)
|
|
246
|
+
})()
|
|
247
|
+
}
|
|
248
|
+
assigned = agent[method] !== previous
|
|
249
|
+
} catch (error) {
|
|
250
|
+
logger.warn(`cannot wrap agent.${method}: ${error instanceof Error ? error.message : String(error)}`)
|
|
251
|
+
}
|
|
252
|
+
if (assigned) wrappedAny = true
|
|
253
|
+
}
|
|
254
|
+
if (wrappedAny) {
|
|
255
|
+
WRAPPED.add(agent)
|
|
256
|
+
logger.info(`agent ${String(agent.id ?? agent.session?.id ?? '?')} wrapped`)
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Circuit breaker (brief §3.3): the thinking round-trip error means a request
|
|
262
|
+
* was assembled against an inconsistent level. Stop automatic switching for
|
|
263
|
+
* that conversation at once instead of repeating the failure every turn.
|
|
264
|
+
*/
|
|
265
|
+
function trip(payload, logger) {
|
|
266
|
+
const agent = payload?.agent ?? payload
|
|
267
|
+
const error = payload?.error ?? payload
|
|
268
|
+
const text = String(error?.message ?? error?.data?.message ?? error ?? '')
|
|
269
|
+
const state = agent && typeof agent === 'object' ? stateOf(agent, { enabled: false }) : null
|
|
270
|
+
if (state === null || !THINKING_ERROR.test(text)) return
|
|
271
|
+
state.auto = false
|
|
272
|
+
state.tripped = true
|
|
273
|
+
state.source = 'manual'
|
|
274
|
+
state.level = agent.model?.current?.()?.reasoningEffort ?? state.level
|
|
275
|
+
state.reason = `检测到 thinking 回传错误,已停止自动切换:${text.slice(0, 120)}`
|
|
276
|
+
publish(agent, state)
|
|
277
|
+
logger.warn(`circuit breaker tripped: ${text.slice(0, 200)}`)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Host plugin entry point.
|
|
282
|
+
* @param {object} ctx - the plugin's scoped Cordis context.
|
|
283
|
+
* @param {unknown} rawConfig - config from `cordis.patch.yml`.
|
|
284
|
+
*/
|
|
285
|
+
export function apply(ctx, rawConfig) {
|
|
286
|
+
const config = resolveConfig(rawConfig)
|
|
287
|
+
const logger = makeLogger(ctx, config)
|
|
288
|
+
logger.info(`loaded (enabled=${config.enabled}, judge=${config.judgeModel}, timeout=${config.timeoutMs}ms)`)
|
|
289
|
+
|
|
290
|
+
ctx.on('agent/created', payload => {
|
|
291
|
+
const agent = payload?.agent ?? payload
|
|
292
|
+
try {
|
|
293
|
+
attach(ctx, agent, config, logger)
|
|
294
|
+
} catch (error) {
|
|
295
|
+
logger.warn(`attach failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
296
|
+
}
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
for (const hook of ['agent/error', 'agent/request-error']) {
|
|
300
|
+
ctx.on(hook, payload => {
|
|
301
|
+
try {
|
|
302
|
+
trip(payload, logger)
|
|
303
|
+
} catch {
|
|
304
|
+
/* a breaker must never throw into the host */
|
|
305
|
+
}
|
|
306
|
+
})
|
|
307
|
+
}
|
|
308
|
+
}
|
package/judge.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The judge: one independent, lightweight LLM call per turn.
|
|
3
|
+
*
|
|
4
|
+
* The brief (§2.1) fixes the shape of this call:
|
|
5
|
+
* - input is only the newest user message plus this short instruction
|
|
6
|
+
* (no history, no tool results, no project system prompt);
|
|
7
|
+
* - the instruction lives in the system slot so every turn reuses the exact
|
|
8
|
+
* same prefix and the provider's KV cache keeps working;
|
|
9
|
+
* - the output is one word, capped at a few tokens;
|
|
10
|
+
* - the whole call is deadline-bounded, and any failure is reported as an
|
|
11
|
+
* error to the caller, which falls back to the user's manual level.
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from 'node:crypto'
|
|
14
|
+
|
|
15
|
+
/** Stable prefix: never interpolate per-turn text into this string. */
|
|
16
|
+
export const JUDGE_SYSTEM = [
|
|
17
|
+
'你是一个任务难度判定器。',
|
|
18
|
+
'你会收到用户的一条消息,只判断“回答它需要多强的推理能力”,不需要真的回答。',
|
|
19
|
+
'只输出一个词,不要标点、不要解释、不要换行。',
|
|
20
|
+
].join('\n')
|
|
21
|
+
|
|
22
|
+
/** The four-way rubric from the brief §2.3, verbatim in spirit. */
|
|
23
|
+
export const JUDGE_INSTRUCTION = [
|
|
24
|
+
'从下面四个词里选一个最合适的,只输出这个词:',
|
|
25
|
+
'off',
|
|
26
|
+
'low',
|
|
27
|
+
'high',
|
|
28
|
+
'max',
|
|
29
|
+
'',
|
|
30
|
+
'判定标准:',
|
|
31
|
+
'off:闲聊、确认、简单改写、查资料、改配置、跑命令。',
|
|
32
|
+
'low:有一定逻辑但路径清晰(整理信息、单文件改动、解释一个具体概念)。',
|
|
33
|
+
'high:需要分析、排查问题、解释原理、写较复杂代码、做设计取舍。',
|
|
34
|
+
'max:高难度推理(复杂架构决策、多因素权衡、疑难 bug、长链条推导)。',
|
|
35
|
+
].join('\n')
|
|
36
|
+
|
|
37
|
+
const WORD_RE = /\b(off|low|high|max)\b/i
|
|
38
|
+
|
|
39
|
+
/** Subset of the adapter error that means “this model has no such effort”. */
|
|
40
|
+
function isUnsupportedEffort(error) {
|
|
41
|
+
const code = error?.code ?? error?.data?.code
|
|
42
|
+
const text = String(error?.message ?? error ?? '')
|
|
43
|
+
return code === 'UNSUPPORTED_REASONING_EFFORT' || /UNSUPPORTED_REASONING_EFFORT|does not support reasoning effort/i.test(text)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function combineSignals(signal, timeoutMs) {
|
|
47
|
+
const controller = new AbortController()
|
|
48
|
+
const timer = setTimeout(() => controller.abort(new Error(`judge timed out after ${timeoutMs} ms`)), timeoutMs)
|
|
49
|
+
const forward = () => controller.abort(signal?.reason)
|
|
50
|
+
if (signal) {
|
|
51
|
+
if (signal.aborted) forward()
|
|
52
|
+
else signal.addEventListener('abort', forward, { once: true })
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
signal: controller.signal,
|
|
56
|
+
dispose() {
|
|
57
|
+
clearTimeout(timer)
|
|
58
|
+
signal?.removeEventListener('abort', forward)
|
|
59
|
+
},
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Ask the judge for a level.
|
|
65
|
+
* @param {object} options
|
|
66
|
+
* @param {{ prepareCall: Function }} options.llm - host `ctx.llm` service.
|
|
67
|
+
* @param {string} options.provider - provider of the session's current route.
|
|
68
|
+
* @param {string} options.model - judge model id from config.
|
|
69
|
+
* @param {string} options.text - the newest user message, unchanged.
|
|
70
|
+
* @param {number} options.timeoutMs - end-to-end deadline.
|
|
71
|
+
* @param {AbortSignal} [options.signal] - the turn's signal.
|
|
72
|
+
* @param {(message: string) => void} [options.debug]
|
|
73
|
+
* @returns {Promise<string>} one of off|low|high|max.
|
|
74
|
+
*/
|
|
75
|
+
export async function judgeLevel({ llm, provider, model, text, timeoutMs, signal, debug }) {
|
|
76
|
+
if (typeof llm?.prepareCall !== 'function') throw new Error('the host llm service is unavailable')
|
|
77
|
+
const route = { provider, model }
|
|
78
|
+
const bound = combineSignals(signal, timeoutMs)
|
|
79
|
+
try {
|
|
80
|
+
let call
|
|
81
|
+
try {
|
|
82
|
+
call = await llm.prepareCall({ ...route, maxTokens: 8, reasoningEffort: 'off' }, bound.signal, controls => controls)
|
|
83
|
+
} catch (error) {
|
|
84
|
+
// A route that cannot run with `off` still answers; drop the effort.
|
|
85
|
+
if (!isUnsupportedEffort(error)) throw error
|
|
86
|
+
call = await llm.prepareCall({ ...route, maxTokens: 8 }, bound.signal, controls => controls)
|
|
87
|
+
}
|
|
88
|
+
bound.signal.throwIfAborted()
|
|
89
|
+
const options = Object.freeze({
|
|
90
|
+
...call.config,
|
|
91
|
+
messages: [{
|
|
92
|
+
id: randomUUID(),
|
|
93
|
+
role: 'user',
|
|
94
|
+
content: [{ type: 'text', text: `${JUDGE_INSTRUCTION}\n\n用户消息:\n${text}` }],
|
|
95
|
+
source: { kind: 'user' },
|
|
96
|
+
}],
|
|
97
|
+
system: JUDGE_SYSTEM,
|
|
98
|
+
signal: bound.signal,
|
|
99
|
+
})
|
|
100
|
+
let answer = ''
|
|
101
|
+
let finish
|
|
102
|
+
for await (const chunk of call.stream(options)) {
|
|
103
|
+
bound.signal.throwIfAborted()
|
|
104
|
+
if (chunk.type === 'text-delta') answer += chunk.text
|
|
105
|
+
else if (chunk.type === 'finish') finish = chunk.reason
|
|
106
|
+
}
|
|
107
|
+
bound.signal.throwIfAborted()
|
|
108
|
+
debug?.(`judge raw="${answer.trim()}" finish=${JSON.stringify(finish)}`)
|
|
109
|
+
if (finish && finish.kind !== 'stop' && finish.kind !== 'max-tokens') {
|
|
110
|
+
throw new Error(`judge finished with ${finish.kind}`)
|
|
111
|
+
}
|
|
112
|
+
const match = WORD_RE.exec(answer)
|
|
113
|
+
if (!match) throw new Error(`judge returned no level: ${JSON.stringify(answer.slice(0, 40))}`)
|
|
114
|
+
return match[1].toLowerCase()
|
|
115
|
+
} finally {
|
|
116
|
+
bound.dispose()
|
|
117
|
+
}
|
|
118
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Automatic effort",
|
|
4
|
+
"description": "Picks the reasoning effort for every user message with one tiny extra call (about 200 tokens in, one word out) and applies it to that same turn. Conversations already open when the bundle loads are judged only after DSH restarts; subagent runs are never judged. Adds roughly half a second per message. Turn the bundle off to stop it; the level you chose by hand is kept.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-auto-effort",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Per-turn reasoning effort picker for DeepSeek Harness: judges the newest user message with one lightweight LLM call and selects off/low/high/max for that same turn.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"dsh",
|
|
9
|
+
"deepseek-harness",
|
|
10
|
+
"dsh-bundle",
|
|
11
|
+
"reasoning-effort",
|
|
12
|
+
"thinking"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./index.js",
|
|
22
|
+
"./icon": "./icon.svg",
|
|
23
|
+
"./locale/en": "./locale/en.json",
|
|
24
|
+
"./locale/zh": "./locale/zh.json"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"index.js",
|
|
28
|
+
"judge.js",
|
|
29
|
+
"config.js",
|
|
30
|
+
"state.js",
|
|
31
|
+
"icon.svg",
|
|
32
|
+
"locale/en.json",
|
|
33
|
+
"locale/zh.json",
|
|
34
|
+
"cordis.patch.yml",
|
|
35
|
+
"docs",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"README.md"
|
|
38
|
+
],
|
|
39
|
+
"dsh": {
|
|
40
|
+
"bundle": {
|
|
41
|
+
"patch": "./cordis.patch.yml"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
package/state.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-agent runtime state.
|
|
3
|
+
*
|
|
4
|
+
* Everything the plugin decides for a conversation lives here: the current
|
|
5
|
+
* level the plugin last applied, where that level came from (手动 / 自动), the
|
|
6
|
+
* judge's reason for this turn, the anti-flap counter and the failure counter.
|
|
7
|
+
* The UI reads the published snapshot instead of the agent internals.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** @typedef {'manual' | 'auto'} LevelSource */
|
|
11
|
+
|
|
12
|
+
const states = new WeakMap()
|
|
13
|
+
|
|
14
|
+
/** Latest snapshot per session id, so a dock widget can render without the Agent. */
|
|
15
|
+
export const published = new Map()
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* State of one agent, created on first use.
|
|
19
|
+
* @param {object} agent
|
|
20
|
+
* @param {{ enabled: boolean }} config
|
|
21
|
+
*/
|
|
22
|
+
export function stateOf(agent, config) {
|
|
23
|
+
let state = states.get(agent)
|
|
24
|
+
if (state === undefined) {
|
|
25
|
+
state = {
|
|
26
|
+
/** Master switch: false means the plugin never touches the level. */
|
|
27
|
+
auto: config.enabled,
|
|
28
|
+
/** True once the circuit breaker stopped automatic switching. */
|
|
29
|
+
tripped: false,
|
|
30
|
+
/** Level the plugin last applied, or null before the first judgement. */
|
|
31
|
+
level: null,
|
|
32
|
+
/** Who owns the current level. */
|
|
33
|
+
source: /** @type {LevelSource} */ ('manual'),
|
|
34
|
+
/** Raw judge answer plus what happened with it, shown in the UI. */
|
|
35
|
+
reason: '本轮还没有判断',
|
|
36
|
+
/** Number of user turns judged so far. */
|
|
37
|
+
judgedTurns: 0,
|
|
38
|
+
/** Consecutive judge failures. */
|
|
39
|
+
failures: 0,
|
|
40
|
+
/** judgedTurns value of the last level change; -Infinity allows the first one. */
|
|
41
|
+
lastChangeTurn: Number.NEGATIVE_INFINITY,
|
|
42
|
+
}
|
|
43
|
+
states.set(agent, state)
|
|
44
|
+
}
|
|
45
|
+
return state
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Freeze what the UI has to show for one turn.
|
|
50
|
+
* @param {object} agent
|
|
51
|
+
* @param {ReturnType<typeof stateOf>} state
|
|
52
|
+
*/
|
|
53
|
+
export function publish(agent, state) {
|
|
54
|
+
const id = agent?.session?.id ?? agent?.id
|
|
55
|
+
if (typeof id !== 'string') return
|
|
56
|
+
published.set(id, Object.freeze({
|
|
57
|
+
level: state.level,
|
|
58
|
+
source: state.source,
|
|
59
|
+
reason: state.reason,
|
|
60
|
+
auto: state.auto && !state.tripped,
|
|
61
|
+
tripped: state.tripped,
|
|
62
|
+
judgedTurns: state.judgedTurns,
|
|
63
|
+
failures: state.failures,
|
|
64
|
+
}))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Read the snapshot for a session.
|
|
69
|
+
* @param {string} sessionId
|
|
70
|
+
*/
|
|
71
|
+
export function snapshotOf(sessionId) {
|
|
72
|
+
return published.get(sessionId)
|
|
73
|
+
}
|