dsh-thinking-levels 0.4.1 → 0.7.0-beta.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.
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Auto-flag sync (check branch): bridge from dsh-thinking-levels to the
3
+ * OFFICIAL llm-pi-ai compat surface.
4
+ *
5
+ * CHECK-BRANCH REPLACEMENT: the previous bridge maintained the
6
+ * `llm-openai-completions` takeover list of the dsh-llm-openai-completions
7
+ * adapter plugin (the short-circuit route). Since dsh v0.1.0-rc.8 the official
8
+ * `compat.supportsDeveloperRole` flag (commit 884f7b9c41) fixes the developer
9
+ * role 400 declaratively, so the short-circuit list is no longer needed: the
10
+ * sync now writes the flag into the OFFICIAL `llm-pi-ai` namespace instead.
11
+ *
12
+ * Storage pattern learned from hytime/dsh-thinking-effort's host side
13
+ * (src/host/settings.ts): read the live section → pure transform with
14
+ * immutable clones → `settings.update('llm-pi-ai', { providers })` whole-section
15
+ * writeback, so dsh's `llm-pi-ai` schema validator (assertServiceable) gates
16
+ * the write where it is WRITTEN (settings-rejected names route and model)
17
+ * instead of storing something the reader cannot serve. The flag is written at
18
+ * the ROUTE level (`providers.<route>.compat`) — the official inheritance chain
19
+ * (model → provider → catalog → protocol) means a model-level explicit value
20
+ * still wins, and explicit values are never clobbered by this sync.
21
+ *
22
+ * Identification is unchanged: a provider that (a) targets a custom
23
+ * openai-completions gateway and (b) declares thinking (a reasoningEfforts
24
+ * table) is exactly the route the short-circuit used to take over. Pure
25
+ * functions here are unit-tested; the host plugin wires them to the settings
26
+ * service.
27
+ *
28
+ * Deliberately soft-coupled: nothing here value-imports dsh-settings. If the
29
+ * installed dsh predates rc.8 the schema rejects the unknown field and the
30
+ * host catches and logs the rejection — no error, no log spam.
31
+ * @module dsh-thinking-levels/takeover-sync
32
+ */
33
+ /** The settings namespace holding the provider/model configs (llm-pi-ai). */
34
+ export const PI_AI_NAMESPACE = 'llm-pi-ai';
35
+ /** The settings namespace of the retired short-circuit adapter, still READ to gate posture. */
36
+ export const TAKEOVER_NAMESPACE = 'llm-openai-completions';
37
+ /** Hosts that are NOT a custom gateway (official OpenAI-compatible endpoints). */
38
+ const OFFICIAL_HOST_RE = /(?:^|\.)(?:deepseek\.com|openai\.com|openrouter\.ai|anthropic\.com|googleapis\.com|ai\.google\.dev|mistral\.ai|x\.ai)$/i;
39
+ /** Whether a value looks like a declared reasoningEfforts table. */
40
+ function isEffortsTable(value) {
41
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
42
+ }
43
+ /**
44
+ * Whether a provider profile targets a CUSTOM openai-completions gateway:
45
+ * explicit `api: openai-completions`, or a baseURL that is not an official
46
+ * host. Catalog routes without either (e.g. xiaomi via pi-ai discovery) are
47
+ * not custom and are left alone.
48
+ * @param profile - the provider profile slice.
49
+ * @returns true when the route is a custom openai-completions gateway.
50
+ */
51
+ export function isCustomOpenAiGateway(profile) {
52
+ if (profile === undefined)
53
+ return false;
54
+ if (profile.api === 'openai-completions')
55
+ return true;
56
+ const baseURL = profile.baseURL;
57
+ if (typeof baseURL !== 'string' || baseURL.length === 0)
58
+ return false;
59
+ try {
60
+ return !OFFICIAL_HOST_RE.test(new URL(baseURL).hostname);
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ /** The model rows a profile declares, from models[] then modelOverrides (effort's modelRows pattern). */
67
+ function modelRows(profile) {
68
+ const rows = [];
69
+ if (Array.isArray(profile.models)) {
70
+ rows.push(...profile.models.filter((row) => typeof row === 'object' && row !== null));
71
+ }
72
+ if (typeof profile.modelOverrides === 'object' && profile.modelOverrides !== null && !Array.isArray(profile.modelOverrides)) {
73
+ rows.push(...Object.values(profile.modelOverrides).filter((row) => typeof row === 'object' && row !== null));
74
+ }
75
+ return rows;
76
+ }
77
+ /**
78
+ * Whether a provider declares thinking: at least one model row carries a
79
+ * reasoningEfforts table (thinking on). `false` (thinking off) and absent
80
+ * both mean no thinking.
81
+ * @param profile - the provider profile slice.
82
+ * @returns true when any model declares a reasoningEfforts table.
83
+ */
84
+ export function declaresThinking(profile) {
85
+ if (profile === undefined)
86
+ return false;
87
+ return modelRows(profile).some((row) => isEffortsTable(row.reasoningEfforts));
88
+ }
89
+ /**
90
+ * Identify the providers that should be taken over by the openai-completions
91
+ * adapter: custom gateway AND thinking declared. Order is stable (the section's
92
+ * own provider order).
93
+ * @param section - the live llm-pi-ai section.
94
+ * @returns the provider ids to add to the takeover list.
95
+ */
96
+ export function identifyTakeoverProviders(section) {
97
+ const providers = section?.providers;
98
+ if (typeof providers !== 'object' || providers === null)
99
+ return [];
100
+ return Object.entries(providers)
101
+ .filter(([, profile]) => isCustomOpenAiGateway(profile) && declaresThinking(profile))
102
+ .map(([id]) => id);
103
+ }
104
+ /** A row's own `compat` record, when it declares one. */
105
+ function ownCompat(row) {
106
+ return typeof row.compat === 'object' && row.compat !== null && !Array.isArray(row.compat)
107
+ ? row.compat
108
+ : undefined;
109
+ }
110
+ /** Whether the ROW ITSELF declares `supportsReasoningEffort: true` (route-level does not count here). */
111
+ function rowEffortCapable(row) {
112
+ return ownCompat(row)?.['supportsReasoningEffort'] === true;
113
+ }
114
+ /** The row's own `thinkingFormat`, when explicitly declared. */
115
+ function rowThinkingFormat(row) {
116
+ return ownCompat(row)?.['thinkingFormat'];
117
+ }
118
+ /**
119
+ * Rewrite one model row's compat for the toggle-thinking fix. Returns the row
120
+ * by reference when nothing to change.
121
+ */
122
+ function withToggleThinkingFormat(row) {
123
+ // Only TOGGLE-STYLE thinking models (a reasoningEfforts table but no
124
+ // row-level effort support) need `thinkingFormat: qwen-chat-template`:
125
+ // pi-ai's default `openai` format sends reasoning_effort — which an early
126
+ // vLLM thinking model rejects or ignores — and the plain `qwen` format's
127
+ // TOP-LEVEL enable_thinking is silently dropped by bare vLLM servers, whose
128
+ // Qwen3 templates only honor chat_template_kwargs.enable_thinking. An
129
+ // explicit thinkingFormat is respected and never clobbered.
130
+ if (!isEffortsTable(row.reasoningEfforts))
131
+ return row;
132
+ if (rowEffortCapable(row))
133
+ return row;
134
+ if (rowThinkingFormat(row) !== undefined)
135
+ return row;
136
+ return { ...row, compat: { ...ownCompat(row), thinkingFormat: 'qwen-chat-template' } };
137
+ }
138
+ /**
139
+ * Compute the llm-pi-ai section with the OFFICIAL compat fixes written for
140
+ * every identified provider (custom openai-completions gateway AND thinking
141
+ * declared):
142
+ *
143
+ * 1. ROUTE level: `compat.supportsDeveloperRole: false` when the route does
144
+ * not carry an explicit value — the system prompt goes out as `system`
145
+ * (fixes the Unexpected message role 400 on vLLM/SGLang gateways).
146
+ * 2. MODEL level: `compat.thinkingFormat: 'qwen-chat-template'` on TOGGLE-STYLE thinking
147
+ * model rows (a reasoningEfforts table, no row-level
148
+ * `supportsReasoningEffort: true`, no explicit thinkingFormat) — pi-ai
149
+ * then sends the `enable_thinking` flag these early vLLM thinking models
150
+ * need, instead of a reasoning_effort they do not support. Effort-capable
151
+ * rows are untouched (their reasoning_effort wire needs the default/openai
152
+ * or declared format), and the route level is deliberately NOT written —
153
+ * a route-wide thinkingFormat would flip effort models onto
154
+ * enable_thinking too.
155
+ *
156
+ * Semantics (learned from dsh-thinking-effort's storage handling):
157
+ * - An EXPLICIT value on any layer is respected and left alone; only ABSENT
158
+ * fields are filled. This keeps the sync idempotent and never overrides
159
+ * user intent.
160
+ * - Immutable: unchanged profiles/rows and the unchanged section are returned
161
+ * by reference, so the host can skip the write on identity.
162
+ * @param section - the live llm-pi-ai section.
163
+ * @returns the next section, or the previous value (identity) when no change.
164
+ */
165
+ export function withOfficialCompatFixes(section) {
166
+ const providers = section?.providers;
167
+ if (typeof providers !== 'object' || providers === null)
168
+ return section;
169
+ let nextProviders;
170
+ for (const [id, profile] of Object.entries(providers)) {
171
+ if (!isCustomOpenAiGateway(profile) || !declaresThinking(profile))
172
+ continue;
173
+ let nextProfile = profile;
174
+ // Route-level developer-role flag (absent only).
175
+ if (profile.compat?.['supportsDeveloperRole'] === undefined) {
176
+ nextProfile = {
177
+ ...nextProfile,
178
+ compat: { ...(typeof nextProfile.compat === 'object' && nextProfile.compat !== null ? nextProfile.compat : {}), supportsDeveloperRole: false },
179
+ };
180
+ }
181
+ // Model-level toggle-thinking format (models[] rows).
182
+ if (Array.isArray(profile.models)) {
183
+ let nextModels;
184
+ profile.models.forEach((row, index) => {
185
+ if (typeof row !== 'object' || row === null)
186
+ return;
187
+ const fixed = withToggleThinkingFormat(row);
188
+ if (fixed !== row) {
189
+ nextModels ??= [...profile.models];
190
+ nextModels[index] = fixed;
191
+ }
192
+ });
193
+ if (nextModels !== undefined)
194
+ nextProfile = { ...nextProfile, models: nextModels };
195
+ }
196
+ // Model-level toggle-thinking format (modelOverrides entries).
197
+ if (typeof profile.modelOverrides === 'object' && profile.modelOverrides !== null && !Array.isArray(profile.modelOverrides)) {
198
+ let nextOverrides;
199
+ for (const [modelId, row] of Object.entries(profile.modelOverrides)) {
200
+ if (typeof row !== 'object' || row === null)
201
+ continue;
202
+ const fixed = withToggleThinkingFormat(row);
203
+ if (fixed !== row) {
204
+ nextOverrides ??= { ...profile.modelOverrides };
205
+ nextOverrides[modelId] = fixed;
206
+ }
207
+ }
208
+ if (nextOverrides !== undefined)
209
+ nextProfile = { ...nextProfile, modelOverrides: nextOverrides };
210
+ }
211
+ if (nextProfile !== profile) {
212
+ nextProviders ??= { ...providers };
213
+ nextProviders[id] = nextProfile;
214
+ }
215
+ }
216
+ return nextProviders === undefined ? section : { ...section, providers: nextProviders };
217
+ }
218
+ /**
219
+ * The providers the openai-completions adapter is currently set up to take
220
+ * over, from the live `llm-openai-completions` settings namespace. Used to
221
+ * gate thinking-levels' own behavior: a route OUTSIDE the takeover list is
222
+ * served by pi-ai with its native reasoning semantics (off/high visible,
223
+ * pi-ai validates and serializes the effort) and must not be folded into an
224
+ * Off/On toggle or have efforts injected by this plugin.
225
+ * @param section - the live llm-openai-completions section, if registered.
226
+ * @returns the provider ids the adapter will serve, or `null` when the
227
+ * namespace is unregistered (adapter plugin absent).
228
+ */
229
+ export function takeoverProvidersOf(section) {
230
+ if (section === undefined)
231
+ return null;
232
+ if (section.enabled !== true)
233
+ return [];
234
+ if (!Array.isArray(section.providers))
235
+ return [];
236
+ return section.providers.filter((id) => typeof id === 'string');
237
+ }
@@ -3,30 +3,44 @@
3
3
  *
4
4
  * The measured bottleneck of tool calls in dsh is the model's THINKING phase
5
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).
6
+ * itself. DeepSeek's API exposes `reasoning_effort` in wire levels
7
+ * (off / low / high / max; low shipped 2026-08-13 in dsh rc.7 — rc.6 and
8
+ * older adapters only accept off / high / max).
9
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).
10
+ * The plugin offers EIGHT standard levels aligned with dsh-thinking-effort's
11
+ * level set, plus the scheduler sentinel:
12
+ * - `off` : thinking disabled (manual only — never auto-picked).
13
+ * - `on` : thinking enabled at the model's default strength. Toggle-only
14
+ * models (Qwen3.6-style) surface Off/On; `on` lifts to the
15
+ * advertised `high` (or the highest thinking level the model
16
+ * takes) instead of an exact wire level.
17
+ * - `minimal` / `low` / `medium` / `high` / `xhigh` / `max` : strength
18
+ * gradients. Each maps to a wire value via the model's `reasoningEfforts`
19
+ * table (customizable per model — e.g. `high` → `ultra`); levels the model
20
+ * does not advertise are clamped to its highest thinking level or stripped.
21
+ * - `auto` : schedule per step from the recent tool-call history, between
22
+ * `low` / `high` / `max` (never `off`, never `auto` itself).
23
+ *
24
+ * A request-level guard decides whether an effort may be injected at all:
25
+ * models that do not advertise reasoning metadata (custom openai-completions
26
+ * routes such as Qwen3.6 with no `reasoningEfforts`) must never receive a
27
+ * `reasoningEffort` — dsh rejects it per request with
28
+ * UNSUPPORTED_REASONING_EFFORT. Unsupported fields are stripped, not sent.
17
29
  *
