dsh-model-switch 0.4.67 → 0.4.69

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/IMPLEMENTATION_PLAN.md +12 -1
  3. package/PRODUCT.md +3 -3
  4. package/README.en.md +17 -19
  5. package/README.md +17 -19
  6. package/cordis.patch.yml +9 -0
  7. package/lib/auto-review-CYvvootQ.js +1079 -0
  8. package/lib/auto-review.js +1 -1
  9. package/lib/automode-compat.js +1 -1
  10. package/lib/client.js +473 -47
  11. package/lib/compaction.js +1 -1
  12. package/lib/index.js +30 -6
  13. package/lib/prime-memory-compat.js +568 -1
  14. package/lib/prime-memory-route-DGUVfogE.js +117 -0
  15. package/lib/review-timeout-FB32BcnO.js +339 -0
  16. package/lib/review-timeout.js +1 -1
  17. package/lib/session-route-CRfpxarI.js +357 -0
  18. package/lib/session-title.js +1 -1
  19. package/lib/subagent-runtime-BgLqMl2z.js +424 -0
  20. package/lib/subagent-runtime-CluWLZio.js +412 -0
  21. package/lib/subagent-runtime-eNKrdb2H.js +424 -0
  22. package/lib/subagent-runtime.js +2 -289
  23. package/lib/tool-allowlist-cN9Z1XKn.js +489 -0
  24. package/lib/types/capabilities-rpc.d.ts +7 -0
  25. package/lib/types/client/ModelSwitchSettings.d.ts +6 -3
  26. package/lib/types/client/locales.d.ts +12 -2
  27. package/lib/types/client-contract.d.ts +33 -1
  28. package/lib/types/host-settings.d.ts +11 -0
  29. package/lib/types/prime-memory-compat.d.ts +7 -4
  30. package/lib/types/prime-memory-route.d.ts +22 -0
  31. package/lib/types/provider-group.d.ts +31 -3
  32. package/lib/types/session-route.d.ts +24 -3
  33. package/lib/types/subagent-runtime.d.ts +34 -0
  34. package/lib/types/tool-allowlist.d.ts +13 -0
  35. package/lib/types/vision-router-compat.d.ts +62 -0
  36. package/lib/types/vision-router-route.d.ts +94 -0
  37. package/lib/vision-router-compat-B9bkgJmh.js +312 -0
  38. package/lib/vision-router-compat.js +2 -0
  39. package/package.json +5 -1
package/lib/compaction.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as sessionProviderOf, i as resolveCapabilityRoute } from "./session-route-D8izd8Zd.js";
1
+ import { a as sessionProviderOf, i as resolveCapabilityRoute } from "./session-route-CRfpxarI.js";
2
2
  //#region lib/types/compaction.js
3
3
  /** Official compaction row this module supersedes. */
4
4
  const OFFICIAL_COMPACTION_ROW = "compaction-basic";
package/lib/index.js CHANGED
@@ -1,10 +1,12 @@
1
- import { s as normalizeProviderGroups } from "./session-route-D8izd8Zd.js";
2
- import { r as resolveToolSource, t as DEFAULT_READ_ONLY_TOOLS } from "./tool-allowlist-DJTeApr-.js";
3
- import { i as autoReviewStatus } from "./auto-review-C5cwVyMD.js";
1
+ import { l as normalizeProviderGroups } from "./session-route-CRfpxarI.js";
2
+ import { r as resolveToolSource, t as DEFAULT_READ_ONLY_TOOLS } from "./tool-allowlist-cN9Z1XKn.js";
3
+ import { i as autoReviewStatus } from "./auto-review-CYvvootQ.js";
4
4
  import { ModelSwitchAdapterRegistry } from "./adapter-registry.js";
5
5
  import { automodeCompatView } from "./automode-compat.js";
6
- import { u as reviewTimeoutStatus } from "./review-timeout-BU0BFHoJ.js";
7
- import { l as primeMemoryCompatStatus } from "./prime-memory-compat-X6WlrtaN.js";
6
+ import { s as subagentDiscoveryHintStatus } from "./subagent-runtime-eNKrdb2H.js";
7
+ import { u as reviewTimeoutStatus } from "./review-timeout-FB32BcnO.js";
8
+ import { primeMemoryCompatStatus } from "./prime-memory-compat.js";
9
+ import { a as visionRouterCompatStatus } from "./vision-router-compat-B9bkgJmh.js";
8
10
  import { createRequire } from "node:module";
