dsh-thinking-levels 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/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # dsh-thinking-levels
2
+
3
+ **Per-round thinking-level (`reasoning_effort`) control for [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness): five levels — `off` / `low` / `high` / `max` for manual control, plus an `auto` scheduler that keeps cheap tool rounds cheap and never starves heavy work.**
4
+
5
+ [中文文档](./README.zh.md) · English
6
+
7
+ In a multi-step tool chain, the model re-thinks before **every** tool call — and that thinking dominates the wall-clock time (a 50-step agent task can spend minutes reasoning between tools). `dsh-thinking-levels` plugs into the `agent/request` waterfall that dsh re-resolves for every step, and injects a thinking level into the next model request.
8
+
9
+ ## Levels
10
+
11
+ | Level | Meaning |
12
+ |---|---|
13
+ | `off` | thinking disabled (manual only — never auto-picked) |
14
+ | `low` | manual pick for simple chat tasks (cheap rounds stay cheap) |
15
+ | `high` | the official default effort |
16
+ | `max` | heavy work |
17
+ | `auto` | schedule per step from the recent tool-call history |
18
+
19
+ Wire-level facts (verified against the official DeepSeek docs and dsh's `llm-deepseek` adapter): `low` maps 1:1 on deepseek-v4-flash / v4-pro, while `medium` / `xhigh` collapse onto `high`. The adapter accepts `off | low | high | max` and rejects anything else with `UNSUPPORTED_REASONING_EFFORT` — this plugin validates the configured level before injecting, fail-loud.
20
+
21
+ ## Auto scheduler
22
+
23
+ The hub is `high` (the official default). `auto` schedules between `low` / `high` / `max`; it never picks `off`, and it always resolves to a wire level before injecting.
24
+
25
+ | Recent tool calls | Level |
26
+ |---|---|
27
+ | none (fresh prompt, pure chat) | `low` |
28
+ | ≥75% simple tools, small args, downgrades allowed | `low` |
29
+ | mixed / heavy tools | `high` |
30
+ | very heavy payloads, upgrades allowed | `max` |
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ # 1. install the plugin into a profile from GitHub (web shown; any profile works)
36
+ # (the web profile is a pnpm workspace root, so -w is required)
37
+ dsh plugin --profile web add https://github.com/drscrewdriver/dsh-thinking-levels.git -w
38
+ # local-path alternative (no network needed, no -w outside workspace roots):
39
+ # dsh plugin --profile web add /absolute/path/to/dsh-thinking-levels
40
+
41
+ # 2. restart dsh web
42
+ # (a running instance does not hot-load new bundle layers)
43
+ dsh web
44
+ ```
45
+
46
+ Manual `link:` registration (alternative to `dsh plugin add`):
47
+
48
+ ```bash
49
+ # ~/.dsh/profiles/web/package.json dependencies:
50
+ # "dsh-thinking-levels": "link:<absolute path to dsh-thinking-levels>"
51
+ # ~/.dsh/profiles/web/cordis.patch.yml:
52
+ # - insert:
53
+ # - id: thinking-levels
54
+ # name: dsh-thinking-levels
55
+ cd ~/.dsh/profiles/web && pnpm install && dsh web
56
+ ```
57
+
58
+ ## Configuration
59
+
60
+ Two surfaces share one schema:
61
+
62
+ - **Assembly** — the plugin row's `config:` in the profile composition (e.g. `cordis.yml`):
63
+ ```yaml
64
+ config:
65
+ level: high # off | low | high | max | auto
66
+ allowDowngrade: false # forbid the scheduler dropping below `high`
67
+ allowUpgrade: false # forbid the scheduler lifting to `max`
68
+ ```
69
+ - **Runtime** — the dsh-settings namespace `thinking-levels` (`level`, `allowDowngrade`, `allowUpgrade`, `enabled`): changes apply to the next model request, no restart needed.
70
+
71
+ Defaults: `{ enabled: true, level: 'auto', allowDowngrade: true, allowUpgrade: false }`.
72
+
73
+ ## Development
74
+
75
+ ```bash
76
+ npm run lint # eslint (typescript-eslint flat config)
77
+ npm run typecheck # tsc --noEmit
78
+ npm test # vitest — 21 tests
79
+ ```
80
+
81
+ Test coverage: level policy (manual pass-through, auto scheduler, validation, simple-tool boundary), session-event parsing (guards, window cap, malformed records), and the config schema (defaults lockstep, out-of-band rejection).
82
+
83
+ ## License
84
+
85
+ MIT
package/README.zh.md ADDED
@@ -0,0 +1,85 @@
1
+ # dsh-thinking-levels
2
+
3
+ **为 [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 提供按轮次的思考档位(`reasoning_effort`)控制:`off` / `low` / `high` / `max` 四档手动固定,外加 `auto` 自动调度——让廉价工具轮次保持廉价,同时绝不让重任务缺少推理。**
4
+
5
+ [中文文档](./README.zh.md) · English
6
+
7
+ 在多步工具链任务中,模型在**每一次工具调用前**都会重新思考——而这个思考过程占据了绝大部分墙钟时间(一个 50 步的 agent 任务可能在工具之间花费数分钟思考)。`dsh-thinking-levels` 接入 dsh 每一步都会重新解析的 `agent/request` waterfall,向下一次模型请求注入思考档位。
8
+
9
+ ## 档位
10
+
11
+ | 档位 | 含义 |
12
+ |---|---|
13
+ | `off` | 关闭思考(仅手动选择,自动调度永不选用) |
14
+ | `low` | 手动低档,对应简单对话任务(廉价轮次保持廉价) |
15
+ | `high` | 官方默认档位 |
16
+ | `max` | 重任务 |
17
+ | `auto` | 依据最近的工具调用历史逐轮调度 |
18
+
19
+ 线缆档位事实(对照官方 DeepSeek 文档与 dsh `llm-deepseek` 适配器核实):deepseek-v4-flash / v4-pro 上 `low` 1:1 生效,`medium` / `xhigh` 折叠到 `high`。适配器只接受 `off | low | high | max`,其他值抛 `UNSUPPORTED_REASONING_EFFORT`——本插件在注入前 fail-loud 校验配置档位。
20
+
21
+ ## 自动调度
22
+
23
+ 中枢为 `high`(官方默认)。`auto` 只在 `low` / `high` / `max` 之间调度;永不选 `off`,且注入前必然解析为具体线缆档位。
24
+
25
+ | 最近的工具调用 | 档位 |
26
+ |---|---|
27
+ | 无(全新提示,纯对话) | `low` |
28
+ | ≥75% 简单工具、小载荷、允许降档 | `low` |
29
+ | 混合 / 重工具 | `high` |
30
+ | 超大载荷、允许升级 | `max` |
31
+
32
+ ## 安装
33
+
34
+ ```bash
35
+ # 1. 从 GitHub 把插件装进某个 profile(以 web 为例,任意 profile 均可)
36
+ # (web profile 是 pnpm workspace root,必须带 -w)
37
+ dsh plugin --profile web add https://github.com/drscrewdriver/dsh-thinking-levels.git -w
38
+ # 本地路径备选(无需网络;非 workspace root 目录无需 -w):
39
+ # dsh plugin --profile web add /dsh-thinking-levels 的绝对路径/
40
+
41
+ # 2. 重启 dsh web
42
+ # (运行中的实例不会热加载新的 bundle 层)
43
+ dsh web
44
+ ```
45
+
46
+ 手动 `link:` 注册(`dsh plugin add` 的备选方式):
47
+
48
+ ```bash
49
+ # ~/.dsh/profiles/web/package.json dependencies 增加:
50
+ # "dsh-thinking-levels": "link:<dsh-thinking-levels 的绝对路径>"
51
+ # ~/.dsh/profiles/web/cordis.patch.yml:
52
+ # - insert:
53
+ # - id: thinking-levels
54
+ # name: dsh-thinking-levels
55
+ cd ~/.dsh/profiles/web && pnpm install && dsh web
56
+ ```
57
+
58
+ ## 配置
59
+
60
+ 两个配置面共用同一套 schema:
61
+
62
+ - **装配层** — profile 组合中插件行的 `config:`(如 `cordis.yml`):
63
+ ```yaml
64
+ config:
65
+ level: high # off | low | high | max | auto
66
+ allowDowngrade: false # 禁止调度器降到 `high` 以下
67
+ allowUpgrade: false # 禁止调度器升到 `max`
68
+ ```
69
+ - **运行时** — dsh-settings 命名空间 `thinking-levels`(`level`、`allowDowngrade`、`allowUpgrade`、`enabled`):改动对下一次模型请求生效,无需重启。
70
+
71
+ 默认值:`{ enabled: true, level: 'auto', allowDowngrade: true, allowUpgrade: false }`。
72
+
73
+ ## 开发
74
+
75
+ ```bash
76
+ npm run lint # eslint(typescript-eslint flat config)
77
+ npm run typecheck # tsc --noEmit
78
+ npm test # vitest — 21 个测试
79
+ ```
80
+
81
+ 测试覆盖:档位策略(手动透传、auto 调度、档位校验、简单工具边界)、会话事件解析(守卫、窗口截断、畸形记录)、配置 schema(默认值同步、越界拒绝)。
82
+
83
+ ## 许可
84
+
85
+ MIT
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: dsh-thinking-levels
3
+ name: dsh-thinking-levels
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "dsh-thinking-levels",
3
+ "version": "0.1.0",
4
+ "description": "DSH host plugin: thinking-level (reasoning_effort) control for dsh — auto-adjust per tool round, with optional manual lock and per-tool timing telemetry.",
5
+ "repository": "git+https://github.com/drscrewdriver/dsh-thinking-levels.git",
6
+ "type": "module",
7
+ "files": [
8
+ "src",
9
+ "cordis.patch.yml"
10
+ ],
11
+ "main": "src/index.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./src/index.ts",
15
+ "default": "./src/index.ts"
16
+ },
17
+ "./thinking-level": {
18
+ "types": "./src/thinking-level.ts",
19
+ "default": "./src/thinking-level.ts"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "peerDependencies": {
27
+ "@deepseek-ai/cordis": "^4.0.1",
28
+ "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
29
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.6"
30
+ },
31
+ "dependencies": {
32
+ "@deepseek-ai/schemastery": "^3.18.0"
33
+ },
34
+ "devDependencies": {
35
+ "@deepseek-ai/cordis": "^4.0.1",
36
+ "@deepseek-ai/dsh-agent": "^0.1.0-rc.6",
37
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.6",
38
+ "@eslint/js": "^10.0.1",
39
+ "@types/node": "^24.0.0",
40
+ "eslint": "^10.8.1",
41
+ "typescript": "^5.6.0",
42
+ "typescript-eslint": "^8.67.0",
43
+ "vitest": "^3.0.0"
44
+ },
45
+ "scripts": {
46
+ "typecheck": "tsc --noEmit",
47
+ "lint": "eslint src tests",
48
+ "test": "vitest run"
49
+ },
50
+ "license": "MIT",
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": "./cordis.patch.yml"
54
+ }
55
+ }
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * dsh-thinking-levels host plugin: injects a user-selected or auto-scheduled
3
+ * `reasoning_effort` into every `agent/request` waterfall (levels: off / low /
4
+ * high / max / auto), and records per-tool wall-clock durations for telemetry.
5
+ *
6
+ * Extension points used (verified in deepseek-ai/deepseek-harness):
7
+ * - `agent/request` waterfall (packages/core/agent-loop/src/agent.ts
8
+ * buildRequest): each listener may return a modified GenerateOptions for
9
+ * the next listener — the sanctioned way to adjust request config.
10
+ * - `session.events` (agent.session) carries the step's tool/call records.
11
+ * - settings service namespace (like DSH-better-sidebar's PrefsSchema) for
12
+ * the user toggles.
13
+ */
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import z from '@deepseek-ai/schemastery'
16
+ import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings'
17
+ import { assertEffortId, decideEffort, type EffortId } from './thinking-level.ts'
18
+ import { recentToolCalls } from './session-events.ts'
19
+
20
+ /** Plugin settings. */
21
+ export interface ThinkingLevelsConfig {
22
+ enabled: boolean
23
+ /** User-selected level: off / low / high / max fix the wire level; `auto` schedules per step. */
24
+ level: EffortId
25
+ /** Scheduler preference: allow dropping below the `high` hub. */
26
+ allowDowngrade: boolean
27
+ /** Scheduler preference: allow lifting above the `high` hub to `max`. */
28
+ allowUpgrade: boolean
29
+ }
30
+
31
+ /**
32
+ * Composition-entry schema: what a dsh profile may configure at assembly
33
+ * time (cordis.yml `config:` of the plugin row). The settings namespace
34
+ * reuses the same schema, so a value admitted at one surface is admitted
35
+ * at the other.
36
+ */
37
+ export const Config: z<ThinkingLevelsConfig> = z.object({
38
+ enabled: z.boolean().default(true),
39
+ level: z.union(['off', 'low', 'high', 'max', 'auto']).default('auto'),
40
+ allowDowngrade: z.boolean().default(true),
41
+ allowUpgrade: z.boolean().default(false),
42
+ })
43
+
44
+ /** Settings defaults, kept in lockstep with the schema defaults above. */
45
+ export const DEFAULT_CONFIG: ThinkingLevelsConfig = {
46
+ enabled: true,
47
+ level: 'auto',
48
+ allowDowngrade: true,
49
+ allowUpgrade: false,
50
+ }
51
+
52
+ /** Runtime-adjustable settings namespace: level + scheduler toggles. */
53
+ export const THINKING_LEVELS_SETTINGS_NAMESPACE = settingsNamespace('thinking-levels')
54
+
55
+ const TOOL_AGE_LIMIT_MS = 10 * 60 * 1000
56
+
57
+ /**
58
+ * Plugin body.
59
+ * @param ctx - host context carrying the agent-event dispatch.
60
+ * @param config - resolved plugin configuration.
61
+ */
62
+ export function apply(ctx: Context, config: ThinkingLevelsConfig = DEFAULT_CONFIG): void {
63
+ if (!config.enabled) return
64
+ // Fail-loud: a stray config value (e.g. `medium` from an old profile) must
65
+ // not ride through into the model request, where dsh throws
66
+ // UNSUPPORTED_REASONING_EFFORT per request.
67
+ assertEffortId(config.level, 'dsh-thinking-levels config.level')
68
+
69
+ // Runtime-adjustable configuration source: the composition entry is the
70
+ // base; the settings namespace layers on top and `current()` always reads
71
+ // the active section (official dsh settings integration pattern).
72
+ let current: () => ThinkingLevelsConfig = () => config
73
+ installSettingsSection(ctx, THINKING_LEVELS_SETTINGS_NAMESPACE, Config, config, {
74
+ setSource: (source) => {
75
+ current = source
76
+ },
77
+ // The decision is read per request, so a committed change needs no
78
+ // re-registration.
79
+ onChange: () => {},
80
+ })
81
+
82
+ // Inject the level decision into every model request of a step.
83
+ // The 'agent/request' event key is augmented onto cordis Events by the
84
+ // dsh-agent runtime's generated scope types; the npm package does not
85
+ // re-export that augmentation, so the emitter is widened at the boundary.
86
+ const on = ctx.on as unknown as (
87
+ event: string,
88
+ handler: (payload: Record<string, unknown>, next: () => unknown) => unknown | Promise<unknown>,
89
+ ) => void
90
+ on('agent/request', async (payload, next) => {
91
+ const seed = await next() as { reasoningEffort?: unknown }
92
+ const cfg = current()
93
+ // `enabled` may flip at runtime through the settings namespace.
94
+ if (!cfg.enabled) return seed
95
+ const calls = recentToolCalls(payload.agent)
96
+ const level = decideEffort({
97
+ recentCalls: calls,
98
+ selected: cfg.level,
99
+ allowDowngrade: cfg.allowDowngrade,
100
+ allowUpgrade: cfg.allowUpgrade,
101
+ })
102
+ // Summary-only log: individual tool names/arg sizes are workflow metadata
103
+ // that need not land in the host log; count and decision suffice.
104
+ ctx.logger?.info?.('[thinking-levels] agent/request: selected=%s calls=%d => level=%s', cfg.level, calls.length, level)
105
+ return { ...seed, reasoningEffort: level }
106
+ })
107
+
108
+ // Per-tool wall-clock telemetry: log tool/call -> tool/result durations.
109
+ // Same boundary widening as above (agent/tool is a generated scope event).
110
+ const started = new Map<string, number>()
111
+ // A tool that never emits `end` (crash, interruption) must not leak its
112
+ // entry forever; sweep stale ones lazily on every new `start`.
113
+ const pruneStale = (now: number): void => {
114
+ for (const [callId, at] of started) {
115
+ if (now - at > TOOL_AGE_LIMIT_MS) started.delete(callId)
116
+ }
117
+ }
118
+ on('agent/tool', async (payload) => {
119
+ const callId = payload.callId
120
+ if (typeof callId !== 'string') return
121
+ if (payload.phase === 'start') {
122
+ const now = Date.now()
123
+ pruneStale(now)
124
+ started.set(callId, now)
125
+ } else if (payload.phase === 'end') {
126
+ const from = started.get(callId)
127
+ started.delete(callId)
128
+ if (from !== undefined) {
129
+ const ms = Date.now() - from
130
+ ctx.logger?.info?.('[thinking-levels] tool %s took %dms', callId, ms)
131
+ }
132
+ }
133
+ })
134
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Session tool-call sampling for dsh-thinking-levels.
3
+ *
4
+ * Pulled out of the plugin body so the extraction logic — the part most
5
+ * exposed to dsh event-shape drift — is unit-testable in isolation, with
6
+ * explicit guards instead of naked type assertions. If a future dsh version
7
+ * reshapes `session.events`, the failure shows up in the tests, not as a
8
+ * silently wrong effort decision.
9
+ */
10
+
11
+ import type { ToolCallSample } from './thinking-level.ts'
12
+
13
+ /** How many recent tool calls to sample for one decision. */
14
+ export const TOOL_SAMPLE_WINDOW = 8
15
+
16
+ function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === 'object' && value !== null
18
+ }
19
+
20
+ /** Guard: one session event shaped like a tool/call record. */
21
+ function isToolCallEvent(event: unknown): event is { data: Record<string, unknown> } {
22
+ if (!isRecord(event) || event.type !== 'tool/call') return false
23
+ return isRecord(event.data)
24
+ }
25
+
26
+ /** Approximate argument size in characters (payload heft); unknown shapes read as 0. */
27
+ function argsSizeOf(argumentsValue: unknown): number {
28
+ return typeof argumentsValue === 'string' ? argumentsValue.length : 0
29
+ }
30
+
31
+ /**
32
+ * Recent tool calls of a session's current step, oldest first.
33
+ * Non-tool events and malformed records are skipped; at most
34
+ * {@link TOOL_SAMPLE_WINDOW} samples are returned.
35
+ *
36
+ * @param agent - the `payload.agent` value from the `agent/request` waterfall.
37
+ * @returns the sampled tool calls, or `[]` for a fresh prompt / unknown shape.
38
+ */
39
+ export function recentToolCalls(agent: unknown): ToolCallSample[] {
40
+ if (!isRecord(agent)) return []
41
+ const session = agent.session
42
+ if (!isRecord(session) || !Array.isArray(session.events)) return []
43
+
44
+ const samples: ToolCallSample[] = []
45
+ for (let index = session.events.length - 1; index >= 0 && samples.length < TOOL_SAMPLE_WINDOW; index -= 1) {
46
+ const event = session.events[index]
47
+ if (!isToolCallEvent(event)) continue
48
+ const data = event.data
49
+ const name = typeof data.name === 'string' && data.name.length > 0 ? data.name : 'tool'
50
+ samples.push({ name, argsSize: argsSizeOf(data.arguments) })
51
+ }
52
+ return samples.reverse()
53
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Pure thinking-level decision for the dsh-thinking-levels plugin.
3
+ *
4
+ * The measured bottleneck of tool calls in dsh is the model's THINKING phase
5
+ * (~90% of the wall-clock time for simple tasks), not the tool execution
6
+ * itself. DeepSeek's API exposes `reasoning_effort` in three wire levels
7
+ * (low / high / max, plus `off` disables thinking; low shipped 2026-08-13 and
8
+ * maps 1:1 per the official docs — medium/xhigh collapse onto high).
9
+ *
10
+ * The plugin offers FIVE user-facing levels:
11
+ * - `off` : thinking disabled (manual only — never auto-picked).
12
+ * - `low` : manual fix for simple chat tasks (cheap rounds stay cheap).
13
+ * - `high` : manual fix, the official default effort.
14
+ * - `max` : manual fix for heavy work.
15
+ * - `auto` : schedule per step from the recent tool-call history, between
16
+ * `low` / `high` / `max` (never `off`, never `auto` itself).
17
+ *
18
+ * Kept dependency-free (pure inputs -> output) so the policy is unit-testable
19
+ * in isolation; the plugin host feeds it the live session's recent calls.
20
+ */
21
+
22
+ /** The five user-facing thinking levels; the wire levels dsh forwards to DeepSeek plus the scheduler sentinel. */
23
+ export type EffortId = 'off' | 'low' | 'high' | 'max' | 'auto'
24
+
25
+ /** Wire levels the auto scheduler may pick (never `off`, never `auto`). */
26
+ export type AutoEffort = Exclude<EffortId, 'auto' | 'off'>
27
+
28
+ /** Runtime guard: is this a level the plugin understands? */
29
+ export function isEffortId(value: unknown): value is EffortId {
30
+ return value === 'off' || value === 'low' || value === 'high' || value === 'max' || value === 'auto'
31
+ }
32
+
33
+ /**
34
+ * Fail-loud config validation: reject an out-of-band level (e.g. a stray
35
+ * `medium` from an old profile) instead of silently injecting it into the
36
+ * model request, where dsh would throw `UNSUPPORTED_REASONING_EFFORT`.
37
+ */
38
+ export function assertEffortId(value: unknown, where: string): asserts value is EffortId {
39
+ if (!isEffortId(value)) {
40
+ throw new TypeError(`${where}: invalid thinking level ${JSON.stringify(value)} (expected off | low | high | max | auto)`)
41
+ }
42
+ }
43
+
44
+ /** One observed tool call of the current/last step. */
45
+ export interface ToolCallSample {
46
+ /** Tool name, e.g. 'bash', 'fs_write', 'web_search', 'mcp__...'. */
47
+ name: string
48
+ /** Approximate argument size in characters (payload heft). */
49
+ argsSize: number
50
+ }
51
+
52
+ /** Everything the policy needs to decide one request's level. */
53
+ export interface EffortDecisionInput {
54
+ /** Recent tool calls of the step (oldest first); empty for a fresh prompt. */
55
+ recentCalls: readonly ToolCallSample[]
56
+ /** The user-selected level: a fixed wire level, or `auto` for scheduling. */
57
+ selected: EffortId
58
+ /** User preference: allow the scheduler to drop below the hub (`high`). */
59
+ allowDowngrade: boolean
60
+ /** User preference: allow the scheduler to lift above the hub to `max`. */
61
+ allowUpgrade: boolean
62
+ }
63
+
64
+ /** Deterministic tool names that are cheap to reason about (word-boundary anchored). */
65
+ const SIMPLE_TOOL_RE = /^(?:fs|bash|terminal|code|text|todo|job|skill|read|list|search|write|grep|glob|edit|ls|cat|rm|mv|cp|touch|mkdir|pwd|head|tail)(?:_|$)/i
66
+
67
+ /** Hefty payloads signal non-trivial work no matter the tool name. */
68
+ const HEAVY_ARGS = 800
69
+
70
+ /** Count how many of the recent calls look cheap-and-deterministic. */
71
+ function simpleRatio(calls: readonly ToolCallSample[]): number {
72
+ if (calls.length === 0) return 1
73
+ const simple = calls.filter(call =>
74
+ SIMPLE_TOOL_RE.test(call.name) && call.argsSize < HEAVY_ARGS,
75
+ ).length
76
+ return simple / calls.length
77
+ }
78
+
79
+ /**
80
+ * Auto schedule: map a recent tool-call history to the wire level the NEXT
81
+ * model request of that step should use.
82
+ *
83
+ * Hub is `high` (the official default). Rules:
84
+ * - No tool calls yet (fresh prompt, pure chat) -> `low` (simple chat tasks).
85
+ * - All/mostly simple tools -> `low` (when downgrades are allowed).
86
+ * - Mixed or heavy tools -> `high` (the hub).
87
+ * - Very heavy context (huge args) -> `max` (when upgrades are allowed).
88
+ *
89
+ * @param calls - recent tool calls of the step.
90
+ * @param allowDowngrade - may drop below `high`.
91
+ * @param allowUpgrade - may lift above `high`.
92
+ * @returns a wire level; never `off` (off is manual-only) and never `auto`.
93
+ */
94
+ function scheduleEffort(
95
+ calls: readonly ToolCallSample[],
96
+ allowDowngrade: boolean,
97
+ allowUpgrade: boolean,
98
+ ): AutoEffort {
99
+ if (calls.length === 0) return allowDowngrade ? 'low' : 'high'
100
+
101
+ const ratio = simpleRatio(calls)
102
+ const heaviest = calls.reduce((max, call) => Math.max(max, call.argsSize), 0)
103
+
104
+ if (ratio >= 0.75 && allowDowngrade) return 'low'
105
+ if (heaviest >= HEAVY_ARGS * 4 && allowUpgrade) return 'max'
106
+ return 'high'
107
+ }
108
+
109
+ /**
110
+ * Map the user's selected level to the level injected into the next
111
+ * `agent/request`. Manual levels (off / low / high / max) pass through
112
+ * unchanged — `low` is the manual pick for simple chat tasks. `auto`
113
+ * delegates to the tool-history scheduler.
114
+ *
115
+ * @param input - recent calls, the selected level and the user's toggles.
116
+ * @returns The level to inject; `auto` is resolved before returning.
117
+ */
118
+ export function decideEffort(input: EffortDecisionInput): EffortId {
119
+ const { recentCalls, selected, allowDowngrade, allowUpgrade } = input
120
+ if (selected !== 'auto') return selected
121
+ return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade)
122
+ }
123
+
124
+ /** Wall-clock delta of one tool call, for the timing telemetry. */
125
+ export function toolDurationMs(startedAt: number, finishedAt: number): number {
126
+ return Math.max(0, finishedAt - startedAt)
127
+ }