dsh-thinking-levels 0.6.0 → 0.7.1-beta.2

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,41 @@
1
+ /**
2
+ * Pure context-window helpers for the dsh-thinking-levels plugin.
3
+ *
4
+ * The context-window limit of a custom gateway model is declared in the
5
+ * llm-pi-ai model entry (`contextWindow`, a positive integer). The harness
6
+ * consumes it through `resolveModelInfo(...).context.contextWindow` for
7
+ * compaction thresholds, context-overflow detection and context-pressure
8
+ * projections — a settings write takes effect on the next request without a
9
+ * restart. This module centralizes the legal range, the common presets and
10
+ * the display formatting shared by the config schema, the settings card and
11
+ * the tests. Kept dependency-free (pure inputs -> output).
12
+ */
13
+ /** Smallest accepted context window (tokens), aligned with dsh-thinking-effort. */
14
+ export declare const CONTEXT_WINDOW_MIN = 2000;
15
+ /** Largest accepted context window (tokens), e.g. third-party DeepSeek 1M. */
16
+ export declare const CONTEXT_WINDOW_MAX = 1000000;
17
+ /** One selectable context-window preset. */
18
+ export interface ContextWindowPreset {
19
+ /** Human-readable label shown on the card button and the model badge. */
20
+ label: string;
21
+ /** The token count written to the llm-pi-ai model entry. */
22
+ value: number;
23
+ }
24
+ /** The multi-level context-window presets, in ascending order. */
25
+ export declare const CONTEXT_WINDOW_PRESETS: readonly ContextWindowPreset[];
26
+ /** Format a token count as a readable label (exact presets keep their label). */
27
+ export declare function formatContextWindow(value: number): string;
28
+ /** The result of validating a context-window value. */
29
+ export type ContextWindowValidation = {
30
+ ok: true;
31
+ value: number;
32
+ } | {
33
+ ok: false;
34
+ reason: 'integer' | 'range';
35
+ };
36
+ /**
37
+ * Validate a context-window candidate (number or numeric string). Accepts only
38
+ * base-10 integers inside [CONTEXT_WINDOW_MIN, CONTEXT_WINDOW_MAX]; anything
39
+ * else (float, 'abc', '1e3', out-of-range) is rejected with a reason.
40
+ */
41
+ export declare function validateContextWindow(value: unknown): ContextWindowValidation;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Pure context-window helpers for the dsh-thinking-levels plugin.
3
+ *
4
+ * The context-window limit of a custom gateway model is declared in the
5
+ * llm-pi-ai model entry (`contextWindow`, a positive integer). The harness
6
+ * consumes it through `resolveModelInfo(...).context.contextWindow` for
7
+ * compaction thresholds, context-overflow detection and context-pressure
8
+ * projections — a settings write takes effect on the next request without a
9
+ * restart. This module centralizes the legal range, the common presets and
10
+ * the display formatting shared by the config schema, the settings card and
11
+ * the tests. Kept dependency-free (pure inputs -> output).
12
+ */
13
+ /** Smallest accepted context window (tokens), aligned with dsh-thinking-effort. */
14
+ export const CONTEXT_WINDOW_MIN = 2000;
15
+ /** Largest accepted context window (tokens), e.g. third-party DeepSeek 1M. */
16
+ export const CONTEXT_WINDOW_MAX = 1_000_000;
17
+ /** The multi-level context-window presets, in ascending order. */
18
+ export const CONTEXT_WINDOW_PRESETS = [
19
+ { label: '64K', value: 64_000 },
20
+ { label: '128K', value: 131_072 },
21
+ { label: '256K', value: 256_000 },
22
+ { label: '400K', value: 400_000 },
23
+ { label: '512K', value: 524_288 },
24
+ { label: '1M', value: 1_000_000 },
25
+ ];
26
+ /** Format a token count as a readable label (exact presets keep their label). */
27
+ export function formatContextWindow(value) {
28
+ const preset = CONTEXT_WINDOW_PRESETS.find(candidate => candidate.value === value);
29
+ if (preset !== undefined)
30
+ return preset.label;
31
+ if (value >= CONTEXT_WINDOW_MAX)
32
+ return '1M';
33
+ if (value >= 1024)
34
+ return `${Math.round(value / 1024)}K`;
35
+ return String(value);
36
+ }
37
+ /**
38
+ * Validate a context-window candidate (number or numeric string). Accepts only
39
+ * base-10 integers inside [CONTEXT_WINDOW_MIN, CONTEXT_WINDOW_MAX]; anything
40
+ * else (float, 'abc', '1e3', out-of-range) is rejected with a reason.
41
+ */
42
+ export function validateContextWindow(value) {
43
+ const raw = typeof value === 'string' ? value.trim() : value;
44
+ const asString = typeof raw === 'string' ? raw : String(raw);
45
+ if (!/^\d+$/.test(asString))
46
+ return { ok: false, reason: 'integer' };
47
+ const numeric = Number(asString);
48
+ if (!Number.isSafeInteger(numeric))
49
+ return { ok: false, reason: 'integer' };
50
+ if (numeric < CONTEXT_WINDOW_MIN || numeric > CONTEXT_WINDOW_MAX) {
51
+ return { ok: false, reason: 'range' };
52
+ }
53
+ return { ok: true, value: numeric };
54
+ }
package/lib/index.d.ts CHANGED
@@ -23,7 +23,12 @@
23
23
  * - `agent/request` waterfall (packages/core/agent-loop/src/agent.ts
24
24
  * buildRequest): each listener may return a modified GenerateOptions for
