dsh-model-switch 0.4.43 → 0.4.45

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,495 @@
1
+ import { r as memoryRouteOf } from "./session-route-D8izd8Zd.js";
2
+ //#region lib/types/prime-memory-route.js
3
+ /**
4
+ * Model Switch's adapter to `dsh-prime-memory`'s distillation route.
5
+ *
6
+ * prime-memory owns its distillation route: a `distillChain` in the volatile
7
+ * `live` settings section (`distillProvider`/`distillModel` before 0.x chains
8
+ * existed), read through its own settings handle and committed with
9
+ * `ctx.settings.update('dsh-memory', { live })` — a volatile-only commit that
10
+ * does not remount the plugin. This module only builds the write Model Switch
11
+ * offers; it never runs a distillation call, never rewrites the plugin, and
12
+ * never changes a route the user did not ask to change.
13
+ *
14
+ * All functions here are pure.
15
+ */
16
+ /** The loader row id prime-memory is composed under (fixed by its bundle patch). */
17
+ const PRIME_MEMORY_ENTRY_ID = "dsh-memory";
18
+ /** The package name that identifies the row; the authoritative identity. */
19
+ const PRIME_MEMORY_PACKAGE = "dsh-prime-memory";
20
+ /** A non-blank string; blank values behave exactly like an absent field. */
21
+ function present(value) {
22
+ return typeof value === "string" && value.trim() !== "";
23
+ }
24
+ /**
25
+ * Whether one loader entry is prime-memory.
26
+ *
27
+ * The package name wins over the row id: a profile layer may rename the row,
28
+ * while an unrelated row could recycle the id.
29
+ * @param entry - the loader entry to test.
30
+ * @returns True for prime-memory's row.
31
+ */
32
+ function isPrimeMemoryRow(entry) {
33
+ const name = entry?.options?.name;
34
+ if (present(name)) return name === PRIME_MEMORY_PACKAGE;
35
+ return entry?.options?.id === PRIME_MEMORY_ENTRY_ID;
36
+ }
37
+ /**
38
+ * The chain prime-memory should use, given the route Model Switch wants.
39
+ *
40
+ * The chosen route goes first; the entries prime-memory already had follow in
41
+ * their own order, minus any route that duplicates the chosen one (a duplicate
42
+ * is a guaranteed second failure, not a fallback). An empty chosen route leaves
43
+ * the existing chain untouched.
44
+ * @param primary - the route Model Switch wants first, if any.
45
+ * @param existing - prime-memory's current chain, as read from its settings.
46
+ * @returns The chain to write; empty when neither side has a complete route.
47
+ */
48
+ function planDistillChain(primary, existing) {
49
+ const chain = [];
50
+ const seen = /* @__PURE__ */ new Set();
51
+ const push = (entry) => {
52
+ const key = `${entry.provider}\u0000${entry.model}`;
53
+ if (seen.has(key)) return;
54
+ seen.add(key);
55
+ chain.push(entry);
56
+ };
57
+ if (primary !== void 0 && present(primary.provider) && present(primary.model)) {
58
+ const effort = primary.reasoningEffort;
59
+ push(present(effort) ? {
60
+ provider: primary.provider,
61
+ model: primary.model,
62
+ reasoningEffort: effort
63
+ } : {
64
+ provider: primary.provider,
65
+ model: primary.model
66
+ });
67
+ }
68
+ for (const entry of existing ?? []) {
69
+ if (!present(entry.provider) || !present(entry.model)) continue;
70
+ push(present(entry.reasoningEffort) ? {
71
+ provider: entry.provider,
72
+ model: entry.model,
73
+ reasoningEffort: entry.reasoningEffort
74
+ } : {
75
+ provider: entry.provider,
76
+ model: entry.model
77
+ });
78
+ }
79
+ return chain;
80
+ }
81
+ /**
82
+ * The settings patch that writes one distillation chain.
83
+ *
84
+ * Only the `distillChain` key is produced: prime-memory's `live` section carries
85
+ * unrelated switches (capture, trace, embedding, memory mutation), and a patch
86
+ * naming them would rewrite the user's choices.
87
+ * @param chain - the chain to write.
88
+ * @returns The `live` patch to pass to `ctx.settings.update`.
89
+ */
90
+ function distillChainPatch(chain) {
91
+ return { live: { distillChain: chain } };
92
+ }
93
+ //#endregion
94
+ //#region lib/types/prime-memory-compat.js
95
+ /**
96
+ * Adapt `dsh-prime-memory`'s distillation route to this plugin's route.
97
+ *
98
+ * The memory plugin resolves its distillation route from its own runtime
99
+ * settings section (`live.distillChain`, legacy `live.distillProvider/Model`,
100
+ * else the deployment default model), and it WRITES that section through the
101
+ * host's settings-forms service:
102
+ *
103
+ * await forms.update('dsh-memory', { live: next })
104
+ *
105
+ * Its row config is read once at plugin init, so patching
106
+ * `entry.options.config.llm.*` afterwards has no effect (verified on 0.2.1-rc.3:
107
+ * the model kept being the deployment default). This adapter therefore writes
108
+ * the same section the plugin itself writes, and only that key:
109
+ *
110
+ * - a chain that is already set and is not the one this adapter wrote counts as
111
+ * user intent and is left alone (`user-set`);
112
+ * - an empty Model Switch route means "leave it alone" (`no-route`);
113
+ * - nothing is persisted by us beyond that section, and no other `live` key
114
+ * (capture, trace, embedding, memory mutation) is touched.
115
+ *
116
+ * The route itself is provider-group based: the group of the deployment default
117
+ * provider (read from the `agent-default-model` row), falling back to the flat
118
+ * memory pair.
119
+ */
120
+ /** Row name and dependencies, mirroring the sibling adapter row. */
121
+ const name = "model-switch-prime-memory-compat";
122
+ const inject = [
123
+ "loader",
124
+ "modelSwitch",
125
+ "settings"
126
+ ];
127
+ /** The loader row id prime-memory is composed under (fixed by its bundle patch). */
128
+ const MEMORY_ENTRY_ID = "dsh-memory";
129
+ /** The state the settings page reads. */
130
+ const primeMemoryCompatStatus = { installed: false };
131
+ /**
132
+ * Write the memory row's static route into the profile patch itself.
133
+ *
134
+ * `settings.update` only accepts the entry's *live* schema fields, so the static
135
+ * `llm` pin never survives that call. The pin is what `resolveModelRoute` returns
136
+ * first, and it is the only key every distillation layer honours — so it has to be
137
+ * written where the next start reads it: the row config in the profile document.
138
+ * @param documentPath - the profile patch file.
139
+ * @param provider - route provider to pin.
140
+ * @param model - route model to pin.
141
+ * @returns whether the document changed.
142
+ */
143
+ async function writeStaticPin(documentPath, provider, model) {
144
+ const { readFile, writeFile } = await import("node:fs/promises");
145
+ let text;
146
+ try {
147
+ text = await readFile(documentPath, "utf8");
148
+ } catch {
149
+ return "missing";
150
+ }
151
+ const rows = text.split(/(?=^- id: )/m);
152
+ const index = rows.findIndex((row) => /^- id: dsh-memory\r?\n/.test(row));
153
+ if (index < 0) return "missing";
154
+ const row = rows[index];
155
+ const desired = ` llm:\n provider: ${provider}\n model: ${model}\n`;
156
+ let next;
157
+ if (/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m.test(row)) next = row.replace(/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m, desired);
158
+ else if (/^ {2}config:\r?\n/m.test(row)) next = row.replace(/^ {2}config:\r?\n/m, ` config:\n${desired}`);
159
+ else next = row.replace(/^- id: dsh-memory\r?\n/m, `- id: dsh-memory\n config:\n${desired}`);
160
+ if (next === row) return "unchanged";
161
+ rows[index] = next;
162
+ try {
163
+ await writeFile(documentPath, rows.join(""), "utf8");
164
+ } catch {
165
+ return "missing";
166
+ }
167
+ return "written";
168
+ }
169
+ /** A non-blank string. */
170
+ function text(value) {
171
+ return typeof value === "string" ? value.trim() : "";
172
+ }
173
+ /** Read a value as a plain record. */
174
+ function asRecord(value) {
175
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
176
+ }
177
+ /**
178
+ * The distillation chain a settings section currently carries.
179
+ *
180
+ * Accepts the chain form and the legacy provider/model pair, so a user who set
181
+ * the old two fields is still recognised as user intent.
182
+ * @param section - the `live` section (or a whole settings view) to read.
183
+ * @returns The chain entries; empty when nothing is set.
184
+ */
185
+ function chainOf(section) {
186
+ const live = asRecord(section);
187
+ if (live === void 0) return [];
188
+ const chain = live.distillChain;
189
+ if (Array.isArray(chain)) {
190
+ const entries = [];
191
+ for (const item of chain) {
192
+ const entry = asRecord(item);
193
+ const provider = text(entry?.provider);
194
+ const model = text(entry?.model);
195
+ if (provider === "" || model === "") continue;
196
+ const effort = text(entry?.reasoningEffort);
197
+ entries.push(effort === "" ? {
198
+ provider,
199
+ model
200
+ } : {
201
+ provider,
202
+ model,
203
+ reasoningEffort: effort
204
+ });
205
+ }
206
+ return entries;
207
+ }
208
+ const provider = text(live.distillProvider);
209
+ const model = text(live.distillModel);
210
+ return provider === "" || model === "" ? [] : [{
211
+ provider,
212
+ model
213
+ }];
214
+ }
215
+ /**
216
+ * Decide the route config one memory row would run with from its config alone.
217
+ *
218
+ * Kept for the settings-free path (a profile that pins `config.llm.*`): the
219
+ * runtime path writes the settings section instead, because the plugin reads its
220
+ * config only at init.
221
+ * @param config - the row's current config (any JSON-ish value).
222
+ * @param route - this plugin's distillation route; an incomplete pair counts as unset.
223
+ * @param adoptedRoute - a `provider/model` this adapter wrote on an earlier pass.
224
+ * @returns The config to install, whether it changed, and what was applied.
225
+ */
226
+ function planPrimeMemoryRoute(config, route, adoptedRoute) {
227
+ const base = asRecord(config);
228
+ if (base === void 0) return {
229
+ config: {},
230
+ changed: false,
231
+ skipped: "no-route"
232
+ };
233
+ const llm = asRecord(base.llm) ?? {};
234
+ const declaredProvider = text(llm.provider);
235
+ const declaredModel = text(llm.model);
236
+ const declaredRoute = declaredProvider !== "" && declaredModel !== "" ? `${declaredProvider}/${declaredModel}` : void 0;
237
+ if (!(declaredRoute !== void 0 && adoptedRoute !== void 0 && declaredRoute === adoptedRoute) && (declaredProvider !== "" || declaredModel !== "")) return {
238
+ config: base,
239
+ changed: false,
240
+ skipped: "user-set"
241
+ };
242
+ const provider = text(route?.provider);
243
+ const model = text(route?.model);
244
+ if (provider === "" || model === "") return {
245
+ config: base,
246
+ changed: false,
247
+ skipped: "no-route"
248
+ };
249
+ return {
250
+ config: {
251
+ ...base,
252
+ llm: {
253
+ ...llm,
254
+ provider,
255
+ model
256
+ }
257
+ },
258
+ changed: true,
259
+ route: `${provider}/${model}`
260
+ };
261
+ }
262
+ /** The endpoint the memory plugin registers for its own runtime settings writes. */
263
+ const MEMORY_RPC_PATH = "/dsh-memory/rpc/settings-set";
264
+ /**
265
+ * Hand the route to the memory plugin through the RPC it registers for its own
266
+ * settings page.
267
+ *
268
+ * Writing the config document (what `settings.update` does) only changes what the
269
+ * next start reads; the plugin resolves its route from the runtime settings object
270
+ * it built at `apply`. This endpoint is the documented runtime write path — the
271
+ * same one its own "distillation parameters" panel posts to — so it takes effect
272
+ * without a restart, which is exactly what a provider switch needs.
273
+ */
274
+ async function pushMemoryRoute(ctx, route) {
275
+ const server = ctx.get("webServer", false);
276
+ const port = server?.port ?? server?.address?.port;
277
+ if (typeof port !== "number" || port <= 0) return "absent";
278
+ try {
279
+ const response = await fetch(`http://127.0.0.1:${port}${MEMORY_RPC_PATH}`, {
280
+ method: "POST",
281
+ headers: { "content-type": "application/json" },
282
+ body: JSON.stringify({
283
+ distillChain: [{
284
+ provider: route.provider,
285
+ model: route.model
286
+ }],
287
+ distillLayerChains: {
288
+ l1: [{
289
+ provider: route.provider,
290
+ model: route.model
291
+ }],
292
+ l2: [{
293
+ provider: route.provider,
294
+ model: route.model
295
+ }],
296
+ l3: [{
297
+ provider: route.provider,
298
+ model: route.model
299
+ }]
300
+ },
301
+ distillProvider: "",
302
+ distillModel: "",
303
+ reasoningEffort: ""
304
+ })
305
+ });
306
+ if (response.status === 404 || response.status === 405 || response.status === 403) return "absent";
307
+ return response.ok ? "pushed" : "rejected";
308
+ } catch {
309
+ return "absent";
310
+ }
311
+ }
312
+ /** The `agent-default-model` row's provider: the deployment default. */
313
+ function defaultProviderOf(loader) {
314
+ if (typeof loader?.entries !== "function") return void 0;
315
+ for (const entry of loader.entries()) {
316
+ if (entry.options?.id !== "agent-default-model") continue;
317
+ const provider = text(asRecord(entry.options?.config)?.provider);
318
+ if (provider !== "") return provider;
319
+ }
320
+ }
321
+ /** The `settings` service the memory plugin itself writes through. */
322
+ function formsOf(ctx) {
323
+ try {
324
+ return ctx.get("settings", false);
325
+ } catch {
326
+ return;
327
+ }
328
+ }
329
+ /**
330
+ * Install the adapter for the whole profile.
331
+ *
332
+ * Writes the memory plugin's own `live` section on activation, on every
333
+ * `loader/patch-context`, on `loader/entry-init`, once more after a short delay
334
+ * (a bundle-inserted row is often composed after this one), and again whenever
335
+ * this plugin's settings change.
336
+ * @param ctx - this row's context.
337
+ * @param loader - the loader service, when present.
338
+ * @param routeOf - resolves this plugin's distillation route for one settings snapshot.
339
+ * @returns The disposer and a replay hook.
340
+ */
341
+ function installPrimeMemoryCompat(ctx, loader, routeOf) {
342
+ /** The route this adapter wrote last, so it may replace its own value only. */
343
+ let adoptedRoute;
344
+ let pending;
345
+ let attempt = 0;
346
+ const timers = [];
347
+ const primeMemoryEntry = () => {
348
+ for (const entry of loader?.entries?.() ?? []) if (isPrimeMemoryRow(entry)) return entry;
349
+ };
350
+ const memoryRowPresent = () => primeMemoryEntry() !== void 0;
351
+ /** The live section the memory plugin registered, read back through the host. */
352
+ const sectionOf = (forms) => {
353
+ try {
354
+ return (forms.describe?.({ redactSecrets: true }) ?? []).find((item) => item.ns === MEMORY_ENTRY_ID);
355
+ } catch {
356
+ return;
357
+ }
358
+ };
359
+ const scheduleRetry = () => {
360
+ if (attempt >= 8) return;
361
+ const delay = Math.min(4e3, 200 * 2 ** attempt);
362
+ attempt += 1;
363
+ const timer = setTimeout(() => {
364
+ run();
365
+ }, delay);
366
+ timer.unref?.();
367
+ timers.push(timer);
368
+ };
369
+ /**
370
+ * Write our route into the section the plugin itself reads, then read it back.
371
+ *
372
+ * The plugin builds that section inside its own `apply` (`settings.register`), so
373
+ * a write issued before that point lands in a section nobody reads — the reason
374
+ * an unverified "write once at mount" pass left it on the deployment default.
375
+ * Writing only once the section is visible, and verifying by reading the chain
376
+ * back, is what makes this measurable instead of hopeful.
377
+ */
378
+ const run = async () => {
379
+ if (pending !== void 0) return pending;
380
+ if (!memoryRowPresent()) return;
381
+ const route = routeOf();
382
+ const provider = text(route?.provider);
383
+ const model = text(route?.model);
384
+ if (provider === "" || model === "") {
385
+ primeMemoryCompatStatus.routeSkipped = "no-route";
386
+ return;
387
+ }
388
+ const forms = formsOf(ctx);
389
+ if (forms?.update === void 0 || forms.describe === void 0) {
390
+ primeMemoryCompatStatus.routeSkipped = "no-route";
391
+ scheduleRetry();
392
+ return;
393
+ }
394
+ const wanted = `${provider}/${model}`;
395
+ const pushed = await pushMemoryRoute(ctx, {
396
+ provider,
397
+ model
398
+ });
399
+ if (pushed === "pushed") {
400
+ adoptedRoute = wanted;
401
+ primeMemoryCompatStatus.installed = true;
402
+ primeMemoryCompatStatus.route = wanted;
403
+ delete primeMemoryCompatStatus.routeSkipped;
404
+ }
405
+ const documentPath = forms.documentPath;
406
+ if (typeof documentPath === "string" && documentPath !== "") try {
407
+ if (await writeStaticPin(documentPath, provider, model) === "written") ctx.logger.info(`model-switch: pinned the dsh-prime-memory distillation route to ${wanted} (applies from the next start)`);
408
+ } catch (cause) {
409
+ ctx.logger.warn(`model-switch: could not pin the dsh-prime-memory route (${String(cause)})`);
410
+ }
411
+ if (pushed === "pushed") return;
412
+ const section = sectionOf(forms);
413
+ if (section === void 0 || asRecord(section.value) === void 0) {
414
+ scheduleRetry();
415
+ return;
416
+ }
417
+ const current = chainOf(section.value);
418
+ const declared = current.length > 0 ? `${text(current[0]?.provider)}/${text(current[0]?.model)}` : "";
419
+ if (declared !== "" && declared !== wanted && adoptedRoute !== wanted) {
420
+ primeMemoryCompatStatus.routeSkipped = "user-set";
421
+ primeMemoryCompatStatus.route = void 0;
422
+ return;
423
+ }
424
+ const chain = planDistillChain({
425
+ provider,
426
+ model
427
+ }, current);
428
+ pending = forms.update(MEMORY_ENTRY_ID, distillChainPatch(chain), section.revision).then(() => {
429
+ const applied = chainOf(sectionOf(forms)?.value);
430
+ if ((applied.length > 0 ? `${text(applied[0]?.provider)}/${text(applied[0]?.model)}` : "") !== wanted) {
431
+ scheduleRetry();
432
+ return;
433
+ }
434
+ adoptedRoute = wanted;
435
+ attempt = 0;
436
+ primeMemoryCompatStatus.installed = true;
437
+ primeMemoryCompatStatus.route = wanted;
438
+ delete primeMemoryCompatStatus.routeSkipped;
439
+ }).catch((cause) => {
440
+ primeMemoryCompatStatus.routeSkipped = "no-route";
441
+ ctx.logger.warn(`model-switch: could not write the dsh-prime-memory distillation route (${String(cause)})`);
442
+ scheduleRetry();
443
+ }).finally(() => {
444
+ pending = void 0;
445
+ });
446
+ return pending;
447
+ };
448
+ const replay = () => {
449
+ run();
450
+ return true;
451
+ };
452
+ run();
453
+ const offPatch = ctx.on("loader/patch-context", function(first, second) {
454
+ const nextFn = typeof first === "function" ? first : second;
455
+ if (isPrimeMemoryRow(typeof first === "function" ? this : first)) run();
456
+ return nextFn === void 0 ? void 0 : nextFn();
457
+ });
458
+ const offInit = ctx.on("loader/entry-init", function(first) {
459
+ const candidate = this ?? first;
460
+ if (candidate !== void 0 && isPrimeMemoryRow(candidate)) run();
461
+ });
462
+ const offService = ctx.on("internal/service", (name) => {
463
+ if (name === "settings") run();
464
+ });
465
+ const lateSweep = setTimeout(() => {
466
+ run();
467
+ }, 1500);
468
+ return {
469
+ dispose: () => {
470
+ offPatch();
471
+ offInit();
472
+ offService();
473
+ clearTimeout(lateSweep);
474
+ for (const timer of timers) clearTimeout(timer);
475
+ },
476
+ replay
477
+ };
478
+ }
479
+ /**
480
+ * Row entry point: adapt the memory plugin on activation and on remount.
481
+ * @param ctx - this row's context.
482
+ */
483
+ function apply(ctx) {
484
+ const loader = ctx.get("loader", false);
485
+ const routeOf = () => memoryRouteOf(ctx.modelSwitch.currentSettings(), defaultProviderOf(loader));
486
+ const adapter = installPrimeMemoryCompat(ctx, loader, routeOf);
487
+ ctx.effect(function* () {
488
+ yield adapter.dispose;
489
+ yield ctx.on("model-switch/settings-update", () => {
490
+ if (adapter.replay()) ctx.logger.info("model-switch: re-applied the dsh-prime-memory distillation route after a settings change");
491
+ });
492
+ }, "model-switch: keep the dsh-prime-memory route aligned with the settings");
493
+ }
494
+ //#endregion
495
+ export { apply, chainOf, inject, installPrimeMemoryCompat, name, planPrimeMemoryRoute, primeMemoryCompatStatus };