18
30
  * Kept dependency-free (pure inputs -> output) so the policy is unit-testable
19
31
  * in isolation; the plugin host feeds it the live session's recent calls.
20
32
  */
21
- /** The five user-facing thinking levels; the wire levels dsh forwards to DeepSeek plus the scheduler sentinel. */
22
- export type EffortId = 'off' | 'low' | 'high' | 'max' | 'auto';
33
+ /** The user-facing thinking levels: the eight standard levels plus the scheduler sentinel. */
34
+ export type EffortId = 'off' | 'on' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'auto';
23
35
  /** Wire levels the auto scheduler may pick (never `off`, never `auto`). */
24
- export type AutoEffort = Exclude<EffortId, 'auto' | 'off'>;
36
+ export type AutoEffort = 'low' | 'high' | 'max';
37
+ /** The eight standard levels (excluding the `auto` scheduler sentinel). */
38
+ export declare const STANDARD_LEVELS: readonly EffortId[];
25
39
  /** Runtime guard: is this a level the plugin understands? */
26
40
  export declare function isEffortId(value: unknown): value is EffortId;
27
41
  /**
28
42
  * Fail-loud config validation: reject an out-of-band level (e.g. a stray
29
- * `medium` from an old profile) instead of silently injecting it into the
43
+ * value from an old profile) instead of silently injecting it into the
30
44
  * model request, where dsh would throw `UNSUPPORTED_REASONING_EFFORT`.
31
45
  */
