dsh-thinking-levels 0.4.1 → 0.6.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/lib/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
- import { assertEffortId, decideEffort, isEffortId } from "./thinking-level.js";
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";
5
+ const effortId = z.union(['off', 'on', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
4
6
  /**
5
7
  * Composition-entry schema: what a dsh profile may configure at assembly
6
8
  * time (cordis.yml `config:` of the plugin row). The settings namespace
@@ -9,9 +11,15 @@ import { recentToolCalls } from "./session-events.js";
9
11
  */
10
12
  export const Config = z.object({
11
13
  enabled: z.boolean().default(true),
12
- level: z.union(['off', 'low', 'high', 'max', 'auto']).default('auto'),
14
+ level: z.union(['off', 'on', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'auto']).default('auto'),
13
15
  allowDowngrade: z.boolean().default(true),
14
16
  allowUpgrade: z.boolean().default(false),
17
+ models: z.dict(z.object({
18
+ // schemastery fields are optional unless marked `.required()`.
19
+ vision: z.boolean(),
20
+ thinking: z.boolean(),
21
+ efforts: z.union([z.const(false), z.array(effortId)]),
22
+ })).default({}),
15
23
  });
16
24
  /** Settings defaults, kept in lockstep with the schema defaults above. */
17
25
  export const DEFAULT_CONFIG = {
@@ -19,6 +27,7 @@ export const DEFAULT_CONFIG = {
19
27
  level: 'auto',
20
28
  allowDowngrade: true,
21
29
  allowUpgrade: false,
30
+ models: {},
22
31
  };
23
32
  /** Runtime-adjustable settings namespace: level + scheduler toggles. */
24
33
  export const THINKING_LEVELS_SETTINGS_NAMESPACE = 'thinking-levels';
@@ -58,25 +67,153 @@ const TOOL_AGE_LIMIT_MS = 10 * 60 * 1000;
58
67
  */
59
68
  const AUTO_EFFORT = { id: 'auto', name: 'Auto' };
60
69
  /**
61
- * Advertise `auto` in the model directory (and the call-config validation it
62
- * feeds): wrap every registered adapter's `resolveModel` so the returned
63
- * `reasoning.efforts` include the mask level. Idempotent per adapter.
70
+ * The `low` level, advertised only for configurer-confirmed models whose
71
+ * adapter predates dsh rc.7 (efforts list without `low`). Advertising it makes
72
+ * the selector show Low and the harness request validation admit the
73
+ * passthrough; the adapter must serialize it (pi-ai openai-completions does,
74
+ * e.g. via `thinkingFormat: qwen` → enable_thinking + thinking_budget).
75
+ */
76
+ const LOW_EFFORT = { id: 'low', name: 'Low' };
77
+ /**
78
+ * Advertise `auto` (and, for configurer-confirmed rc.6-era models, `low`) in
79
+ * the model directory: wrap every registered adapter's `resolveModel` so the
80
+ * returned `reasoning.efforts` include the extra levels. Idempotent per
81
+ * adapter. `auto` is a mask the plugin resolves per request; `low` is only
82
+ * added when the model override confirms the level, so rc.7+ models (which
83
+ * already advertise low) and unconfirmed models stay untouched.
84
+ *
85
+ * A thinking model WITHOUT effort support (Qwen3.6-style, per the llm-pi-ai
86
+ * config: `reasoningEfforts` present but `compat.supportsReasoningEffort` not
87
+ * true) gets its selector collapsed to a plain On/Off toggle: `off` disables
88
+ * thinking, `on` maps to the `high` level, which pi-ai serializes as
89
+ * `enable_thinking: true` under `thinkingFormat: qwen`. No auto/low masks are
90
+ * offered for these — there is nothing to schedule.
64
91
  * @param llm - the resolved `llm` service, when present.
92
+ * @param overrideFor - model override lookup, keyed `provider/model`.
93
+ * @param piAiFor - llm-pi-ai config capability lookup, keyed `provider/model`.
65
94
  */
66
- function advertiseAutoEffort(llm) {
95
+ function advertiseModelCapability(llm, overrideFor, piAiFor) {
67
96
  for (const registration of llm?.adapters?.values() ?? []) {
68
97
  const adapter = registration.adapter;
69
98
  const original = adapter.resolveModel.bind(adapter);
70
99
  adapter.resolveModel = async (provider, model, signal) => {
71
100
  const info = await original(provider, model, signal);
72
101
  const reasoning = info.reasoning;
73
- if (reasoning !== undefined && !reasoning.efforts?.some((effort) => effort.id === 'auto')) {
74
- info.reasoning = { ...reasoning, efforts: [...(reasoning.efforts ?? []), AUTO_EFFORT] };
102
+ if (reasoning === undefined)
103
+ return info;
104
+ const piCap = piAiFor(provider, model);
105
+ if (piCap?.thinkingOn === true && piCap.supportsEffort === false) {
106
+ // Toggle-only model (Qwen3.6 / mimo-v2.5 style): the selector shows
107
+ // Off/On. The On pick MUST be a level the provider's own request path
108
+ // accepts — pi-ai resolves only its fixed seven levels and rejects
109
+ // anything else per stream (`UNSUPPORTED_REASONING_EFFORT`). `high` is
110
+ // that level: because the model declares supportsReasoningEffort:
111
+ // false, pi-ai serializes a non-off effort as enable_thinking only —
112
+ // no reasoning_effort is sent, which is exactly the toggle semantics.
113
+ info.reasoning = {
114
+ ...reasoning,
115
+ efforts: [
116
+ { id: 'off', name: 'Off' },
117
+ { id: 'high', name: 'On' },
118
+ ],
119
+ };
120
+ return info;
121
+ }
122
+ const efforts = [...(reasoning.efforts ?? [])];
123
+ if (!efforts.some(effort => effort.id === 'auto'))
124
+ efforts.push(AUTO_EFFORT);
125
+ const override = overrideFor(provider, model);
126
+ if (override?.efforts !== undefined
127
+ && override.efforts !== false
128
+ && override.efforts.includes('low')
129
+ && !efforts.some(effort => effort.id === 'low')) {
130
+ efforts.push(LOW_EFFORT);
75
131
  }
132
+ info.reasoning = { ...reasoning, efforts };
76
133
  return info;
77
134
  };
78
135
  }
79
136
  }
137
+ /**
138
+ * The providers currently taken over by dsh-llm-openai-completions, read
139
+ * lazily from the live `llm-openai-completions` namespace. `null` when the
140
+ * namespace is unregistered (adapter plugin absent). Toggle folding and effort
141
+ * injection apply only to routes inside this list; everything else keeps
142
+ * pi-ai's native reasoning semantics.
143
+ */
144
+ function takeoverOf(ctx) {
145
+ const settings = ctx.get('settings');
146
+ const section = settings?.get?.(TAKEOVER_NAMESPACE);
147
+ return takeoverProvidersOf(section);
148
+ }
149
+ /**
150
+ * The llm-pi-ai posture of one model, read from the live settings namespace
151
+ * (the capability card writes `reasoningEfforts` and `compat` there). Absent
152
+ * when the route/model is not configured.
153
+ *
154
+ * A model is toggle-only (Off/On, no effort levels) only when BOTH the model
155
+ * declares a thinking toggle (reasoningEfforts table, no
156
+ * supportsReasoningEffort) AND the route is taken over by the
157
+ * openai-completions adapter (it is in the `llm-openai-completions` list).
158
+ * A route OUTSIDE the takeover list is served by pi-ai with its native
159
+ * reasoning semantics — off/high stay visible and pi-ai validates the effort —
160
+ * so it is NOT folded into a toggle here.
161
+ */
162
+ function piAiPosture(ctx, provider, model, takeover) {
163
+ const settings = ctx.get('settings');
164
+ const section = settings?.get?.('llm-pi-ai');
165
+ const entry = section?.providers?.[provider]?.models?.find(candidate => candidate['id'] === model);
166
+ if (entry === undefined)
167
+ return undefined;
168
+ const efforts = entry['reasoningEfforts'];
169
+ const compat = entry['compat'];
170
+ const thinkingOn = typeof efforts === 'object' && efforts !== null && !Array.isArray(efforts);
171
+ const supportsEffort = typeof compat === 'object' && compat !== null
172
+ && compat['supportsReasoningEffort'] === true;
173
+ // Toggle folding is a takeover-list concern: only the openai-completions
174
+ // adapter's routes get the Off/On treatment. pi-ai-served routes keep their
175
+ // native effort levels (off/high visible).
176
+ const toggled = takeover !== null && takeover.includes(provider);
177
+ return { thinkingOn: thinkingOn && toggled, supportsEffort };
178
+ }
179
+ const CAPABILITY_CACHE_KEY_SEPARATOR = '\u0000';
180
+ /** A model that cannot be resolved is treated as non-reasoning: never inject. */
181
+ const UNRESOLVABLE_CAPABILITY = { supportsReasoning: false, efforts: [], vision: false, toggleOnly: false };
182
+ /** Runtime model-capability lookup with a per-route cache. */
183
+ function capabilityResolver(ctx) {
184
+ const cache = new Map();
185
+ return {
186
+ async resolve(provider, model) {
187
+ if (typeof provider !== 'string' || typeof model !== 'string')
188
+ return UNRESOLVABLE_CAPABILITY;
189
+ const key = `${provider}${CAPABILITY_CACHE_KEY_SEPARATOR}${model}`;
190
+ const cached = cache.get(key);
191
+ if (cached !== undefined)
192
+ return cached;
193
+ const llm = ctx.get('llm');
194
+ let capability;
195
+ try {
196
+ const info = await llm?.resolveModelInfo?.(provider, model);
197
+ const efforts = info?.reasoning?.efforts?.map(effort => effort.id) ?? [];
198
+ const posture = piAiPosture(ctx, provider, model, takeoverOf(ctx));
199
+ capability = {
200
+ supportsReasoning: reasoningEffortSupported(info?.reasoning),
201
+ efforts,
202
+ vision: Array.isArray(info?.inputModalities) && info.inputModalities.includes('image'),
203
+ toggleOnly: posture?.thinkingOn === true && posture.supportsEffort === false,
204
+ };
205
+ }
206
+ catch {
207
+ capability = UNRESOLVABLE_CAPABILITY;
208
+ }
209
+ cache.set(key, capability);
210
+ return capability;
211
+ },
212
+ clear() {
213
+ cache.clear();
214
+ },
215
+ };
216
+ }
80
217
  /**
81
218
  * Plugin body.
82
219
  * @param ctx - host context carrying the agent-event dispatch.
@@ -101,6 +238,43 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
101
238
  // re-registration.
102
239
  onChange: () => { },
103
240
  });
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.
251
+ let syncTail = Promise.resolve();
252
+ const syncTakeover = () => {
253
+ syncTail = syncTail.then(async () => {
254
+ 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
+ const piAi = settings?.get?.(PI_AI_NAMESPACE);
260
+ const next = nextTakeoverSection(previous, identifyTakeoverProviders(piAi));
261
+ if (next === previous)
262
+ 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);
265
+ }).catch((error) => {
266
+ ctx.logger?.warn?.('[thinking-levels] auto-takeover sync failed (kept previous list)', error);
267
+ });
268
+ };
269
+ // 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();
272
+ const onSyncAny = ctx.on;
273
+ onSyncAny('llm/adapters-updated', () => syncTakeover());
274
+ onSyncAny('settings/document-updated', (ns) => {
275
+ if (ns === PI_AI_NAMESPACE || ns === TAKEOVER_NAMESPACE)
276
+ syncTakeover();
277
+ });
104
278
  // Inject the level decision into every model request of a step.
105
279
  // The 'agent/request' event key is augmented onto cordis Events by the
106
280
  // dsh-agent runtime's generated scope types; the npm package does not
@@ -110,41 +284,62 @@ export function apply(ctx, config = DEFAULT_CONFIG) {
110
284
  // overwrites `reasoningEffort` with the session's selection after `next()`;
111
285
  // registering first keeps this plugin's decision OUTERMOST so it runs last.
112
286
  const on = ctx.on;
287
+ // Model capability snapshots, cached per provider/model and cleared whenever
288
+ // the adapter registry changes (a route's reasoning metadata can move).
289
+ const capability = capabilityResolver(ctx);
113
290
  on('agent/request', async (payload, next) => {
114
291
  const seed = await next();
115
292
  const cfg = current();
116
293
  // `enabled` may flip at runtime through the settings namespace.
117
294
  if (!cfg.enabled)
118
295
  return seed;
119
- const selected = seed.reasoningEffort;
120
- // A wire level picked in the model selector (off/low/high/max) wins — the
121
- // plugin only intervenes for the `auto` mask or when nothing was selected.
122
- if (isEffortId(selected) && selected !== 'auto')
123
- return seed;
124
- // `auto` mask (or an unset/unknown value): resolve through the plugin's
125
- // scheduler, falling back to the configured default level.
126
- const base = selected === 'auto' ? 'auto' : cfg.level;
296
+ // Model-aware guard: never send a reasoning effort to a model that does
297
+ // not advertise one (custom openai-completions routes such as Qwen3.6).
298
+ // Unsupported fields are stripped, not sent; a resolved low/auto schedule
299
+ // only ever reaches models whose metadata admits the level.
300
+ const capabilityFor = await capability.resolve(seed.provider, seed.model);
127
301
  const calls = recentToolCalls(payload.agent);
128
- const level = decideEffort({
302
+ const decision = resolveEffortInjection({
303
+ supportsReasoning: capabilityFor.supportsReasoning,
304
+ seedEffort: seed.reasoningEffort,
305
+ selected: cfg.level,
129
306
  recentCalls: calls,
130
- selected: base,
131
307
  allowDowngrade: cfg.allowDowngrade,
132
308
  allowUpgrade: cfg.allowUpgrade,
309
+ efforts: capabilityFor.efforts,
310
+ toggleOnly: capabilityFor.toggleOnly,
133
311
  });
312
+ if (!decision.inject) {
313
+ // The model cannot take any effort: drop an inherited one so dsh does
314
+ // not reject the request (UNSUPPORTED_REASONING_EFFORT).
315
+ const stripped = { ...seed };
316
+ delete stripped.reasoningEffort;
317
+ ctx.logger?.info?.('[thinking-levels] agent/request: model=%s/%s has no reasoning effort; stripped', String(seed.provider), String(seed.model));
318
+ return stripped;
319
+ }
134
320
  // Summary-only log: individual tool names/arg sizes are workflow metadata
135
321
  // that need not land in the host log; count and decision suffice.
136
- ctx.logger?.info?.('[thinking-levels] agent/request: selected=%s calls=%d => level=%s', String(selected), calls.length, level);
137
- return { ...seed, reasoningEffort: level };
322
+ ctx.logger?.info?.('[thinking-levels] agent/request: model=%s/%s selected=%s calls=%d => level=%s', String(seed.provider), String(seed.model), String(seed.reasoningEffort), calls.length, decision.level);
323
+ return { ...seed, reasoningEffort: decision.level };
138
324
  }, { prepend: true });
139
- // Advertise the `auto` mask in the model directory so the session model
140
- // selector offers it alongside Off/Low/High/Max. Adapters may register after
141
- // this plugin's apply (the load order differs between the CLI and DSH
142
- // Desktop), so the wrapper also re-runs on every `llm/adapters-updated`.
325
+ // Advertise the `auto` mask (and, for configurer-confirmed rc.6-era models,
326
+ // `low`) in the model directory so the session model selector offers them
327
+ // alongside the adapter's native levels. Adapters may register after this
328
+ // plugin's apply (the load order differs between the CLI and DSH Desktop),
329
+ // so the wrapper also re-runs on every `llm/adapters-updated`.
143
330
  const llm = ctx.get('llm');
144
- advertiseAutoEffort(llm);
331
+ const overrideFor = (provider, model) => current().models[`${provider}/${model}`];
332
+ // Read the live llm-pi-ai config for the thinking/effort posture the card
333
+ // wrote there: a model with `reasoningEfforts` but without effort support
334
+ // (Qwen3.6) is collapsed to an On/Off toggle in the selector — but ONLY when
335
+ // the route is taken over by the openai-completions adapter. A pi-ai-served
336
+ // route (e.g. mimo via xiaomi) keeps its native off/high levels.
337
+ const piAiFor = (provider, model) => piAiPosture(ctx, provider, model, takeoverOf(ctx));
338
+ advertiseModelCapability(llm, overrideFor, piAiFor);
145
339
  const onAny = ctx.on;
146
340
  onAny('llm/adapters-updated', () => {
147
- advertiseAutoEffort(ctx.get('llm'));
341
+ capability.clear();
342
+ advertiseModelCapability(ctx.get('llm'), overrideFor, piAiFor);
148
343
  });
149
344
  // Per-tool wall-clock telemetry: log tool/call -> tool/result durations.
150
345
  // Same boundary widening as above (agent/tool is a generated scope event).
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Auto-takeover sync: bridge from dsh-thinking-levels to the
3
+ * dsh-llm-openai-completions adapter plugin.
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).
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.
17
+ *
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.
21
+ * @module dsh-thinking-levels/takeover-sync
22
+ */
23
+ /** The settings namespace owned by dsh-llm-openai-completions. */
24
+ export declare const TAKEOVER_NAMESPACE = "llm-openai-completions";
25
+ /** The settings namespace holding the provider/model configs (llm-pi-ai). */
26
+ export declare const PI_AI_NAMESPACE = "llm-pi-ai";
27
+ /** One model row of the llm-pi-ai section (minimal face). */
28
+ export interface PiAiModelRow {
29
+ id?: unknown;
30
+ reasoningEfforts?: unknown;
31
+ }
32
+ /** One provider profile of the llm-pi-ai section (minimal face). */
33
+ export interface PiAiProviderProfile {
34
+ api?: unknown;
35
+ baseURL?: unknown;
36
+ models?: unknown;
37
+ /** Other profile fields (apiKeyEnv, displayName, …) exist but are unused. */
38
+ [key: string]: unknown;
39
+ }
40
+ /** The llm-pi-ai section slice this module reads. */
41
+ export interface PiAiSection {
42
+ providers?: Record<string, PiAiProviderProfile>;
43
+ }
44
+ /** The llm-openai-completions section this module writes. */
45
+ export interface TakeoverSection {
46
+ enabled: boolean;
47
+ providers: string[];
48
+ }
49
+ /**
50
+ * Whether a provider profile targets a CUSTOM openai-completions gateway:
51
+ * explicit `api: openai-completions`, or a baseURL that is not an official
52
+ * host. Catalog routes without either (e.g. xiaomi via pi-ai discovery) are
53
+ * not custom and are left alone.
54
+ * @param profile - the provider profile slice.
55
+ * @returns true when the route is a custom openai-completions gateway.
56
+ */
57
+ export declare function isCustomOpenAiGateway(profile: PiAiProviderProfile | undefined): boolean;
58
+ /**
59
+ * Whether a provider declares thinking: at least one model row carries a
60
+ * reasoningEfforts table (thinking on). `false` (thinking off) and absent
61
+ * both mean no thinking.
62
+ * @param profile - the provider profile slice.
63
+ * @returns true when any model declares a reasoningEfforts table.
64
+ */
65
+ export declare function declaresThinking(profile: PiAiProviderProfile | undefined): boolean;
66
+ /**
67
+ * Identify the providers that should be taken over by the openai-completions
68
+ * adapter: custom gateway AND thinking declared. Order is stable (the section's
69
+ * own provider order).
70
+ * @param section - the live llm-pi-ai section.
71
+ * @returns the provider ids to add to the takeover list.
72
+ */
73
+ export declare function identifyTakeoverProviders(section: PiAiSection | undefined): string[];
74
+ /**
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
+ */
83
+ export declare function nextTakeoverSection(previous: TakeoverSection | undefined, identified: readonly string[]): TakeoverSection;
84
+ /**
85
+ * The providers the openai-completions adapter is currently set up to take
86
+ * over, from the live `llm-openai-completions` settings namespace. Used to
87
+ * gate thinking-levels' own behavior: a route OUTSIDE the takeover list is
88
+ * served by pi-ai with its native reasoning semantics (off/high visible,
89
+ * pi-ai validates and serializes the effort) and must not be folded into an
90
+ * Off/On toggle or have efforts injected by this plugin.
91
+ * @param section - the live llm-openai-completions section, if registered.
92
+ * @returns the provider ids the adapter will serve, or `null` when the
93
+ * namespace is unregistered (adapter plugin absent).
94
+ */
95
+ export declare function takeoverProvidersOf(section: {
96
+ enabled?: unknown;
97
+ providers?: unknown;
98
+ } | undefined): string[] | null;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Auto-takeover sync: bridge from dsh-thinking-levels to the
3
+ * dsh-llm-openai-completions adapter plugin.
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).
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.
17
+ *
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.
21
+ * @module dsh-thinking-levels/takeover-sync
22
+ */
23
+ /** The settings namespace owned by dsh-llm-openai-completions. */
24
+ export const TAKEOVER_NAMESPACE = 'llm-openai-completions';
25
+ /** The settings namespace holding the provider/model configs (llm-pi-ai). */
26
+ export const PI_AI_NAMESPACE = 'llm-pi-ai';
27
+ /** Hosts that are NOT a custom gateway (official OpenAI-compatible endpoints). */
28
+ const OFFICIAL_HOST_RE = /(?:^|\.)(?:deepseek\.com|openai\.com|openrouter\.ai|anthropic\.com|googleapis\.com|ai\.google\.dev|mistral\.ai|x\.ai)$/i;
29
+ /** Whether a value looks like a declared reasoningEfforts table. */
30
+ function isEffortsTable(value) {
31
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
32
+ }
33
+ /**
34
+ * Whether a provider profile targets a CUSTOM openai-completions gateway:
35
+ * explicit `api: openai-completions`, or a baseURL that is not an official
36
+ * host. Catalog routes without either (e.g. xiaomi via pi-ai discovery) are
37
+ * not custom and are left alone.
38
+ * @param profile - the provider profile slice.
39
+ * @returns true when the route is a custom openai-completions gateway.
40
+ */
41
+ export function isCustomOpenAiGateway(profile) {
42
+ if (profile === undefined)
43
+ return false;
44
+ if (profile.api === 'openai-completions')
45
+ return true;
46
+ const baseURL = profile.baseURL;
47
+ if (typeof baseURL !== 'string' || baseURL.length === 0)
48
+ return false;
49
+ try {
50
+ return !OFFICIAL_HOST_RE.test(new URL(baseURL).hostname);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ /**
57
+ * Whether a provider declares thinking: at least one model row carries a
58
+ * reasoningEfforts table (thinking on). `false` (thinking off) and absent
59
+ * both mean no thinking.
60
+ * @param profile - the provider profile slice.
61
+ * @returns true when any model declares a reasoningEfforts table.
62
+ */
63
+ export function declaresThinking(profile) {
64
+ if (profile === undefined || !Array.isArray(profile.models))
65
+ return false;
66
+ return profile.models.some((row) => {
67
+ if (typeof row !== 'object' || row === null)
68
+ return false;
69
+ return isEffortsTable(row.reasoningEfforts);
70
+ });
71
+ }
72
+ /**
73
+ * Identify the providers that should be taken over by the openai-completions
74
+ * adapter: custom gateway AND thinking declared. Order is stable (the section's
75
+ * own provider order).
76
+ * @param section - the live llm-pi-ai section.
77
+ * @returns the provider ids to add to the takeover list.
78
+ */
79
+ export function identifyTakeoverProviders(section) {
80
+ const providers = section?.providers;
81
+ if (typeof providers !== 'object' || providers === null)
82
+ return [];
83
+ return Object.entries(providers)
84
+ .filter(([, profile]) => isCustomOpenAiGateway(profile) && declaresThinking(profile))
85
+ .map(([id]) => id);
86
+ }
87
+ /**
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.
95
+ */
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);
107
+ }
108
+ if (base.enabled && merged.length === base.providers.length)
109
+ return base;
110
+ return { enabled: true, providers: merged };
111
+ }
112
+ /**
113
+ * The providers the openai-completions adapter is currently set up to take
114
+ * over, from the live `llm-openai-completions` settings namespace. Used to
115
+ * gate thinking-levels' own behavior: a route OUTSIDE the takeover list is
116
+ * served by pi-ai with its native reasoning semantics (off/high visible,
117
+ * pi-ai validates and serializes the effort) and must not be folded into an
118
+ * Off/On toggle or have efforts injected by this plugin.
119
+ * @param section - the live llm-openai-completions section, if registered.
120
+ * @returns the provider ids the adapter will serve, or `null` when the
121
+ * namespace is unregistered (adapter plugin absent).
122
+ */
123
+ export function takeoverProvidersOf(section) {
124
+ if (section === undefined)
125
+ return null;
126
+ if (section.enabled !== true)
127
+ return [];
128
+ if (!Array.isArray(section.providers))
129
+ return [];
130
+ return section.providers.filter((id) => typeof id === 'string');
131
+ }