9
11
  import z from "@deepseek-ai/schemastery";
10
12
  import { Service } from "@deepseek-ai/cordis";
@@ -42,6 +44,9 @@ const Config = z.object({
42
44
  titleModel: z.string().volatile(),
43
45
  memoryProvider: z.string().volatile(),
44
46
  memoryModel: z.string().volatile(),
47
+ memoryReasoningEffort: z.string().volatile(),
48
+ visionProvider: z.string().volatile(),
49
+ visionModel: z.string().volatile(),
45
50
  providerGroups: z.array(z.object({
46
51
  provider: z.string().default(""),
47
52
  compactProvider: z.string().default(""),
@@ -54,7 +59,10 @@ const Config = z.object({
54
59
  titleProvider: z.string().default(""),
55
60
  titleModel: z.string().default(""),
56
61
  memoryProvider: z.string().default(""),
57
- memoryModel: z.string().default("")
62
+ memoryModel: z.string().default(""),
63
+ memoryReasoningEffort: z.string().default(""),
64
+ visionProvider: z.string().default(""),
65
+ visionModel: z.string().default("")
58
66
  })).default([]).volatile()
59
67
  });
60
68
  function readConfig(config) {
@@ -76,6 +84,9 @@ function readConfig(config) {
76
84
  const titleModel = config.titleModel.get();
77
85
  const memoryProvider = config.memoryProvider.get();
78
86
  const memoryModel = config.memoryModel.get();
87
+ const memoryReasoningEffort = config.memoryReasoningEffort.get();
88
+ const visionProvider = config.visionProvider.get();
89
+ const visionModel = config.visionModel.get();
79
90
  const providerGroups = normalizeProviderGroups(config.providerGroups.get());
80
91
  return {
81
92
  subagentMode: config.subagentMode.get(),
@@ -97,6 +108,9 @@ function readConfig(config) {
97
108
  ...titleModel === void 0 || titleModel === "" ? {} : { titleModel },
98
109
  ...memoryProvider === void 0 || memoryProvider === "" ? {} : { memoryProvider },
99
110
  ...memoryModel === void 0 || memoryModel === "" ? {} : { memoryModel },
111
+ ...memoryReasoningEffort === void 0 || memoryReasoningEffort === "" ? {} : { memoryReasoningEffort },
112
+ ...visionProvider === void 0 || visionProvider === "" ? {} : { visionProvider },
113
+ ...visionModel === void 0 || visionModel === "" ? {} : { visionModel },
100
114
  ...Object.keys(providerGroups).length === 0 ? {} : { providerGroups }
101
115
  };
102
116
  }
@@ -550,12 +564,22 @@ function installCapabilitiesRpc(ctx, registry, snapshot) {
550
564
  routeSkipped: primeMemoryCompatStatus.routeSkipped,
551
565
  replays: primeMemoryCompatStatus.replays
552
566
  },
567
+ visionRouter: {
568
+ installed: visionRouterCompatStatus.installed,
569
+ route: visionRouterCompatStatus.route,
570
+ routeSkipped: visionRouterCompatStatus.routeSkipped,
571
+ replays: visionRouterCompatStatus.replays
572
+ },
553
573
  reviewTimeout: {
554
574
  configuredMs: reviewTimeoutStatus.configuredMs,
555
575
  applied: reviewTimeoutStatus.applied,
556
576
  hotApplied: reviewTimeoutStatus.hotApplied,
557
577
  hot: reviewTimeoutStatus.hot,
558
578
  hotReason: reviewTimeoutStatus.hotReason
579
+ },
580
+ subagentDiscoveryHint: {
581
+ installed: subagentDiscoveryHintStatus.installed,
582
+ toolWrapped: subagentDiscoveryHintStatus.toolWrapped
559
583
  }
560
584
  }));
561
585
  const dispose = scope.connection.fetch.register({
@@ -1,2 +1,569 @@
1
- import { a as installPrimeMemoryCompat, c as planPrimeMemoryRoute, d as readMemoryLive, f as writeStaticPin, i as inject, l as primeMemoryCompatStatus, n as chainOf, o as memoryLiveMatchesRoute, r as clearStaticPin, s as name, t as apply, u as pushMemoryRoute } from "./prime-memory-compat-X6WlrtaN.js";
1
+ import { r as memoryRouteOf } from "./session-route-CRfpxarI.js";
2
+ import { i as planDistillChain, n as distillChainPatch, r as isPrimeMemoryRow, t as deploymentDefaultProviderOf } from "./prime-memory-route-DGUVfogE.js";
3
+ //#region lib/types/prime-memory-compat.js
4
+ /**
5
+ * Adapt `dsh-prime-memory`'s distillation route to this plugin's route.
6
+ *
7
+ * The memory plugin resolves its distillation route from its own runtime
8
+ * settings section (`live.distillChain`, legacy `live.distillProvider/Model`,
9
+ * else the deployment default model), and it WRITES that section through the
10
+ * host's settings-forms service:
11
+ *
12
+ * await forms.update('dsh-memory', { live: next })
13
+ *
14
+ * Its row config is read once at plugin init, so patching
15
+ * `entry.options.config.llm.*` afterwards has no effect (verified on 0.2.1-rc.3:
16
+ * the model kept being the deployment default). This adapter therefore writes
17
+ * the same section the plugin itself writes, and only that key:
18
+ *
19
+ * - a chain that is already set and is not the one this adapter wrote counts as
20
+ * user intent and is left alone (`user-set`);
21
+ * - an empty Model Switch route means "leave it alone" (`no-route`);
22
+ * - nothing is persisted by us beyond that section, and no other `live` key
23
+ * (capture, trace, embedding, memory mutation) is touched.
24
+ *
25
+ * The route itself is provider-group based: the group of the deployment default
26
+ * provider (read from the `agent-default-model` row), falling back to the flat
27
+ * memory pair.
28
+ */
29
+ /** Row name and dependencies, mirroring the sibling adapter row. */
30
+ const name = "model-switch-prime-memory-compat";
31
+ const inject = ["loader", "settings"];
32
+ /** The loader row id prime-memory is composed under (fixed by its bundle patch). */
33
+ const MEMORY_ENTRY_ID = "dsh-memory";
34
+ /** The state the settings page reads. */
35
+ const primeMemoryCompatStatus = {
36
+ installed: false,
37
+ replays: 0
38
+ };
39
+ /**
40
+ * Write the memory row's static route into the profile patch itself.
41
+ *
42
+ * `settings.update` only accepts the entry's *live* schema fields, so the static
43
+ * `llm` pin never survives that call. The pin is what `resolveModelRoute` returns
44
+ * first, and it is the only key every distillation layer honours — so it has to be
45
+ * written where the next start reads it: the row config in the profile document.
46
+ * @param documentPath - the profile patch file.
47
+ * @param provider - route provider to pin.
48
+ * @param model - route model to pin.
49
+ * @returns whether the document changed.
50
+ */
51
+ /**
52
+ * Remove this plugin's own static pin from the memory row.
53
+ *
54
+ * `effectiveCfg` (dsh-prime-memory `pipeline/runner.js`) treats a non-empty
55
+ * `cfg.llm.provider + cfg.llm.model` pair as "pinned" and then ignores *both* the runtime
56
+ * chain and the legacy `distillProvider`/`distillModel` pair. A pin written earlier — for a
57
+ * host whose live RPC was not ready yet — is therefore not harmless: it keeps winning over
58
+ * every later live push, which is exactly the "the card changed, the calls did not" report.
59
+ * Once a live push is confirmed, the pin has to go.
60
+ *
61
+ * @param documentPath - the profile patch document that holds the memory row.
62
+ * @returns what happened, so the caller can log it without guessing.
63
+ */
64
+ async function clearStaticPin(documentPath) {
65
+ const { readFile, writeFile } = await import("node:fs/promises");
66
+ let text;
67
+ try {
68
+ text = await readFile(documentPath, "utf8");
69
+ } catch {
70
+ return "missing";
71
+ }
72
+ const rows = text.split(/(?=^- id: )/m);
73
+ const index = rows.findIndex((row) => /^- id: dsh-memory\r?\n/.test(row));
74
+ if (index < 0) return "missing";
75
+ const row = rows[index];
76
+ const trimmed = row.replace(/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m, "");
77
+ if (trimmed === row) return "absent";
78
+ rows[index] = trimmed;
79
+ try {
80
+ await writeFile(documentPath, rows.join(""), "utf8");
81
+ } catch {
82
+ return "missing";
83
+ }
84
+ return "cleared";
85
+ }
86
+ async function writeStaticPin(documentPath, provider, model) {
87
+ const { readFile, writeFile } = await import("node:fs/promises");
88
+ let text;
89
+ try {
90
+ text = await readFile(documentPath, "utf8");
91
+ } catch {
92
+ return "missing";
93
+ }
94
+ const rows = text.split(/(?=^- id: )/m);
95
+ const index = rows.findIndex((row) => /^- id: dsh-memory\r?\n/.test(row));
96
+ if (index < 0) return "missing";
97
+ const row = rows[index];
98
+ const desired = ` llm:\n provider: ${provider}\n model: ${model}\n`;
99
+ let next;
100
+ if (/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m.test(row)) next = row.replace(/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m, desired);
101
+ else if (/^ {2}config:\r?\n/m.test(row)) next = row.replace(/^ {2}config:\r?\n/m, ` config:\n${desired}`);
102
+ else next = row.replace(/^- id: dsh-memory\r?\n/m, `- id: dsh-memory\n config:\n${desired}`);
103
+ if (next === row) return "unchanged";
104
+ rows[index] = next;
105
+ try {
106
+ await writeFile(documentPath, rows.join(""), "utf8");
107
+ } catch {
108
+ return "missing";
109
+ }
110
+ return "written";
111
+ }
112
+ /** A non-blank string. */
113
+ function text(value) {
114
+ return typeof value === "string" ? value.trim() : "";
115
+ }
116
+ /** Read a value as a plain record. */
117
+ function asRecord(value) {
118
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
119
+ }
120
+ /**
121
+ * The distillation chain a settings section currently carries.
122
+ *
123
+ * Accepts the chain form and the legacy provider/model pair, so a user who set
124
+ * the old two fields is still recognised as user intent.
125
+ * @param section - the `live` section (or a whole settings view) to read.
126
+ * @returns The chain entries; empty when nothing is set.
127
+ */
128
+ function chainOf(section) {
129
+ const live = asRecord(section);
130
+ if (live === void 0) return [];
131
+ const chain = live.distillChain;
132
+ if (Array.isArray(chain)) {
133
+ const entries = [];
134
+ for (const item of chain) {
135
+ const entry = asRecord(item);
136
+ const provider = text(entry?.provider);
137
+ const model = text(entry?.model);
138
+ if (provider === "" || model === "") continue;
139
+ const effort = text(entry?.reasoningEffort);
140
+ entries.push(effort === "" ? {
141
+ provider,
142
+ model
143
+ } : {
144
+ provider,
145
+ model,
146
+ reasoningEffort: effort
147
+ });
148
+ }
149
+ return entries;
150
+ }
151
+ const provider = text(live.distillProvider);
152
+ const model = text(live.distillModel);
153
+ return provider === "" || model === "" ? [] : [{
154
+ provider,
155
+ model
156
+ }];
157
+ }
158
+ /**
159
+ * Decide the route config one memory row would run with from its config alone.
160
+ *
161
+ * Kept for the settings-free path (a profile that pins `config.llm.*`): the
162
+ * runtime path writes the settings section instead, because the plugin reads its
163
+ * config only at init.
164
+ * @param config - the row's current config (any JSON-ish value).
165
+ * @param route - this plugin's distillation route; an incomplete pair counts as unset.
166
+ * @param adoptedRoute - a `provider/model` this adapter wrote on an earlier pass.
167
+ * @returns The config to install, whether it changed, and what was applied.
168
+ */
169
+ function planPrimeMemoryRoute(config, route, adoptedRoute) {
170
+ const base = asRecord(config);
171
+ if (base === void 0) return {
172
+ config: {},
173
+ changed: false,
174
+ skipped: "no-route"
175
+ };
176
+ const llm = asRecord(base.llm) ?? {};
177
+ const declaredProvider = text(llm.provider);
178
+ const declaredModel = text(llm.model);
179
+ const declaredRoute = declaredProvider !== "" && declaredModel !== "" ? `${declaredProvider}/${declaredModel}` : void 0;
180
+ if (!(declaredRoute !== void 0 && adoptedRoute !== void 0 && declaredRoute === adoptedRoute) && (declaredProvider !== "" || declaredModel !== "")) return {
181
+ config: base,
182
+ changed: false,
183
+ skipped: "user-set"
184
+ };
185
+ const provider = text(route?.provider);
186
+ const model = text(route?.model);
187
+ if (provider === "" || model === "") return {
188
+ config: base,
189
+ changed: false,
190
+ skipped: "no-route"
191
+ };
192
+ return {
193
+ config: {
194
+ ...base,
195
+ llm: {
196
+ ...llm,
197
+ provider,
198
+ model
199
+ }
200
+ },
201
+ changed: true,
202
+ route: `${provider}/${model}`
203
+ };
204
+ }
205
+ /** The endpoint the memory plugin registers for its own runtime settings writes. */
206
+ const MEMORY_RPC_PATH = "/dsh-memory/rpc/settings-set";
207
+ /** One layer-chain entry of the push payload; the effort rides only when set. */
208
+ function layerEntryOf(route) {
209
+ const effort = route.reasoningEffort ?? "";
210
+ return effort === "" ? {
211
+ provider: route.provider,
212
+ model: route.model
213
+ } : {
214
+ provider: route.provider,
215
+ model: route.model,
216
+ reasoningEffort: effort
217
+ };
218
+ }
219
+ /**
220
+ * Whether the memory row's live section already carries exactly our route.
221
+ *
222
+ * The RPC write path persists the live section to the profile document on every
223
+ * call, and a document change reloads the composition — so pushing an unchanged
224
+ * route re-triggers this adapter forever (a ~6 s recompose loop, observed with
225
+ * `dsh-prime-memory@0.26.10`). Comparing first is what makes the push idempotent
226
+ * across reloads. The reasoning effort compares on both the global field and
227
+ * every layer entry; the plugin's schema defaults both to `''` (auto).
228
+ *
229
+ * @param value - the memory row's live settings object, as the forms describe it.
230
+ * @param provider - route provider to compare against.
231
+ * @param model - route model to compare against.
232
+ * @param effort - route reasoning effort to compare against; undefined means auto.
233
+ * @returns true when a push would change nothing.
234
+ */
235
+ function memoryLiveMatchesRoute(value, provider, model, effort) {
236
+ const outer = value === null || typeof value !== "object" ? void 0 : value;
237
+ if (outer === void 0) return false;
238
+ const inner = outer.live;
239
+ const live = inner !== null && typeof inner === "object" ? inner : outer;
240
+ if (live.distillProvider !== provider || live.distillModel !== model) return false;
241
+ const wanted = effort ?? "";
242
+ if ((typeof live.reasoningEffort === "string" ? live.reasoningEffort : "") !== wanted) return false;
243
+ const chain = live.distillChain;
244
+ if (Array.isArray(chain) && chain.length !== 0) return false;
245
+ const layers = live.distillLayerChains;
246
+ if (layers === null || typeof layers !== "object") return false;
247
+ for (const key of [
248
+ "l1",
249
+ "l2",
250
+ "l3"
251
+ ]) {
252
+ const layer = layers[key];
253
+ if (!Array.isArray(layer) || layer.length !== 1) return false;
254
+ const first = layer[0];
255
+ if (first === void 0 || first.provider !== provider || first.model !== model) return false;
256
+ if ((typeof first.reasoningEffort === "string" ? first.reasoningEffort : "") !== wanted) return false;
257
+ }
258
+ return true;
259
+ }
260
+ /**
261
+ * Hand the route to the memory plugin through the RPC it registers for its own
262
+ * settings page.
263
+ *
264
+ * Writing the config document (what `settings.update` does) only changes what the
265
+ * next start reads; the plugin resolves its route from the runtime settings object
266
+ * it built at `apply`. This endpoint is the documented runtime write path — the
267
+ * same one its own "distillation parameters" panel posts to — so it takes effect
268
+ * without a restart, which is exactly what a provider switch needs.
269
+ */
270
+ async function pushMemoryRoute(ctx, route) {
271
+ const server = ctx.get("webServer", false);
272
+ const port = server?.port ?? server?.address?.port;
273
+ if (typeof port !== "number" || port <= 0) return "absent";
274
+ try {
275
+ const response = await fetch(`http://127.0.0.1:${port}${MEMORY_RPC_PATH}`, {
276
+ method: "POST",
277
+ headers: { "content-type": "application/json" },
278
+ body: JSON.stringify({
279
+ distillChain: [],
280
+ distillLayerChains: {
281
+ l1: [layerEntryOf(route)],
282
+ l2: [layerEntryOf(route)],
283
+ l3: [layerEntryOf(route)]
284
+ },
285
+ distillProvider: route.provider,
286
+ distillModel: route.model,
287
+ reasoningEffort: route.reasoningEffort ?? ""
288
+ })
289
+ });
290
+ if (response.status === 404 || response.status === 405 || response.status === 403) return "absent";
291
+ return response.ok ? "pushed" : "rejected";
292
+ } catch {
293
+ return "absent";
294
+ }
295
+ }
296
+ /** The endpoint the memory plugin registers for its own runtime settings reads. */
297
+ const MEMORY_RPC_GET_PATH = "/dsh-memory/rpc/settings-get";
298
+ /**
299
+ * Read the memory plugin's live settings through the RPC its panel posts to.
300
+ *
301
+ * The `settings` forms descriptors are an internal detail of the plugin: on
302
+ * `dsh-prime-memory@0.26.16` this row could not observe them, which skipped every
303
+ * push and left the plugin on its own deployment default. Its RPC is the surface
304
+ * its own panel uses, so reading there keeps the adapter working across plugin
305
+ * releases — and it is what makes the push idempotent across document reloads.
306
+ * @param ctx - this row's context; the host web server supplies the port.
307
+ * @returns The live settings object, or undefined when the seam is unreachable.
308
+ */
309
+ async function readMemoryLive(ctx) {
310
+ const server = ctx.get("webServer", false);
311
+ const port = server?.port ?? server?.address?.port;
312
+ if (typeof port !== "number" || port <= 0) return void 0;
313
+ try {
314
+ const response = await fetch(`http://127.0.0.1:${port}${MEMORY_RPC_GET_PATH}`, {
315
+ method: "POST",
316
+ headers: { "content-type": "application/json" },
317
+ body: JSON.stringify({ method: "settings-get" })
318
+ });
319
+ if (!response.ok) return void 0;
320
+ return (await response.json())?.value?.settings;
321
+ } catch {
322
+ return;
323
+ }
324
+ }
325
+ /** The `settings` service the memory plugin itself writes through. */
326
+ function formsOf(ctx) {
327
+ try {
328
+ return ctx.get("settings", false);
329
+ } catch {
330
+ return;
331
+ }
332
+ }
333
+ /** Live attempts to spend before falling back to the static pin. */
334
+ const PIN_AFTER_ATTEMPTS = 4;
335
+ /**
336
+ * Install the adapter for the whole profile.
337
+ *
338
+ * Writes the memory plugin's own `live` section on activation, on every
339
+ * `loader/patch-context`, on `loader/entry-init`, once more after a short delay
340
+ * (a bundle-inserted row is often composed after this one), and again whenever
341
+ * this plugin's settings change.
342
+ * @param ctx - this row's context.
343
+ * @param loader - the loader service, when present.
344
+ * @param routeOf - resolves this plugin's distillation route for one settings snapshot.
345
+ * @returns The disposer and a replay hook.
346
+ */
347
+ function installPrimeMemoryCompat(ctx, loader, routeOf) {
348
+ /** The route this adapter wrote last, so it may replace its own value only. */
349
+ let adoptedRoute;
350
+ let pending;
351
+ let attempt = 0;
352
+ const timers = [];
353
+ const primeMemoryEntry = () => {
354
+ for (const entry of loader?.entries?.() ?? []) if (isPrimeMemoryRow(entry)) return entry;
355
+ };
356
+ const memoryRowPresent = () => primeMemoryEntry() !== void 0;
357
+ /** The live section the memory plugin registered, read back through the host. */
358
+ const sectionOf = (forms) => {
359
+ try {
360
+ return (forms.describe?.({ redactSecrets: true }) ?? []).find((item) => item.ns === MEMORY_ENTRY_ID);
361
+ } catch {
362
+ return;
363
+ }
364
+ };
365
+ const scheduleRetry = () => {
366
+ if (attempt >= 8) return;
367
+ const delay = Math.min(4e3, 200 * 2 ** attempt);
368
+ attempt += 1;
369
+ const timer = setTimeout(() => {
370
+ run();
371
+ }, delay);
372
+ timer.unref?.();
373
+ timers.push(timer);
374
+ };
375
+ /**
376
+ * Last resort for a host whose live seams never accept the route.
377
+ *
378
+ * Writing the static pin disables every live form (`pinned` in `effectiveCfg`), so it must
379
+ * not happen while the live attempts still have a chance: a pin written on a slow start is
380
+ * what kept overriding later pushes. It therefore waits for the retry budget to run out.
381
+ *
382
+ * @param forms - the settings service describing the memory row.
383
+ * @param provider - route provider to pin.
384
+ * @param model - route model to pin.
385
+ * @param wanted - `provider/model`, for the log line.
386
+ */
387
+ const pinAsFallback = async (forms, provider, model, wanted) => {
388
+ if (attempt < PIN_AFTER_ATTEMPTS) {
389
+ scheduleRetry();
390
+ return;
391
+ }
392
+ const documentPath = forms.documentPath;
393
+ if (typeof documentPath !== "string" || documentPath === "") return;
394
+ try {
395
+ if (await writeStaticPin(documentPath, provider, model) === "written") ctx.logger.info(`model-switch: pinned the dsh-prime-memory distillation route to ${wanted} after ${attempt} live attempts (applies from the next start)`);
396
+ } catch (cause) {
397
+ ctx.logger.warn(`model-switch: could not pin the dsh-prime-memory route (${String(cause)})`);
398
+ }
399
+ };
400
+ /**
401
+ * Drop a pin left over from an earlier release.
402
+ *
403
+ * A static `llm.provider/model` pin sets `pinned`, which makes the plugin's
404
+ * `effectiveCfg` ignore the chain *and* the live pair, so the live route decides
405
+ * nothing on that host until the pin is gone.
406
+ * @param forms - the settings seam, when this host exposes it.
407
+ */
408
+ const clearStalePin = async (forms) => {
409
+ const pinnedDocument = forms?.documentPath;
410
+ if (typeof pinnedDocument !== "string" || pinnedDocument === "") return;
411
+ try {
412
+ if (await clearStaticPin(pinnedDocument) === "cleared") ctx.logger.info("model-switch: removed the stale dsh-prime-memory static pin; the live route decides now");
413
+ } catch (cause) {
414
+ ctx.logger.warn(`model-switch: could not clear the dsh-prime-memory static pin (${String(cause)})`);
415
+ }
416
+ };
417
+ /**
418
+ *
419
+ * The plugin builds that section inside its own `apply` (`settings.register`), so
420
+ * a write issued before that point lands in a section nobody reads — the reason
421
+ * an unverified "write once at mount" pass left it on the deployment default.
422
+ * Writing only once the section is visible, and verifying by reading the chain
423
+ * back, is what makes this measurable instead of hopeful.
424
+ */
425
+ const run = async () => {
426
+ if (pending !== void 0) return pending;
427
+ if (!memoryRowPresent()) {
428
+ primeMemoryCompatStatus.routeSkipped = "no-row";
429
+ return;
430
+ }
431
+ const route = routeOf();
432
+ const provider = text(route?.provider);
433
+ const model = text(route?.model);
434
+ const effort = text(route?.reasoningEffort);
435
+ if (provider === "" || model === "") {
436
+ primeMemoryCompatStatus.routeSkipped = "no-route";
437
+ return;
438
+ }
439
+ const wanted = `${provider}/${model}`;
440
+ const forms = formsOf(ctx);
441
+ const live = await readMemoryLive(ctx);
442
+ if (live === void 0) {
443
+ primeMemoryCompatStatus.routeSkipped = "no-route";
444
+ scheduleRetry();
445
+ return;
446
+ }
447
+ if (memoryLiveMatchesRoute(live, provider, model, effort)) {
448
+ adoptedRoute = wanted;
449
+ primeMemoryCompatStatus.installed = true;
450
+ primeMemoryCompatStatus.route = wanted;
451
+ delete primeMemoryCompatStatus.routeSkipped;
452
+ await clearStalePin(forms);
453
+ return;
454
+ }
455
+ const declared = chainOf(live);
456
+ const declaredRoute = declared.length > 0 ? `${text(declared[0]?.provider)}/${text(declared[0]?.model)}` : "";
457
+ if (declaredRoute !== "" && declaredRoute !== wanted && declaredRoute !== adoptedRoute) {
458
+ primeMemoryCompatStatus.routeSkipped = "user-set";
459
+ primeMemoryCompatStatus.route = void 0;
460
+ return;
461
+ }
462
+ if (await pushMemoryRoute(ctx, {
463
+ provider,
464
+ model,
465
+ ...effort === "" ? {} : { reasoningEffort: effort }
466
+ }) === "pushed") {
467
+ const after = await readMemoryLive(ctx);
468
+ if (after !== void 0 && memoryLiveMatchesRoute(after, provider, model, effort)) {
469
+ adoptedRoute = wanted;
470
+ attempt = 0;
471
+ primeMemoryCompatStatus.installed = true;
472
+ primeMemoryCompatStatus.route = wanted;
473
+ delete primeMemoryCompatStatus.routeSkipped;
474
+ await clearStalePin(forms);
475
+ return;
476
+ }
477
+ primeMemoryCompatStatus.routeSkipped = "live-rejected";
478
+ }
479
+ if (forms === void 0 || forms.update === void 0 || forms.describe === void 0) {
480
+ primeMemoryCompatStatus.routeSkipped = "no-route";
481
+ scheduleRetry();
482
+ return;
483
+ }
484
+ const section = sectionOf(forms);
485
+ if (section === void 0 || asRecord(section.value) === void 0) {
486
+ await pinAsFallback(forms, provider, model, wanted);
487
+ return;
488
+ }
489
+ const chain = planDistillChain({
490
+ provider,
491
+ model,
492
+ ...effort === "" ? {} : { reasoningEffort: effort }
493
+ }, chainOf(section.value));
494
+ pending = forms.update(MEMORY_ENTRY_ID, distillChainPatch(chain), section.revision).then(async () => {
495
+ const applied = chainOf(sectionOf(forms)?.value);
496
+ if ((applied.length > 0 ? `${text(applied[0]?.provider)}/${text(applied[0]?.model)}` : "") !== wanted) {
497
+ await pinAsFallback(forms, provider, model, wanted);
498
+ return;
499
+ }
500
+ adoptedRoute = wanted;
501
+ attempt = 0;
502
+ primeMemoryCompatStatus.installed = true;
503
+ primeMemoryCompatStatus.route = wanted;
504
+ delete primeMemoryCompatStatus.routeSkipped;
505
+ }).catch(async (cause) => {
506
+ primeMemoryCompatStatus.routeSkipped = "no-route";
507
+ ctx.logger.warn(`model-switch: could not write the dsh-prime-memory distillation route (${String(cause)})`);
508
+ await pinAsFallback(forms, provider, model, wanted);
509
+ }).finally(() => {
510
+ pending = void 0;
511
+ });
512
+ return pending;
513
+ };
514
+ const replay = () => {
515
+ primeMemoryCompatStatus.replays += 1;
516
+ run();
517
+ return true;
518
+ };
519
+ run();
520
+ const offPatch = ctx.on("loader/patch-context", function(first, second) {
521
+ const nextFn = typeof first === "function" ? first : second;
522
+ const candidate = typeof first === "function" ? this : first;
523
+ if (isPrimeMemoryRow(candidate)) run();
524
+ return nextFn === void 0 ? void 0 : nextFn();
525
+ });
526
+ const offInit = ctx.on("loader/entry-init", function(first) {
527
+ const candidate = this ?? first;
528
+ if (candidate !== void 0 && isPrimeMemoryRow(candidate)) run();
529
+ });
530
+ const offService = ctx.on("internal/service", (name) => {
531
+ if (name === "settings") run();
532
+ });
533
+ const lateSweep = setTimeout(() => {
534
+ run();
535
+ }, 1500);
536
+ return {
537
+ dispose: () => {
538
+ offPatch();
539
+ offInit();
540
+ offService();
541
+ clearTimeout(lateSweep);
542
+ for (const timer of timers) clearTimeout(timer);
543
+ },
544
+ replay
545
+ };
546
+ }
547
+ /**
548
+ * Row entry point: adapt the memory plugin on activation and on remount.
549
+ * @param ctx - this row's context.
550
+ */
551
+ function apply(ctx) {
552
+ ctx.inject(["modelSwitch"], (withProvider) => {
553
+ withProvider.inject(["webServer"], (scope) => scope.effect(() => {
554
+ const runtime = scope.modelSwitch;
555
+ const loader = scope.get("loader", false);
556
+ const routeOf = () => memoryRouteOf(runtime.currentSettings(), deploymentDefaultProviderOf(loader));
557
+ const adapter = installPrimeMemoryCompat(scope, loader, routeOf);
558
+ const off = scope.on("model-switch/settings-update", () => {
559
+ if (adapter.replay()) scope.logger.info("model-switch: re-applied the dsh-prime-memory distillation route after a settings change");
560
+ });
561
+ return () => {
562
+ off();
563
+ adapter.dispose();
564
+ };
565
+ }, "model-switch: keep the dsh-prime-memory route aligned with the settings"));
566
+ });
567
+ }
568
+ //#endregion
2
569
  export { apply, chainOf, clearStaticPin, inject, installPrimeMemoryCompat, memoryLiveMatchesRoute, name, planPrimeMemoryRoute, primeMemoryCompatStatus, pushMemoryRoute, readMemoryLive, writeStaticPin };