32
46
  export declare function assertEffortId(value: unknown, where: string): asserts value is EffortId;
@@ -37,13 +51,15 @@ export interface ToolCallSample {
37
51
  /** Approximate argument size in characters (payload heft). */
38
52
  argsSize: number;
39
53
  }
40
- /** Everything the policy needs to decide one request's level. */
54
+ /**
55
+ * Everything the policy needs to decide one request's level.
56
+ */
41
57
  export interface EffortDecisionInput {
42
58
  /** Recent tool calls of the step (oldest first); empty for a fresh prompt. */
43
59
  recentCalls: readonly ToolCallSample[];
44
60
  /** The user-selected level: a fixed wire level, or `auto` for scheduling. */
45
61
  selected: EffortId;
46
- /** User preference: allow the scheduler to drop below the hub (`high`). */
62
+ /** Scheduler preference: allow the scheduler to drop below the hub (`high`). */
47
63
  allowDowngrade: boolean;
48
64
  /** User preference: allow the scheduler to lift above the hub to `max`. */
49
65
  allowUpgrade: boolean;
@@ -58,5 +74,79 @@ export interface EffortDecisionInput {
58
74
  * @returns The level to inject; `auto` is resolved before returning.
59
75
  */
60
76
  export declare function decideEffort(input: EffortDecisionInput): EffortId;
77
+ /**
78
+ * Whether a model's resolved metadata advertises reasoning-effort support.
79
+ * dsh resolves `reasoning` to `undefined` for non-reasoning models (e.g. a
80
+ * hand-declared openai-completions route without `reasoningEfforts`), and
81
+ * rejects any requested effort for them per request. An empty efforts list is
82
+ * equally incapable and is treated as unsupported.
83
+ * @param reasoning - the `reasoning` field of a resolved model info.
84
+ * @returns true when the model advertises at least one effort level.
85
+ */
86
+ export declare function reasoningEffortSupported(reasoning: unknown): boolean;
87
+ /** One request-level injection decision. */
88
+ export interface EffortInjectionInput {
89
+ /** Whether the target model advertises reasoning-effort support. */
90
+ supportsReasoning: boolean;
91
+ /** The `reasoningEffort` already present on the request seed, if any. */
92
+ seedEffort: unknown;
93
+ /** Plugin-configured default level when the seed carries none. */
94
+ selected: EffortId;
95
+ /** Recent tool calls of the step, for the auto scheduler. */
96
+ recentCalls: readonly ToolCallSample[];
97
+ /** Scheduler preference: allow the scheduler to drop below `high`. */
98
+ allowDowngrade: boolean;
99
+ /** Scheduler preference: allow lifting above `high` to `max`. */
100
+ allowUpgrade: boolean;
101
+ /** The model's advertised effort ids (including plugin masks like `auto`). */
102
+ efforts: readonly string[];
103
+ /**
104
+ * The model takes only an on/off thinking toggle (Qwen3.6 / mimo-v2.5
105
+ * style): `off` must be stripped (pi-ai expresses it by omitting the effort,
106
+ * not by sending an `off` value), and `on` maps to the advertised `high`
107
+ * level (pi-ai serializes it as enable_thinking, no reasoning_effort).
108
+ */
109
+ toggleOnly: boolean;
110
+ }
111
+ /** The resolved action for one `agent/request`. */
112
+ export interface EffortInjectionDecision {
113
+ /** Keep/inject a `reasoningEffort` on the request (false = strip it). */
114
+ inject: boolean;
115
+ /** The wire level to set, present when `inject` is true. */
116
+ level?: EffortId;
117
+ }
118
+ /**
119
+ * Clamp a level to the ones the model actually advertises. The adapter rejects
120
+ * any other value per request (UNSUPPORTED_REASONING_EFFORT), so an unsupported
121
+ * scheduled level is lifted to the model's highest advertised thinking level
122
+ * (a toggle-only model advertises off/high → a scheduled low becomes `high`,
123
+ * which enables thinking without sending a think effort), and a model
124
+ * advertising no thinking level at all yields nothing (strip).
125
+ * @param level - the scheduled or manually selected level.
126
+ * @param efforts - the model's advertised effort ids (escalation-ordered).
127
+ * @returns the level to inject, or `undefined` when the model cannot take it.
128
+ */
129
+ export declare function clampToEfforts(level: EffortId, efforts: readonly string[]): EffortId | undefined;
130
+ /**
131
+ * Decide what one model request should do with `reasoningEffort`.
132
+ *
133
+ * - A model without reasoning support never receives the field: dsh would
134
+ * throw UNSUPPORTED_REASONING_EFFORT, so the seed's inherited effort (from a
135
+ * previous route or session header) is stripped.
136
+ * - A manual wire selection passes through unchanged when the model advertises
137
+ * it; an unsupported manual pick is stripped rather than clamped (the user
138
+ * asked for that exact level).
139
+ * - `on` is the enable-thinking toggle, never a wire level: on a toggle-only
140
+ * model it injects the advertised thinking level (`high`), which the wire
141
+ * serializes as enable_thinking without a reasoning_effort; an
142
+ * effort-capable model does not advertise `on`, so it is stripped.
143
+ * - `auto` (or no selection) resolves through the scheduler; the result is
144
+ * clamped to the model's advertised levels, so a scheduled `low` on a model
145
+ * that only takes off/high (Qwen3.6) becomes `high` instead of an error.
146
+ *
147
+ * @param input - model capability plus the seed's current effort.
148
+ * @returns whether to inject and the level to set.
149
+ */
150
+ export declare function resolveEffortInjection(input: EffortInjectionInput): EffortInjectionDecision;
61
151
  /** Wall-clock delta of one tool call, for the timing telemetry. */
62
152
  export declare function toolDurationMs(startedAt: number, finishedAt: number): number;
@@ -3,33 +3,50 @@
3
3
  *
4
4
  * The measured bottleneck of tool calls in dsh is the model's THINKING phase
5
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).
6
+ * itself. DeepSeek's API exposes `reasoning_effort` in wire levels
7
+ * (off / low / high / max; low shipped 2026-08-13 in dsh rc.7 — rc.6 and
8
+ * older adapters only accept off / high / max).
9
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).
10
+ * The plugin offers EIGHT standard levels aligned with dsh-thinking-effort's
11
+ * level set, plus the scheduler sentinel:
12
+ * - `off` : thinking disabled (manual only — never auto-picked).
13
+ * - `on` : thinking enabled at the model's default strength. Toggle-only
14
+ * models (Qwen3.6-style) surface Off/On; `on` lifts to the
15
+ * advertised `high` (or the highest thinking level the model
16
+ * takes) instead of an exact wire level.
17
+ * - `minimal` / `low` / `medium` / `high` / `xhigh` / `max` : strength
18
+ * gradients. Each maps to a wire value via the model's `reasoningEfforts`
19
+ * table (customizable per model — e.g. `high` → `ultra`); levels the model
20
+ * does not advertise are clamped to its highest thinking level or stripped.
21
+ * - `auto` : schedule per step from the recent tool-call history, between
22
+ * `low` / `high` / `max` (never `off`, never `auto` itself).
23
+ *
24
+ * A request-level guard decides whether an effort may be injected at all:
25
+ * models that do not advertise reasoning metadata (custom openai-completions
26
+ * routes such as Qwen3.6 with no `reasoningEfforts`) must never receive a
27
+ * `reasoningEffort` — dsh rejects it per request with
28
+ * UNSUPPORTED_REASONING_EFFORT. Unsupported fields are stripped, not sent.
17
29
  *
