dsh-model-switch 0.4.56 → 0.4.57

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,334 @@
1
+ import "./tool-allowlist-DlzB5GlQ.js";
2
+ import { t as applyFiberConfig } from "./fiber-hot-update-DrZANcwD.js";
3
+ Object.freeze({
4
+ mode: "subagentMode",
5
+ provider: "subagentProvider",
6
+ model: "subagentModel",
7
+ reasoningEffort: "subagentReasoningEffort"
8
+ });
9
+ Object.freeze({
10
+ provider: "searchProvider",
11
+ model: "searchModel"
12
+ });
13
+ Object.freeze({
14
+ provider: "imageProvider",
15
+ model: "imageModel"
16
+ });
17
+ Object.freeze({
18
+ provider: "autoReviewProvider",
19
+ model: "autoReviewModel"
20
+ });
21
+ Object.freeze({
22
+ enabled: "autoReviewSkipReadOnly",
23
+ tools: "autoReviewAllowlist"
24
+ });
25
+ /** Upstream ceiling enforced by `@deepseek-ai/dsh-timeout` (MAX_TIMER_DELAY_MS). */
26
+ const UPSTREAM_MAX_IDLE_TIMEOUT_MS = 2147483647;
27
+ Object.freeze({
28
+ provider: "compactProvider",
29
+ model: "compactModel"
30
+ });
31
+ Object.freeze({
32
+ provider: "titleProvider",
33
+ model: "titleModel"
34
+ });
35
+ Object.freeze({
36
+ provider: "memoryProvider",
37
+ model: "memoryModel"
38
+ });
39
+ //#endregion
40
+ //#region lib/types/review-timeout.js
41
+ /** Cordis plugin identity; matches the `cordis.patch.yml` insert row id. */
42
+ const name = "model-switch-review-timeout";
43
+ /** This row needs the Host's settings service (for `documentPath` and our ns). */
44
+ const inject = ["settings"];
45
+ /** The pi-ai row whose provider profiles carry `streamIdleTimeoutMs`. */
46
+ const PI_AI_ROW = "llm-pi-ai";
47
+ /** The package the pi-ai row loads; matching by name survives a profile id rename. */
48
+ const PI_AI_PACKAGE = "@deepseek-ai/dsh-llm-pi-ai";
49
+ /** Live state surfaced next to the reviewer card through the capabilities RPC. */
50
+ const reviewTimeoutStatus = {
51
+ configuredMs: void 0,
52
+ applied: [],
53
+ skipped: [],
54
+ /** Providers whose running row was reloaded with the new timeout. */
55
+ hotApplied: [],
56
+ /** Whether the running row took the value, or the next start has to. */
57
+ hot: void 0,
58
+ /** Why the running row did not take the value, when it did not. */
59
+ hotReason: void 0
60
+ };
61
+ /**
62
+ * Resolve the stored setting into concrete write values.
63
+ *
64
+ * Stored values are user intent: absent = follow the provider default, `0` =
65
+ * cancelled (written as the upstream ceiling), anything else is clamped into
66
+ * the upstream-legal range so a hand-edited profile cannot produce a rejected
67
+ * value.
68
+ *
69
+ * @param settings - the plugin's current settings.
70
+ * @returns the write value and the reviewer providers to apply it to.
71
+ */
72
+ function planReviewTimeout(settings) {
73
+ const raw = settings.autoReviewTimeoutMs;
74
+ const timeoutMs = raw === void 0 ? void 0 : raw <= 0 ? UPSTREAM_MAX_IDLE_TIMEOUT_MS : Math.min(Math.floor(raw), UPSTREAM_MAX_IDLE_TIMEOUT_MS);
75
+ const providers = /* @__PURE__ */ new Set();
76
+ const add = (value) => {
77
+ const trimmed = (value ?? "").trim();
78
+ if (trimmed !== "") providers.add(trimmed);
79
+ };
80
+ add(settings.autoReviewProvider);
81
+ for (const group of Object.values(settings.providerGroups ?? {})) add(group.autoReviewProvider);
82
+ return {
83
+ timeoutMs,
84
+ providers: [...providers]
85
+ };
86
+ }
87
+ /** Escape a provider id for use inside a regular expression. */
88
+ function escapeRegExp(value) {
89
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
90
+ }
91
+ /**
92
+ * Set or remove one pi-ai provider's `streamIdleTimeoutMs` in the profile
93
+ * document, touching only that provider's block.
94
+ *
95
+ * The pi-ai row's layout is fixed by its schema: the provider sits at six
96
+ * spaces under `providers:`, its fields at eight. The patch inserts the key at
97
+ * the top of the provider block, replaces it in place, or removes it, and never
98
+ * touches another provider or row.
99
+ *
100
+ * @param text - the full profile document.
101
+ * @param provider - the pi-ai provider id.
102
+ * @param timeoutMs - the value to write, or undefined to remove the key.
103
+ * @returns the patched text and what happened.
104
+ */
105
+ function patchProviderIdleTimeout(text, provider, timeoutMs) {
106
+ const rows = text.split(/(?=^- id: )/m);
107
+ const index = rows.findIndex((row) => new RegExp(`^- id: ${escapeRegExp(PI_AI_ROW)}\\r?$`, "m").test(row.split("\n", 1)[0] ?? ""));
108
+ if (index < 0) return {
109
+ text,
110
+ outcome: "missing-row"
111
+ };
112
+ const row = rows[index];
113
+ const match = new RegExp(`^( {6})(${escapeRegExp(provider)}):(\\r?)$`, "m").exec(row);
114
+ if (match === null) return {
115
+ text,
116
+ outcome: "missing-provider"
117
+ };
118
+ const blockStart = match.index + match[0].length;
119
+ const bodyRe = /\r?\n {0,6}\S/g;
120
+ bodyRe.lastIndex = blockStart;
121
+ const bodyEnd = bodyRe.exec(row)?.index ?? row.length;
122
+ const block = row.slice(blockStart, bodyEnd);
123
+ const idleRe = /^( {8})streamIdleTimeoutMs: *(\d+)(\r?)$/m;
124
+ const idleMatch = idleRe.exec(block);
125
+ if (timeoutMs !== void 0) {
126
+ if (idleMatch !== null) {
127
+ if (Number(idleMatch[2]) === timeoutMs) return {
128
+ text,
129
+ outcome: "unchanged"
130
+ };
131
+ const nextBlock = block.replace(idleRe, `${idleMatch[1]}streamIdleTimeoutMs: ${timeoutMs}${idleMatch[3]}`);
132
+ rows[index] = row.slice(0, blockStart) + nextBlock + row.slice(bodyEnd);
133
+ return {
134
+ text: rows.join(""),
135
+ outcome: "written"
136
+ };
137
+ }
138
+ const nextBlock = `\n streamIdleTimeoutMs: ${timeoutMs}${match[3] === "\r" ? "\r\n" : "\n"}${block.slice(1)}`;
139
+ rows[index] = row.slice(0, blockStart) + nextBlock + row.slice(bodyEnd);
140
+ return {
141
+ text: rows.join(""),
142
+ outcome: "written"
143
+ };
144
+ }
145
+ if (idleMatch === null) return {
146
+ text,
147
+ outcome: "unchanged"
148
+ };
149
+ const removeRe = /^ {8}streamIdleTimeoutMs: *\d+\r?\n/m;
150
+ const withoutLine = removeRe.test(block) ? block.replace(removeRe, "") : block.replace(idleRe, "");
151
+ rows[index] = row.slice(0, blockStart) + withoutLine + row.slice(bodyEnd);
152
+ return {
153
+ text: rows.join(""),
154
+ outcome: "written"
155
+ };
156
+ }
157
+ /**
158
+ * Read a provider's current `streamIdleTimeoutMs` from the document.
159
+ *
160
+ * Used to record the pre-overwrite value so a later reset restores it.
161
+ *
162
+ * @param text - the full profile document.
163
+ * @param provider - the pi-ai provider id.
164
+ * @returns the value, or null when the key is absent.
165
+ */
166
+ function readProviderIdleTimeout(text, provider) {
167
+ const row = text.split(/(?=^- id: )/m).find((candidate) => candidate.startsWith(`- id: llm-pi-ai\n`) || candidate.startsWith(`- id: llm-pi-ai\r\n`));
168
+ if (row === void 0) return null;
169
+ const match = new RegExp(`^ {6}${escapeRegExp(provider)}:\\r?\\n((?: {8}.*\\r?\\n)*)`, "m").exec(row);
170
+ if (match === null) return null;
171
+ const idle = /^ {8}streamIdleTimeoutMs: *(\d+)/m.exec(match[1] ?? "");
172
+ return idle === null ? null : Number(idle[1]);
173
+ }
174
+ /**
175
+ * Build the pi-ai row config with one provider's idle timeout set or removed.
176
+ *
177
+ * Pure: the caller decides whether to hand the result to the loader, and a shape
178
+ * this function does not recognize returns `undefined` instead of a guess.
179
+ *
180
+ * @param config - the row's current config object.
181
+ * @param provider - the pi-ai provider id inside `providers`.
182
+ * @param timeoutMs - the value to set, or undefined to remove the key.
183
+ * @returns the next config, or undefined when the current one is not an object.
184
+ */
185
+ function planProviderConfig(config, provider, timeoutMs) {
186
+ if (config === null || typeof config !== "object" || Array.isArray(config)) return void 0;
187
+ const base = config;
188
+ const providers = base.providers === null || typeof base.providers !== "object" || Array.isArray(base.providers) ? {} : base.providers;
189
+ const nextProvider = { ...providers[provider] === null || typeof providers[provider] !== "object" || Array.isArray(providers[provider]) ? {} : providers[provider] };
190
+ if (timeoutMs === void 0) delete nextProvider.streamIdleTimeoutMs;
191
+ else nextProvider.streamIdleTimeoutMs = timeoutMs;
192
+ return {
193
+ ...base,
194
+ providers: {
195
+ ...providers,
196
+ [provider]: nextProvider
197
+ }
198
+ };
199
+ }
200
+ /**
201
+ * Find the loader row that owns the pi-ai provider profiles.
202
+ *
203
+ * @param loader - the Host loader service, when present.
204
+ * @returns the row entry, or undefined when the profile does not load it.
205
+ */
206
+ function findPiAiEntry(loader) {
207
+ if (loader === void 0 || typeof loader.entries !== "function") return void 0;
208
+ for (const entry of loader.entries()) if (entry.options?.name === PI_AI_PACKAGE || entry.id === "llm-pi-ai") return entry;
209
+ }
210
+ /**
211
+ * Reload the pi-ai row so a changed timeout applies without a Host restart.
212
+ *
213
+ * The document write already happened; this is the runtime half. One reload
214
+ * carries every provider that changed. A reload aborts the provider's in-flight
215
+ * calls, which is why it only runs on an actual value change.
216
+ *
217
+ * @param loader - the Host loader service.
218
+ * @param log - row logger for the one-line report.
219
+ * @param providers - providers whose `streamIdleTimeoutMs` the document write changed.
220
+ * @param timeoutMs - the value the document now carries, or undefined for a reset.
221
+ */
222
+ async function pushHotTimeout(loader, log, providers, timeoutMs) {
223
+ const entry = findPiAiEntry(loader);
224
+ if (entry === void 0) {
225
+ reviewTimeoutStatus.hot = "restart-required";
226
+ reviewTimeoutStatus.hotReason = "the pi-ai row is not loaded";
227
+ return;
228
+ }
229
+ let config = entry.options?.config;
230
+ for (const provider of providers) {
231
+ const next = planProviderConfig(config, provider, timeoutMs);
232
+ if (next === void 0) {
233
+ reviewTimeoutStatus.hot = "restart-required";
234
+ reviewTimeoutStatus.hotReason = "the pi-ai row config is not an object";
235
+ return;
236
+ }
237
+ config = next;
238
+ }
239
+ const result = await applyFiberConfig(entry, config);
240
+ const label = timeoutMs === void 0 ? "reset (provider defaults restored)" : `${timeoutMs}ms`;
241
+ if (result.outcome === "updated") {
242
+ reviewTimeoutStatus.hot = "applied";
243
+ reviewTimeoutStatus.hotReason = void 0;
244
+ for (const provider of providers) if (!reviewTimeoutStatus.hotApplied.includes(provider)) reviewTimeoutStatus.hotApplied.push(provider);
245
+ log.info(`model-switch: reloaded ${PI_AI_ROW} so the review timeout (${label}) applies now to [${providers.join(", ")}]; its in-flight calls were dropped`);
246
+ return;
247
+ }
248
+ reviewTimeoutStatus.hot = "restart-required";
249
+ reviewTimeoutStatus.hotReason = result.outcome === "failed" ? result.error ?? "reload failed" : result.outcome === "no-fiber" ? "the pi-ai row has no live instance" : "the pi-ai row is mid-transition";
250
+ if (result.outcome === "failed") log.warn(`model-switch: the pi-ai reload for the review timeout failed (${reviewTimeoutStatus.hotReason}); the value applies after a Host restart`);
251
+ }
252
+ /**
253
+ * Row entry point: apply the configured timeout to the reviewer providers'
254
+ * pi-ai profiles in the profile document.
255
+ *
256
+ * Every failure is contained and logged; a broken document must never take the
257
+ * Host down. The write is idempotent: replays find the value already in place
258
+ * and do nothing.
259
+ *
260
+ * @param ctx - this row's context.
261
+ */
262
+ function apply(outer) {
263
+ outer.inject(["modelSwitch"], (ctx) => {
264
+ const runtime = ctx.modelSwitch;
265
+ const log = ctx.logger;
266
+ const execute = async () => {
267
+ reviewTimeoutStatus.configuredMs = void 0;
268
+ reviewTimeoutStatus.applied = [];
269
+ reviewTimeoutStatus.skipped = [];
270
+ reviewTimeoutStatus.hotApplied = [];
271
+ reviewTimeoutStatus.hot = void 0;
272
+ reviewTimeoutStatus.hotReason = void 0;
273
+ const settings = runtime.currentSettings();
274
+ const plan = planReviewTimeout(settings);
275
+ reviewTimeoutStatus.configuredMs = settings.autoReviewTimeoutMs;
276
+ if (plan.providers.length === 0) return;
277
+ const forms = ctx.get("settings", true);
278
+ const documentPath = forms?.documentPath;
279
+ if (forms === void 0 || typeof documentPath !== "string" || documentPath === "") {
280
+ reviewTimeoutStatus.skipped.push(...plan.providers);
281
+ log.warn("model-switch: no profile document is reachable; the review timeout write is skipped");
282
+ return;
283
+ }
284
+ try {
285
+ const { readFile, writeFile } = await import("node:fs/promises");
286
+ let text = await readFile(documentPath, "utf8");
287
+ let changed = false;
288
+ const changedProviders = [];
289
+ for (const provider of plan.providers) {
290
+ const patched = patchProviderIdleTimeout(text, provider, plan.timeoutMs);
291
+ if (patched.outcome === "written") {
292
+ text = patched.text;
293
+ changed = true;
294
+ changedProviders.push(provider);
295
+ }
296
+ if (patched.outcome === "written" || patched.outcome === "unchanged") reviewTimeoutStatus.applied.push(provider);
297
+ else reviewTimeoutStatus.skipped.push(provider);
298
+ }
299
+ if (changed) await writeFile(documentPath, text, "utf8");
300
+ log.info(`model-switch: review timeout ${plan.timeoutMs === void 0 ? "reset (provider defaults restored)" : `${plan.timeoutMs}ms`} applied to [${reviewTimeoutStatus.applied.join(", ")}]; skipped [${reviewTimeoutStatus.skipped.join(", ")}]`);
301
+ if (changedProviders.length > 0) pushHotTimeout(ctx.get("loader", false), log, changedProviders, plan.timeoutMs);
302
+ } catch (cause) {
303
+ log.warn(`model-switch: the review timeout write failed (${String(cause)})`);
304
+ }
305
+ };
306
+ let pending;
307
+ const run = () => {
308
+ if (pending !== void 0) return pending;
309
+ const next = execute().finally(() => {
310
+ if (pending === next) pending = void 0;
311
+ });
312
+ pending = next;
313
+ return next;
314
+ };
315
+ run();
316
+ const lateSweep = setTimeout(() => {
317
+ run();
318
+ }, 1500);
319
+ const offService = ctx.on("internal/service", (name) => {
320
+ if (name === "settings") run();
321
+ });
322
+ ctx.effect(function* () {
323
+ yield () => {
324
+ offService();
325
+ clearTimeout(lateSweep);
326
+ };
327
+ yield ctx.on("model-switch/settings-update", () => {
328
+ run();
329
+ });
330
+ }, "model-switch: keep the review timeout write aligned with the settings");
331
+ });
332
+ }
333
+ //#endregion
334
+ export { name as a, planReviewTimeout as c, inject as i, readProviderIdleTimeout as l, apply as n, patchProviderIdleTimeout as o, findPiAiEntry as r, planProviderConfig as s, PI_AI_ROW as t, reviewTimeoutStatus as u };
@@ -1,2 +1,2 @@
1
- import { a as name, c as planReviewTimeout, i as inject, l as readProviderIdleTimeout, n as apply, o as patchProviderIdleTimeout, r as findPiAiEntry, s as planProviderConfig, t as PI_AI_ROW, u as reviewTimeoutStatus } from "./review-timeout-CKTTDj8g.js";
1
+ import { a as name, c as planReviewTimeout, i as inject, l as readProviderIdleTimeout, n as apply, o as patchProviderIdleTimeout, r as findPiAiEntry, s as planProviderConfig, t as PI_AI_ROW, u as reviewTimeoutStatus } from "./review-timeout-DJJot3kf.js";
2
2
  export { PI_AI_ROW, apply, findPiAiEntry, inject, name, patchProviderIdleTimeout, planProviderConfig, planReviewTimeout, readProviderIdleTimeout, reviewTimeoutStatus };