25
25
  * the next listener — the sanctioned way to adjust request config.
26
- * - `session.events` (agent.session) carries the step's tool/call records.
26
+ * - `session.events` (agent.session) carries the step's tool/call records; the
27
+ * auto scheduler PULLS the recent calls from there at request time
28
+ * (`recentToolCalls`). There is no `agent/tool` push event in DSH — the
29
+ * scope-event registry (`packages/core/scope/src/scoped-events.generated.ts`)
30
+ * lists no such name in 0.1.1-rc.2 or 0.1.2-rc.1, so tool recognition must
31
+ * stay a pull from `session.events`.
27
32
  * - settings service namespace (like DSH-better-sidebar's PrefsSchema) for
28
33
  * the user toggles.
29
34
  */
@@ -43,6 +48,12 @@ export interface ModelCapabilityOverride {
43
48
  * adapter-advertised list.
44
49
  */
45
50
  efforts?: false | Exclude<EffortId, 'auto'>[];
51
+ /**
52
+ * Declared context-window limit in tokens (2000–1_000_000). Declaration-only:
53
+ * the runtime harness reads it from the llm-pi-ai model entry, so this
54
+ * override is a validated config-surface declaration.
55
+ */
56
+ contextWindow?: number;
46
57
  }
47
58
  /** Plugin settings. */
48
59
  export interface ThinkingLevelsConfig {
package/lib/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
2
  import { assertEffortId, reasoningEffortSupported, resolveEffortInjection } from "./thinking-level.js";
3
3
  import { recentToolCalls } from "./session-events.js";
4
- import { identifyTakeoverProviders, nextTakeoverSection, PI_AI_NAMESPACE, TAKEOVER_NAMESPACE, takeoverProvidersOf, } from "./takeover-sync.js";
4
+ import { CONTEXT_WINDOW_MAX, CONTEXT_WINDOW_MIN } from "./context-window.js";
5
+ import { PI_AI_NAMESPACE, TAKEOVER_NAMESPACE, takeoverProvidersOf, withOfficialCompatFixes, } from "./takeover-sync.js";
5
6
  const effortId = z.union(['off', 'on', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
6
7
  /**
7
8
  * Composition-entry schema: what a dsh profile may configure at assembly
@@ -19,6 +20,7 @@ export const Config = z.object({
19
20
  vision: z.boolean(),
20
21
  thinking: z.boolean(),
21
22
  efforts: z.union([z.const(false), z.array(effortId)]),
23
+ contextWindow: z.number().step(1).min(CONTEXT_WINDOW_MIN).max(CONTEXT_WINDOW_MAX),
22
24
  })).default({}),
23
25
  });
24
26
  /** Settings defaults, kept in lockstep with the schema defaults above. */
@@ -57,7 +59,6 @@ function installSettingsSection(ctx, ns, schema, entry, hooks) {
57
59
  scope.watch(() => hooks.onChange());
58
60
  });
59
61
  }
60
- const TOOL_AGE_LIMIT_MS = 10 * 60 * 1000;
61
62
  /**
62
63
  * The `auto` mask shown in the model directory: a user-facing level that is
63
64
  * never sent to the API — the plugin resolves it to a wire level per request.
@@ -238,42 +239,46 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
238
239
  // re-registration.
239
240
  onChange: () => { },
240
241
  });
241
- // Auto-takeover bridge: keep the dsh-llm-openai-completions provider list in
242
- // sync with the llm-pi-ai section. A provider that targets a custom
243
- // openai-completions gateway AND declares thinking (reasoningEfforts table)
244
- // is exactly the route whose wire behavior must be taken over by the adapter
245
- // plugin — without the list entry the pi-ai adapter would serve it (developer
246
- // role 400 / no enable_thinking). The sync is soft-coupled: when the
247
- // llm-openai-completions plugin is not composed its namespace is unregistered
248
- // and the write is skipped. The read is lazy (the settings service may
249
- // register after this plugin's apply) and writes are queued by the service,
250
- // so no race with a concurrent Settings → Models edit.
242
+ // Official-compat bridge (check branch): write the OFFICIAL compat surface
243
+ // into the llm-pi-ai namespace for every provider that targets a custom
244
+ // openai-completions gateway AND declares thinking (reasoningEfforts table):
245
+ // route-level `supportsDeveloperRole: false` plus model-level
246
+ // `thinkingFormat: qwen` on toggle-style thinking rows. This replaces the
247
+ // retired short-circuit route (maintaining the dsh-llm-openai-completions
248
+ // takeover list): since dsh v0.1.0-rc.8 the declarative compat fixes the
249
+ // developer-role 400 AND drives enable_thinking at the pi-ai adapter itself,
250
+ // so pi-ai keeps serving the route and no transport takeover is needed.
251
+ // Storage pattern follows
252
+ // hytime/dsh-thinking-effort's host side: read → pure transform (identity
253
+ // when nothing to change) → whole-section update, so dsh's llm-pi-ai schema
254
+ // validator gates the write where it is WRITTEN; an installed dsh predating
255
+ // rc.8 rejects the unknown field and we log and keep the previous section.
256
+ // The read is lazy and writes are queued by the service, so no race with a
257
+ // concurrent Settings → Models edit.
251
258
  let syncTail = Promise.resolve();
252
- const syncTakeover = () => {
259
+ const syncDeveloperRole = () => {
253
260
  syncTail = syncTail.then(async () => {
254
261
  const settings = ctx.get('settings');
255
- const previous = settings?.get?.(TAKEOVER_NAMESPACE);
256
- // Unregistered namespace → the adapter plugin is absent; never write.
257
- if (previous === undefined)
258
- return;
259
262
  const piAi = settings?.get?.(PI_AI_NAMESPACE);
260
- const next = nextTakeoverSection(previous, identifyTakeoverProviders(piAi));
261
- if (next === previous)
263
+ const next = withOfficialCompatFixes(piAi);
264
+ if (next === undefined || next === piAi)
262
265
  return;
263
- await settings?.update?.(TAKEOVER_NAMESPACE, next);
264
- ctx.logger?.info?.('[thinking-levels] auto-takeover: llm-openai-completions providers=%j (from llm-pi-ai thinking routes)', next.providers);
266
+ await settings?.update?.(PI_AI_NAMESPACE, { providers: next.providers });
267
+ ctx.logger?.info?.('[thinking-levels] official-compat: supportsDeveloperRole=false (route) and thinkingFormat=qwen (toggle-style models) written to llm-pi-ai for custom thinking routes');
265
268
  }).catch((error) => {
266
- ctx.logger?.warn?.('[thinking-levels] auto-takeover sync failed (kept previous list)', error);
269
+ ctx.logger?.warn?.('[thinking-levels] developer-role compat sync rejected (schema gate); kept previous section', error);
267
270
  });
268
271
  };
269
272
  // Initial sync (adapters may register later; re-run on every adapters update
270
- // and every settings document update so a Settings → Models edit propagates).
271
- syncTakeover();
273
+ // and every llm-pi-ai settings update so a Settings → Models edit propagates.
274
+ // The write is identity-gated, so the re-entry triggered by our own update
275
+ // settles immediately).
276
+ syncDeveloperRole();
272
277
  const onSyncAny = ctx.on;
273
- onSyncAny('llm/adapters-updated', () => syncTakeover());
278
+ onSyncAny('llm/adapters-updated', () => syncDeveloperRole());
274
279
  onSyncAny('settings/document-updated', (ns) => {
275
- if (ns === PI_AI_NAMESPACE || ns === TAKEOVER_NAMESPACE)
276
- syncTakeover();
280
+ if (ns === PI_AI_NAMESPACE)
281
+ syncDeveloperRole();
277
282
  });
278
283
  // Inject the level decision into every model request of a step.
279
284
  // The 'agent/request' event key is augmented onto cordis Events by the
@@ -341,33 +346,4 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
341
346
  capability.clear();
342
347
  advertiseModelCapability(ctx.get('llm'), overrideFor, piAiFor);
343
348
  });
344
- // Per-tool wall-clock telemetry: log tool/call -> tool/result durations.
345
- // Same boundary widening as above (agent/tool is a generated scope event).
346
- const started = new Map();
347
- // A tool that never emits `end` (crash, interruption) must not leak its
348
- // entry forever; sweep stale ones lazily on every new `start`.
349
- const pruneStale = (now) => {
350
- for (const [callId, at] of started) {
351
- if (now - at > TOOL_AGE_LIMIT_MS)
352
- started.delete(callId);
353
- }
354
- };
355
- on('agent/tool', async (payload) => {
356
- const callId = payload.callId;
357
- if (typeof callId !== 'string')
358
- return;
359
- if (payload.phase === 'start') {
360
- const now = Date.now();
361
- pruneStale(now);
362
- started.set(callId, now);
363
- }
364
- else if (payload.phase === 'end') {
365
- const from = started.get(callId);
366
- started.delete(callId);
367
- if (from !== undefined) {
368
- const ms = Date.now() - from;
369
- ctx.logger?.info?.('[thinking-levels] tool %s took %dms', callId, ms);
370
- }
371
- }
372
- });
373
349
  }
@@ -1,51 +1,58 @@
1
1
  /**
2
- * Auto-takeover sync: bridge from dsh-thinking-levels to the
3
- * dsh-llm-openai-completions adapter plugin.
2
+ * Auto-flag sync (check branch): bridge from dsh-thinking-levels to the
3
+ * OFFICIAL llm-pi-ai compat surface.
4
4
  *
5
- * The openai-completions adapter takes over streaming for the providers listed
6
- * in the `llm-openai-completions` settings namespace (`{ enabled, providers }`).
7
- * Maintaining that list by hand is friction: a user who configures a custom
8
- * gateway with thinking in `llm-pi-ai` (reasoningEfforts table) must ALSO add
9
- * the provider to the takeover list or the pi-ai adapter serves the route with
10
- * the wrong wire behavior (developer role / no enable_thinking).
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
11
  *
12
- * This module closes that gap: it scans the live `llm-pi-ai` section for
13
- * providers that (a) target a custom openai-completions gateway and (b) declare
14
- * thinking (a reasoningEfforts table), and computes the `llm-openai-completions`
15
- * list that would take them over. Pure functions here are unit-tested; the host
16
- * plugin wires them to the settings service.
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.
17
21
  *
18
- * Deliberately soft-coupled: nothing here value-imports the adapter plugin or
19
- * dsh-settings. If the `llm-openai-completions` namespace is unregistered (the
20
- * plugin is not composed), the host skips the write — no error, no log spam.
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.
21
31
  * @module dsh-thinking-levels/takeover-sync
22
32
  */
23
- /** The settings namespace owned by dsh-llm-openai-completions. */
24
- export declare const TAKEOVER_NAMESPACE = "llm-openai-completions";
25
33
  /** The settings namespace holding the provider/model configs (llm-pi-ai). */
26
34
  export declare const PI_AI_NAMESPACE = "llm-pi-ai";
35
+ /** The settings namespace of the retired short-circuit adapter, still READ to gate posture. */
36
+ export declare const TAKEOVER_NAMESPACE = "llm-openai-completions";
27
37
  /** One model row of the llm-pi-ai section (minimal face). */
28
38
  export interface PiAiModelRow {
29
39
  id?: unknown;
30
40
  reasoningEfforts?: unknown;
41
+ compat?: unknown;
31
42
  }
32
43
  /** One provider profile of the llm-pi-ai section (minimal face). */
33
44
  export interface PiAiProviderProfile {
34
45
  api?: unknown;
35
46
  baseURL?: unknown;
36
47
  models?: unknown;
48
+ compat?: unknown;
37
49
  /** Other profile fields (apiKeyEnv, displayName, …) exist but are unused. */
38
50
  [key: string]: unknown;
39
51
  }
40
- /** The llm-pi-ai section slice this module reads. */
52
+ /** The llm-pi-ai section slice this module reads and transforms. */
41
53
  export interface PiAiSection {
42
54
  providers?: Record<string, PiAiProviderProfile>;
43
55
  }
44
- /** The llm-openai-completions section this module writes. */
45
- export interface TakeoverSection {
46
- enabled: boolean;
47
- providers: string[];
48
- }
49
56
  /**
50
57
  * Whether a provider profile targets a CUSTOM openai-completions gateway:
51
58
  * explicit `api: openai-completions`, or a baseURL that is not an official
@@ -72,15 +79,33 @@ export declare function declaresThinking(profile: PiAiProviderProfile | undefine
72
79
  */
73
80
  export declare function identifyTakeoverProviders(section: PiAiSection | undefined): string[];
74
81
  /**
75
- * Compute the next takeover section: the previous user list plus every
76
- * identified provider (deduped, order preserved), enabled. When nothing
77
- * changes, the previous section is returned unchanged (identity — the host
78
- * compares before writing).
79
- * @param previous - the current llm-openai-completions value, if registered.
80
- * @param identified - providers identified for takeover.
81
- * @returns the section to write, or the previous value when no change.
82
+ * Compute the llm-pi-ai section with the OFFICIAL compat fixes written for
83
+ * every identified provider (custom openai-completions gateway AND thinking
84
+ * declared):
85
+ *
86
+ * 1. ROUTE level: `compat.supportsDeveloperRole: false` when the route does
87
+ * not carry an explicit value — the system prompt goes out as `system`
88
+ * (fixes the Unexpected message role 400 on vLLM/SGLang gateways).
89
+ * 2. MODEL level: `compat.thinkingFormat: 'qwen-chat-template'` on TOGGLE-STYLE thinking
90
+ * model rows (a reasoningEfforts table, no row-level
91
+ * `supportsReasoningEffort: true`, no explicit thinkingFormat) — pi-ai
92
+ * then sends the `enable_thinking` flag these early vLLM thinking models
93
+ * need, instead of a reasoning_effort they do not support. Effort-capable
94
+ * rows are untouched (their reasoning_effort wire needs the default/openai
95
+ * or declared format), and the route level is deliberately NOT written —
96
+ * a route-wide thinkingFormat would flip effort models onto
97
+ * enable_thinking too.
98
+ *
99
+ * Semantics (learned from dsh-thinking-effort's storage handling):
100
+ * - An EXPLICIT value on any layer is respected and left alone; only ABSENT
101
+ * fields are filled. This keeps the sync idempotent and never overrides
102
+ * user intent.
103
+ * - Immutable: unchanged profiles/rows and the unchanged section are returned
104
+ * by reference, so the host can skip the write on identity.
105
+ * @param section - the live llm-pi-ai section.
106
+ * @returns the next section, or the previous value (identity) when no change.
82
107
  */
83
- export declare function nextTakeoverSection(previous: TakeoverSection | undefined, identified: readonly string[]): TakeoverSection;
108
+ export declare function withOfficialCompatFixes(section: PiAiSection | undefined): PiAiSection | undefined;
84
109
  /**
85
110
  * The providers the openai-completions adapter is currently set up to take
86
111
  * over, from the live `llm-openai-completions` settings namespace. Used to
@@ -1,29 +1,39 @@
1
1
  /**
2
- * Auto-takeover sync: bridge from dsh-thinking-levels to the
3
- * dsh-llm-openai-completions adapter plugin.
2
+ * Auto-flag sync (check branch): bridge from dsh-thinking-levels to the
3
+ * OFFICIAL llm-pi-ai compat surface.
4
4
  *
5
- * The openai-completions adapter takes over streaming for the providers listed
6
- * in the `llm-openai-completions` settings namespace (`{ enabled, providers }`).
7
- * Maintaining that list by hand is friction: a user who configures a custom
8
- * gateway with thinking in `llm-pi-ai` (reasoningEfforts table) must ALSO add
9
- * the provider to the takeover list or the pi-ai adapter serves the route with
10
- * the wrong wire behavior (developer role / no enable_thinking).
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
11
  *
12
- * This module closes that gap: it scans the live `llm-pi-ai` section for
13
- * providers that (a) target a custom openai-completions gateway and (b) declare
14
- * thinking (a reasoningEfforts table), and computes the `llm-openai-completions`
15
- * list that would take them over. Pure functions here are unit-tested; the host
16
- * plugin wires them to the settings service.
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.
17
21
  *
18
- * Deliberately soft-coupled: nothing here value-imports the adapter plugin or
19
- * dsh-settings. If the `llm-openai-completions` namespace is unregistered (the
20
- * plugin is not composed), the host skips the write — no error, no log spam.
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.
21
31
  * @module dsh-thinking-levels/takeover-sync
22
32
  */
23
- /** The settings namespace owned by dsh-llm-openai-completions. */
24
- export const TAKEOVER_NAMESPACE = 'llm-openai-completions';
25
33
  /** The settings namespace holding the provider/model configs (llm-pi-ai). */
26
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';
27
37
  /** Hosts that are NOT a custom gateway (official OpenAI-compatible endpoints). */
28
38
  const OFFICIAL_HOST_RE = /(?:^|\.)(?:deepseek\.com|openai\.com|openrouter\.ai|anthropic\.com|googleapis\.com|ai\.google\.dev|mistral\.ai|x\.ai)$/i;
29
39
  /** Whether a value looks like a declared reasoningEfforts table. */
@@ -53,6 +63,17 @@ export function isCustomOpenAiGateway(profile) {
53
63
  return false;
54
64
  }
55
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
+ }
56
77
  /**
57
78
  * Whether a provider declares thinking: at least one model row carries a
58
79
  * reasoningEfforts table (thinking on). `false` (thinking off) and absent
@@ -61,13 +82,9 @@ export function isCustomOpenAiGateway(profile) {
61
82
  * @returns true when any model declares a reasoningEfforts table.
62
83
  */
63
84
  export function declaresThinking(profile) {
64
- if (profile === undefined || !Array.isArray(profile.models))
85
+ if (profile === undefined)
65
86
  return false;
66
- return profile.models.some((row) => {
67
- if (typeof row !== 'object' || row === null)
68
- return false;
69
- return isEffortsTable(row.reasoningEfforts);
70
- });
87
+ return modelRows(profile).some((row) => isEffortsTable(row.reasoningEfforts));
71
88
  }
72
89
  /**
73
90
  * Identify the providers that should be taken over by the openai-completions
@@ -84,30 +101,119 @@ export function identifyTakeoverProviders(section) {
84
101
  .filter(([, profile]) => isCustomOpenAiGateway(profile) && declaresThinking(profile))
85
102
  .map(([id]) => id);
86
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
+ }
87
118
  /**
88
- * Compute the next takeover section: the previous user list plus every
89
- * identified provider (deduped, order preserved), enabled. When nothing
90
- * changes, the previous section is returned unchanged (identity — the host
91
- * compares before writing).
92
- * @param previous - the current llm-openai-completions value, if registered.
93
- * @param identified - providers identified for takeover.
94
- * @returns the section to write, or the previous value when no change.
119
+ * Rewrite one model row's compat for the toggle-thinking fix. Returns the row
120
+ * by reference when nothing to change.
95
121
  */
96
- export function nextTakeoverSection(previous, identified) {
97
- const base = previous ?? { enabled: false, providers: [] };
98
- if (identified.length === 0) {
99
- // Nothing to take over: keep the previous list untouched (respect a manual
100
- // list; do not enable on our own).
101
- return base;
102
- }
103
- const merged = [...base.providers];
104
- for (const id of identified) {
105
- if (!merged.includes(id))
106
- merged.push(id);
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
+ }
107
215
  }
108
- if (base.enabled && merged.length === base.providers.length)
109
- return base;
110
- return { enabled: true, providers: merged };
216
+ return nextProviders === undefined ? section : { ...section, providers: nextProviders };
111
217
  }
112
218
  /**
113
219
  * The providers the openai-completions adapter is currently set up to take