18
30
  * Kept dependency-free (pure inputs -> output) so the policy is unit-testable
19
31
  * in isolation; the plugin host feeds it the live session's recent calls.
20
32
  */
33
+ /** The eight standard levels (excluding the `auto` scheduler sentinel). */
34
+ export const STANDARD_LEVELS = [
35
+ 'off', 'on', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max',
36
+ ];
21
37
  /** Runtime guard: is this a level the plugin understands? */
22
38
  export function isEffortId(value) {
23
- return value === 'off' || value === 'low' || value === 'high' || value === 'max' || value === 'auto';
39
+ return STANDARD_LEVELS.includes(value) || value === 'auto';
24
40
  }
25
41
  /**
26
42
  * Fail-loud config validation: reject an out-of-band level (e.g. a stray
27
- * `medium` from an old profile) instead of silently injecting it into the
43
+ * value from an old profile) instead of silently injecting it into the
28
44
  * model request, where dsh would throw `UNSUPPORTED_REASONING_EFFORT`.
29
45
  */
30
46
  export function assertEffortId(value, where) {
31
47
  if (!isEffortId(value)) {
32
- throw new TypeError(`${where}: invalid thinking level ${JSON.stringify(value)} (expected off | low | high | max | auto)`);
48
+ throw new TypeError(`${where}: invalid thinking level ${JSON.stringify(value)} `
49
+ + '(expected off | on | minimal | low | medium | high | xhigh | max | auto)');
33
50
  }
34
51
  }