@@ -284,4 +284,4 @@ export declare function autoReviewGate(gate: OfficialAutoReviewGate, hooks?: {
284
284
  * `./auto-review-takeover.ts` for the choreography and why the yield is
285
285
  * synchronous.
286
286
  */
287
- export declare function apply(ctx: Context): Promise<void>;
287
+ export declare function apply(outer: Context): Promise<void>;
@@ -157,4 +157,4 @@ export declare function installAutomodeCompat(ctx: Context, loader: Loader | und
157
157
  * Row entry point: adapt the third-party row on activation and on remount.
158
158
  * @param ctx - this row's context.
159
159
  */
160
- export declare function apply(ctx: Context): void;
160
+ export declare function apply(outer: Context): void;
@@ -18,6 +18,13 @@ export interface ReviewStatus {
18
18
  readonly hot?: 'applied' | 'restart-required' | undefined;
19
19
  readonly hotReason?: string | undefined;
20
20
  } | undefined;
21
+ /** Memory-plugin adapter state: whether our distillation route reached the plugin. */
22
+ readonly primeMemory?: {
23
+ readonly installed: boolean;
24
+ readonly route?: string | undefined;
25
+ readonly routeSkipped?: string | undefined;
26
+ readonly replays?: number | undefined;
27
+ } | undefined;
21
28
  /** Review-timeout adapter state: the write and the runtime reload behind it. */
22
29
  readonly reviewTimeout?: {
23
30
  readonly configuredMs?: number | undefined;
@@ -31,7 +31,7 @@ import { type DistillChainEntry } from './prime-memory-route.js';
31
31
  export declare const name = "model-switch-prime-memory-compat";
32
32
  export declare const inject: string[];
33
33
  /** Why the adapter stayed out of the way. */
34
- export type PrimeMemoryRouteSkip = 'user-set' | 'no-route';
34
+ export type PrimeMemoryRouteSkip = 'user-set' | 'no-route' | 'no-row' | 'no-service' | 'no-seam' | 'live-rejected';
35
35
  /** Live adapter state, surfaced next to the settings card. */
36
36
  export interface PrimeMemoryCompatStatus {
37
37
  /** Whether at least one write reached the memory plugin's settings. */
@@ -40,6 +40,8 @@ export interface PrimeMemoryCompatStatus {
40
40
  route?: string | undefined;
41
41
  /** Why the route was not written, when it was not. */
42
42
  routeSkipped?: PrimeMemoryRouteSkip | undefined;
43
+ /** How many settings-update replays this adapter has run (diagnostics). */
44
+ replays: number;
43
45
  }
44
46
  /** The state the settings page reads. */
45
47
  export declare const primeMemoryCompatStatus: PrimeMemoryCompatStatus;
@@ -135,6 +137,18 @@ export declare function pushMemoryRoute(ctx: Context, route: {
135
137
  provider: string;
136
138
  model: string;
137
139
  }): Promise<'pushed' | 'absent' | 'rejected'>;
140
+ /**
141
+ * Read the memory plugin's live settings through the RPC its panel posts to.
142
+ *
143
+ * The `settings` forms descriptors are an internal detail of the plugin: on
144
+ * `dsh-prime-memory@0.26.16` this row could not observe them, which skipped every
145
+ * push and left the plugin on its own deployment default. Its RPC is the surface
146
+ * its own panel uses, so reading there keeps the adapter working across plugin
147
+ * releases — and it is what makes the push idempotent across document reloads.
148
+ * @param ctx - this row's context; the host web server supplies the port.
149
+ * @returns The live settings object, or undefined when the seam is unreachable.
150
+ */
151
+ export declare function readMemoryLive(ctx: Context): Promise<unknown>;
138
152
  /**
139
153
  * Install the adapter for the whole profile.
140
154
  *
@@ -130,4 +130,4 @@ export declare function findPiAiEntry(loader: Loader | undefined): Entry | undef
130
130
  *
131
131
  * @param ctx - this row's context.
132
132
  */
133
- export declare function apply(ctx: Context): void;
133
+ export declare function apply(outer: Context): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-model-switch",
3
- "version": "0.4.56",
3
+ "version": "0.4.57",
4
4
  "description": "Explicit model routing plus composer/Plan picker for DeepSeek Harness",
5
5
  "repository": {
6
6
  "type": "git",