35
52
  /** Deterministic tool names that are cheap to reason about (word-boundary anchored). */
@@ -53,6 +70,10 @@ function simpleRatio(calls) {
53
70
  * - Mixed or heavy tools -> `high` (the hub).
54
71
  * - Very heavy context (huge args) -> `max` (when upgrades are allowed).
55
72
  *
73
+ * The scheduler MAY pick `low`: the request-level capability guard strips any
74
+ * effort from models that do not support it, so a scheduled `low` only ever
75
+ * reaches models that advertise the level.
76
+ *
56
77
  * @param calls - recent tool calls of the step.
57
78
  * @param allowDowngrade - may drop below `high`.
58
79
  * @param allowUpgrade - may lift above `high`.
@@ -84,6 +105,98 @@ export function decideEffort(input) {
84
105
  return selected;
85
106
  return scheduleEffort(recentCalls, allowDowngrade, allowUpgrade);
86
107
  }
108
+ /**
109
+ * Whether a model's resolved metadata advertises reasoning-effort support.
110
+ * dsh resolves `reasoning` to `undefined` for non-reasoning models (e.g. a
111
+ * hand-declared openai-completions route without `reasoningEfforts`), and
112
+ * rejects any requested effort for them per request. An empty efforts list is
113
+ * equally incapable and is treated as unsupported.
114
+ * @param reasoning - the `reasoning` field of a resolved model info.
115
+ * @returns true when the model advertises at least one effort level.
116
+ */
117
+ export function reasoningEffortSupported(reasoning) {
118
+ if (typeof reasoning !== 'object' || reasoning === null)
119
+ return false;
120
+ const efforts = reasoning.efforts;
121
+ return Array.isArray(efforts) && efforts.length > 0;
122
+ }
123
+ /**
124
+ * Clamp a level to the ones the model actually advertises. The adapter rejects
125
+ * any other value per request (UNSUPPORTED_REASONING_EFFORT), so an unsupported
126
+ * scheduled level is lifted to the model's highest advertised thinking level
127
+ * (a toggle-only model advertises off/high → a scheduled low becomes `high`,
128
+ * which enables thinking without sending a think effort), and a model
129
+ * advertising no thinking level at all yields nothing (strip).
130
+ * @param level - the scheduled or manually selected level.
131
+ * @param efforts - the model's advertised effort ids (escalation-ordered).
132
+ * @returns the level to inject, or `undefined` when the model cannot take it.
133
+ */
134
+ export function clampToEfforts(level, efforts) {
135
+ if (efforts.includes(level))
136
+ return level;
137
+ // off and auto are not thinking levels; the advertised list is
138
+ // escalation-ordered.
139
+ const thinking = efforts.filter(id => id !== 'off' && id !== 'auto');
140
+ if (thinking.length === 0)
141
+ return undefined;
142
+ return thinking[thinking.length - 1];
143
+ }
144
+ /**
145
+ * Decide what one model request should do with `reasoningEffort`.
146
+ *
147
+ * - A model without reasoning support never receives the field: dsh would
148
+ * throw UNSUPPORTED_REASONING_EFFORT, so the seed's inherited effort (from a
149
+ * previous route or session header) is stripped.
150
+ * - A manual wire selection passes through unchanged when the model advertises
151
+ * it; an unsupported manual pick is stripped rather than clamped (the user
152
+ * asked for that exact level).
153
+ * - `on` is the enable-thinking toggle, never a wire level: on a toggle-only
154
+ * model it injects the advertised thinking level (`high`), which the wire
155
+ * serializes as enable_thinking without a reasoning_effort; an
156
+ * effort-capable model does not advertise `on`, so it is stripped.
157
+ * - `auto` (or no selection) resolves through the scheduler; the result is
158
+ * clamped to the model's advertised levels, so a scheduled `low` on a model
159
+ * that only takes off/high (Qwen3.6) becomes `high` instead of an error.
160
+ *
161
+ * @param input - model capability plus the seed's current effort.
162
+ * @returns whether to inject and the level to set.
163
+ */
164
+ export function resolveEffortInjection(input) {
165
+ const { supportsReasoning, seedEffort, selected, efforts, toggleOnly } = input;
166
+ if (!supportsReasoning)
167
+ return { inject: false };
168
+ if (toggleOnly) {
169
+ // Toggle-only model (Qwen3.6 / mimo-v2.5 style): thinking is an on/off
170
+ // switch expressed through the provider's enable_thinking semantics.
171
+ // - Off → inject `off`: the provider maps it to thinking disabled.
172
+ // - On / any other seed → inject `high` (the advertised toggle level): the
173
+ // short-circuit adapter serializes a non-off effort as enable_thinking
174
+ // true — an explicit "thinking on" signal the wire needs. (A request
175
+ // with NO effort at all is the ambiguous case: leaving it absent relies
176
+ // on the provider default, which some gateways treat as off.)
177
+ return { inject: true, level: seedEffort === 'off' ? 'off' : 'high' };
178
+ }
179
+ if (seedEffort === 'on') {
180
+ // A stray On on an effort-capable model: never a wire level, stripped.
181
+ return { inject: false };
182
+ }
183
+ if (isEffortId(seedEffort) && seedEffort !== 'auto') {
184
+ // A manual pick is the user asking for that exact level: pass it through
185
+ // only when the model advertises it, strip it otherwise (no clamping of an
186
+ // explicit choice).
187
+ return efforts.includes(seedEffort)
188
+ ? { inject: true, level: seedEffort }
189
+ : { inject: false };
190
+ }
191
+ const level = decideEffort({
192
+ recentCalls: input.recentCalls,
193
+ selected: seedEffort === 'auto' ? 'auto' : selected,
194
+ allowDowngrade: input.allowDowngrade,
195
+ allowUpgrade: input.allowUpgrade,
196
+ });
197
+ const clamped = clampToEfforts(level, efforts);
198
+ return clamped === undefined ? { inject: false } : { inject: true, level: clamped };
199
+ }
87
200
  /** Wall-clock delta of one tool call, for the timing telemetry. */
88
201
  export function toolDurationMs(startedAt, finishedAt) {
89
202
  return Math.max(0, finishedAt - startedAt);