dsh-model-switch 0.4.55 → 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,649 @@
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 = ["loader", "settings"];
123
+ /** The loader row id prime-memory is composed under (fixed by its bundle patch). */
124
+ const MEMORY_ENTRY_ID = "dsh-memory";
125
+ /** The state the settings page reads. */
126
+ const primeMemoryCompatStatus = { installed: false };
127
+ /**
128
+ * Write the memory row's static route into the profile patch itself.
129
+ *
130
+ * `settings.update` only accepts the entry's *live* schema fields, so the static
131
+ * `llm` pin never survives that call. The pin is what `resolveModelRoute` returns
132
+ * first, and it is the only key every distillation layer honours — so it has to be
133
+ * written where the next start reads it: the row config in the profile document.
134
+ * @param documentPath - the profile patch file.
135
+ * @param provider - route provider to pin.
136
+ * @param model - route model to pin.
137
+ * @returns whether the document changed.
138
+ */
139
+ /**
140
+ * Remove this plugin's own static pin from the memory row.
141
+ *
142
+ * `effectiveCfg` (dsh-prime-memory `pipeline/runner.js`) treats a non-empty
143
+ * `cfg.llm.provider + cfg.llm.model` pair as "pinned" and then ignores *both* the runtime
144
+ * chain and the legacy `distillProvider`/`distillModel` pair. A pin written earlier — for a
145
+ * host whose live RPC was not ready yet — is therefore not harmless: it keeps winning over
146
+ * every later live push, which is exactly the "the card changed, the calls did not" report.
147
+ * Once a live push is confirmed, the pin has to go.
148
+ *
149
+ * @param documentPath - the profile patch document that holds the memory row.
150
+ * @returns what happened, so the caller can log it without guessing.
151
+ */
152
+ async function clearStaticPin(documentPath) {
153
+ const { readFile, writeFile } = await import("node:fs/promises");
154
+ let text;
155
+ try {
156
+ text = await readFile(documentPath, "utf8");
157
+ } catch {
158
+ return "missing";
159
+ }
160
+ const rows = text.split(/(?=^- id: )/m);
161
+ const index = rows.findIndex((row) => /^- id: dsh-memory\r?\n/.test(row));
162
+ if (index < 0) return "missing";
163
+ const row = rows[index];
164
+ const trimmed = row.replace(/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m, "");
165
+ if (trimmed === row) return "absent";
166
+ rows[index] = trimmed;
167
+ try {
168
+ await writeFile(documentPath, rows.join(""), "utf8");
169
+ } catch {
170
+ return "missing";
171
+ }
172
+ return "cleared";
173
+ }
174
+ async function writeStaticPin(documentPath, provider, model) {
175
+ const { readFile, writeFile } = await import("node:fs/promises");
176
+ let text;
177
+ try {
178
+ text = await readFile(documentPath, "utf8");
179
+ } catch {
180
+ return "missing";
181
+ }
182
+ const rows = text.split(/(?=^- id: )/m);
183
+ const index = rows.findIndex((row) => /^- id: dsh-memory\r?\n/.test(row));
184
+ if (index < 0) return "missing";
185
+ const row = rows[index];
186
+ const desired = ` llm:\n provider: ${provider}\n model: ${model}\n`;
187
+ let next;
188
+ if (/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m.test(row)) next = row.replace(/^ {4}llm:\r?\n(?: {6}.*\r?\n)*/m, desired);
189
+ else if (/^ {2}config:\r?\n/m.test(row)) next = row.replace(/^ {2}config:\r?\n/m, ` config:\n${desired}`);
190
+ else next = row.replace(/^- id: dsh-memory\r?\n/m, `- id: dsh-memory\n config:\n${desired}`);
191
+ if (next === row) return "unchanged";
192
+ rows[index] = next;
193
+ try {
194
+ await writeFile(documentPath, rows.join(""), "utf8");
195
+ } catch {
196
+ return "missing";
197
+ }
198
+ return "written";
199
+ }
200
+ /** A non-blank string. */
201
+ function text(value) {
202
+ return typeof value === "string" ? value.trim() : "";
203
+ }
204
+ /** Read a value as a plain record. */
205
+ function asRecord(value) {
206
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
207
+ }
208
+ /**
209
+ * The distillation chain a settings section currently carries.
210
+ *
211
+ * Accepts the chain form and the legacy provider/model pair, so a user who set
212
+ * the old two fields is still recognised as user intent.
213
+ * @param section - the `live` section (or a whole settings view) to read.
214
+ * @returns The chain entries; empty when nothing is set.
215
+ */
216
+ function chainOf(section) {
217
+ const live = asRecord(section);
218
+ if (live === void 0) return [];
219
+ const chain = live.distillChain;
220
+ if (Array.isArray(chain)) {
221
+ const entries = [];
222
+ for (const item of chain) {
223
+ const entry = asRecord(item);
224
+ const provider = text(entry?.provider);
225
+ const model = text(entry?.model);
226
+ if (provider === "" || model === "") continue;
227
+ const effort = text(entry?.reasoningEffort);
228
+ entries.push(effort === "" ? {
229
+ provider,
230
+ model
231
+ } : {
232
+ provider,
233
+ model,
234
+ reasoningEffort: effort
235
+ });
236
+ }
237
+ return entries;
238
+ }
239
+ const provider = text(live.distillProvider);
240
+ const model = text(live.distillModel);
241
+ return provider === "" || model === "" ? [] : [{
242
+ provider,
243
+ model
244
+ }];
245
+ }
246
+ /**
247
+ * Decide the route config one memory row would run with from its config alone.
248
+ *
249
+ * Kept for the settings-free path (a profile that pins `config.llm.*`): the
250
+ * runtime path writes the settings section instead, because the plugin reads its
251
+ * config only at init.
252
+ * @param config - the row's current config (any JSON-ish value).
253
+ * @param route - this plugin's distillation route; an incomplete pair counts as unset.
254
+ * @param adoptedRoute - a `provider/model` this adapter wrote on an earlier pass.
255
+ * @returns The config to install, whether it changed, and what was applied.
256
+ */
257
+ function planPrimeMemoryRoute(config, route, adoptedRoute) {
258
+ const base = asRecord(config);
259
+ if (base === void 0) return {
260
+ config: {},
261
+ changed: false,
262
+ skipped: "no-route"
263
+ };
264
+ const llm = asRecord(base.llm) ?? {};
265
+ const declaredProvider = text(llm.provider);
266
+ const declaredModel = text(llm.model);
267
+ const declaredRoute = declaredProvider !== "" && declaredModel !== "" ? `${declaredProvider}/${declaredModel}` : void 0;
268
+ if (!(declaredRoute !== void 0 && adoptedRoute !== void 0 && declaredRoute === adoptedRoute) && (declaredProvider !== "" || declaredModel !== "")) return {
269
+ config: base,
270
+ changed: false,
271
+ skipped: "user-set"
272
+ };
273
+ const provider = text(route?.provider);
274
+ const model = text(route?.model);
275
+ if (provider === "" || model === "") return {
276
+ config: base,
277
+ changed: false,
278
+ skipped: "no-route"
279
+ };
280
+ return {
281
+ config: {
282
+ ...base,
283
+ llm: {
284
+ ...llm,
285
+ provider,
286
+ model
287
+ }
288
+ },
289
+ changed: true,
290
+ route: `${provider}/${model}`
291
+ };
292
+ }
293
+ /** The endpoint the memory plugin registers for its own runtime settings writes. */
294
+ const MEMORY_RPC_PATH = "/dsh-memory/rpc/settings-set";
295
+ /**
296
+ * Whether the memory row's live section already carries exactly our route.
297
+ *
298
+ * The RPC write path persists the live section to the profile document on every
299
+ * call, and a document change reloads the composition — so pushing an unchanged
300
+ * route re-triggers this adapter forever (a ~6 s recompose loop, observed with
301
+ * `dsh-prime-memory@0.26.10`). Comparing first is what makes the push idempotent
302
+ * across reloads.
303
+ *
304
+ * @param value - the memory row's live settings object, as the forms describe it.
305
+ * @param provider - route provider to compare against.
306
+ * @param model - route model to compare against.
307
+ * @returns true when a push would change nothing.
308
+ */
309
+ function memoryLiveMatchesRoute(value, provider, model) {
310
+ const outer = value === null || typeof value !== "object" ? void 0 : value;
311
+ if (outer === void 0) return false;
312
+ const inner = outer.live;
313
+ const live = inner !== null && typeof inner === "object" ? inner : outer;
314
+ if (live.distillProvider !== provider || live.distillModel !== model) return false;
315
+ const chain = live.distillChain;
316
+ if (Array.isArray(chain) && chain.length !== 0) return false;
317
+ const layers = live.distillLayerChains;
318
+ if (layers === null || typeof layers !== "object") return false;
319
+ for (const key of [
320
+ "l1",
321
+ "l2",
322
+ "l3"
323
+ ]) {
324
+ const layer = layers[key];
325
+ if (!Array.isArray(layer) || layer.length !== 1) return false;
326
+ const first = layer[0];
327
+ if (first === void 0 || first.provider !== provider || first.model !== model) return false;
328
+ }
329
+ return true;
330
+ }
331
+ /**
332
+ * Hand the route to the memory plugin through the RPC it registers for its own
333
+ * settings page.
334
+ *
335
+ * Writing the config document (what `settings.update` does) only changes what the
336
+ * next start reads; the plugin resolves its route from the runtime settings object
337
+ * it built at `apply`. This endpoint is the documented runtime write path — the
338
+ * same one its own "distillation parameters" panel posts to — so it takes effect
339
+ * without a restart, which is exactly what a provider switch needs.
340
+ */
341
+ async function pushMemoryRoute(ctx, route) {
342
+ const server = ctx.get("webServer", false);
343
+ const port = server?.port ?? server?.address?.port;
344
+ if (typeof port !== "number" || port <= 0) return "absent";
345
+ try {
346
+ const response = await fetch(`http://127.0.0.1:${port}${MEMORY_RPC_PATH}`, {
347
+ method: "POST",
348
+ headers: { "content-type": "application/json" },
349
+ body: JSON.stringify({
350
+ distillChain: [],
351
+ distillLayerChains: {
352
+ l1: [{
353
+ provider: route.provider,
354
+ model: route.model
355
+ }],
356
+ l2: [{
357
+ provider: route.provider,
358
+ model: route.model
359
+ }],
360
+ l3: [{
361
+ provider: route.provider,
362
+ model: route.model
363
+ }]
364
+ },
365
+ distillProvider: route.provider,
366
+ distillModel: route.model,
367
+ reasoningEffort: ""
368
+ })
369
+ });
370
+ if (response.status === 404 || response.status === 405 || response.status === 403) return "absent";
371
+ return response.ok ? "pushed" : "rejected";
372
+ } catch {
373
+ return "absent";
374
+ }
375
+ }
376
+ /** The endpoint the memory plugin registers for its own runtime settings reads. */
377
+ const MEMORY_RPC_GET_PATH = "/dsh-memory/rpc/settings-get";
378
+ /**
379
+ * Read the memory plugin's live settings through the RPC its panel posts to.
380
+ *
381
+ * The `settings` forms descriptors are an internal detail of the plugin: on
382
+ * `dsh-prime-memory@0.26.16` this row could not observe them, which skipped every
383
+ * push and left the plugin on its own deployment default. Its RPC is the surface
384
+ * its own panel uses, so reading there keeps the adapter working across plugin
385
+ * releases — and it is what makes the push idempotent across document reloads.
386
+ * @param ctx - this row's context; the host web server supplies the port.
387
+ * @returns The live settings object, or undefined when the seam is unreachable.
388
+ */
389
+ async function readMemoryLive(ctx) {
390
+ const server = ctx.get("webServer", false);
391
+ const port = server?.port ?? server?.address?.port;
392
+ if (typeof port !== "number" || port <= 0) return void 0;
393
+ try {
394
+ const response = await fetch(`http://127.0.0.1:${port}${MEMORY_RPC_GET_PATH}`, {
395
+ method: "POST",
396
+ headers: { "content-type": "application/json" },
397
+ body: JSON.stringify({ method: "settings-get" })
398
+ });
399
+ if (!response.ok) return void 0;
400
+ return (await response.json())?.value?.settings;
401
+ } catch {
402
+ return;
403
+ }
404
+ }
405
+ /** The `agent-default-model` row's provider: the deployment default. */
406
+ function defaultProviderOf(loader) {
407
+ if (typeof loader?.entries !== "function") return void 0;
408
+ for (const entry of loader.entries()) {
409
+ if (entry.options?.id !== "agent-default-model") continue;
410
+ const provider = text(asRecord(entry.options?.config)?.provider);
411
+ if (provider !== "") return provider;
412
+ }
413
+ }
414
+ /** The `settings` service the memory plugin itself writes through. */
415
+ function formsOf(ctx) {
416
+ try {
417
+ return ctx.get("settings", false);
418
+ } catch {
419
+ return;
420
+ }
421
+ }
422
+ /** Live attempts to spend before falling back to the static pin. */
423
+ const PIN_AFTER_ATTEMPTS = 4;
424
+ /**
425
+ * Install the adapter for the whole profile.
426
+ *
427
+ * Writes the memory plugin's own `live` section on activation, on every
428
+ * `loader/patch-context`, on `loader/entry-init`, once more after a short delay
429
+ * (a bundle-inserted row is often composed after this one), and again whenever
430
+ * this plugin's settings change.
431
+ * @param ctx - this row's context.
432
+ * @param loader - the loader service, when present.
433
+ * @param routeOf - resolves this plugin's distillation route for one settings snapshot.
434
+ * @returns The disposer and a replay hook.
435
+ */
436
+ function installPrimeMemoryCompat(ctx, loader, routeOf) {
437
+ /** The route this adapter wrote last, so it may replace its own value only. */
438
+ let adoptedRoute;
439
+ let pending;
440
+ let attempt = 0;
441
+ const timers = [];
442
+ const primeMemoryEntry = () => {
443
+ for (const entry of loader?.entries?.() ?? []) if (isPrimeMemoryRow(entry)) return entry;
444
+ };
445
+ const memoryRowPresent = () => primeMemoryEntry() !== void 0;
446
+ /** The live section the memory plugin registered, read back through the host. */
447
+ const sectionOf = (forms) => {
448
+ try {
449
+ return (forms.describe?.({ redactSecrets: true }) ?? []).find((item) => item.ns === MEMORY_ENTRY_ID);
450
+ } catch {
451
+ return;
452
+ }
453
+ };
454
+ const scheduleRetry = () => {
455
+ if (attempt >= 8) return;
456
+ const delay = Math.min(4e3, 200 * 2 ** attempt);
457
+ attempt += 1;
458
+ const timer = setTimeout(() => {
459
+ run();
460
+ }, delay);
461
+ timer.unref?.();
462
+ timers.push(timer);
463
+ };
464
+ /**
465
+ * Last resort for a host whose live seams never accept the route.
466
+ *
467
+ * Writing the static pin disables every live form (`pinned` in `effectiveCfg`), so it must
468
+ * not happen while the live attempts still have a chance: a pin written on a slow start is
469
+ * what kept overriding later pushes. It therefore waits for the retry budget to run out.
470
+ *
471
+ * @param forms - the settings service describing the memory row.
472
+ * @param provider - route provider to pin.
473
+ * @param model - route model to pin.
474
+ * @param wanted - `provider/model`, for the log line.
475
+ */
476
+ const pinAsFallback = async (forms, provider, model, wanted) => {
477
+ if (attempt < PIN_AFTER_ATTEMPTS) {
478
+ scheduleRetry();
479
+ return;
480
+ }
481
+ const documentPath = forms.documentPath;
482
+ if (typeof documentPath !== "string" || documentPath === "") return;
483
+ try {
484
+ 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)`);
485
+ } catch (cause) {
486
+ ctx.logger.warn(`model-switch: could not pin the dsh-prime-memory route (${String(cause)})`);
487
+ }
488
+ };
489
+ /**
490
+ * Drop a pin left over from an earlier release.
491
+ *
492
+ * A static `llm.provider/model` pin sets `pinned`, which makes the plugin's
493
+ * `effectiveCfg` ignore the chain *and* the live pair, so the live route decides
494
+ * nothing on that host until the pin is gone.
495
+ * @param forms - the settings seam, when this host exposes it.
496
+ */
497
+ const clearStalePin = async (forms) => {
498
+ const pinnedDocument = forms?.documentPath;
499
+ if (typeof pinnedDocument !== "string" || pinnedDocument === "") return;
500
+ try {
501
+ if (await clearStaticPin(pinnedDocument) === "cleared") ctx.logger.info("model-switch: removed the stale dsh-prime-memory static pin; the live route decides now");
502
+ } catch (cause) {
503
+ ctx.logger.warn(`model-switch: could not clear the dsh-prime-memory static pin (${String(cause)})`);
504
+ }
505
+ };
506
+ /**
507
+ *
508
+ * The plugin builds that section inside its own `apply` (`settings.register`), so
509
+ * a write issued before that point lands in a section nobody reads — the reason
510
+ * an unverified "write once at mount" pass left it on the deployment default.
511
+ * Writing only once the section is visible, and verifying by reading the chain
512
+ * back, is what makes this measurable instead of hopeful.
513
+ */
514
+ const run = async () => {
515
+ if (pending !== void 0) return pending;
516
+ if (!memoryRowPresent()) {
517
+ primeMemoryCompatStatus.routeSkipped = "no-row";
518
+ return;
519
+ }
520
+ const route = routeOf();
521
+ const provider = text(route?.provider);
522
+ const model = text(route?.model);
523
+ if (provider === "" || model === "") {
524
+ primeMemoryCompatStatus.routeSkipped = "no-route";
525
+ return;
526
+ }
527
+ const wanted = `${provider}/${model}`;
528
+ const forms = formsOf(ctx);
529
+ const live = await readMemoryLive(ctx);
530
+ if (live === void 0) {
531
+ primeMemoryCompatStatus.routeSkipped = "no-route";
532
+ scheduleRetry();
533
+ return;
534
+ }
535
+ if (memoryLiveMatchesRoute(live, provider, model)) {
536
+ adoptedRoute = wanted;
537
+ primeMemoryCompatStatus.installed = true;
538
+ primeMemoryCompatStatus.route = wanted;
539
+ delete primeMemoryCompatStatus.routeSkipped;
540
+ await clearStalePin(forms);
541
+ return;
542
+ }
543
+ const declared = chainOf(live);
544
+ const declaredRoute = declared.length > 0 ? `${text(declared[0]?.provider)}/${text(declared[0]?.model)}` : "";
545
+ if (declaredRoute !== "" && declaredRoute !== wanted && declaredRoute !== adoptedRoute) {
546
+ primeMemoryCompatStatus.routeSkipped = "user-set";
547
+ primeMemoryCompatStatus.route = void 0;
548
+ return;
549
+ }
550
+ if (await pushMemoryRoute(ctx, {
551
+ provider,
552
+ model
553
+ }) === "pushed") {
554
+ adoptedRoute = wanted;
555
+ attempt = 0;
556
+ primeMemoryCompatStatus.installed = true;
557
+ primeMemoryCompatStatus.route = wanted;
558
+ delete primeMemoryCompatStatus.routeSkipped;
559
+ await clearStalePin(forms);
560
+ return;
561
+ }
562
+ if (forms === void 0 || forms.update === void 0 || forms.describe === void 0) {
563
+ primeMemoryCompatStatus.routeSkipped = "no-route";
564
+ scheduleRetry();
565
+ return;
566
+ }
567
+ const section = sectionOf(forms);
568
+ if (section === void 0 || asRecord(section.value) === void 0) {
569
+ await pinAsFallback(forms, provider, model, wanted);
570
+ return;
571
+ }
572
+ const chain = planDistillChain({
573
+ provider,
574
+ model
575
+ }, chainOf(section.value));
576
+ pending = forms.update(MEMORY_ENTRY_ID, distillChainPatch(chain), section.revision).then(async () => {
577
+ const applied = chainOf(sectionOf(forms)?.value);
578
+ if ((applied.length > 0 ? `${text(applied[0]?.provider)}/${text(applied[0]?.model)}` : "") !== wanted) {
579
+ await pinAsFallback(forms, provider, model, wanted);
580
+ return;
581
+ }
582
+ adoptedRoute = wanted;
583
+ attempt = 0;
584
+ primeMemoryCompatStatus.installed = true;
585
+ primeMemoryCompatStatus.route = wanted;
586
+ delete primeMemoryCompatStatus.routeSkipped;
587
+ }).catch(async (cause) => {
588
+ primeMemoryCompatStatus.routeSkipped = "no-route";
589
+ ctx.logger.warn(`model-switch: could not write the dsh-prime-memory distillation route (${String(cause)})`);
590
+ await pinAsFallback(forms, provider, model, wanted);
591
+ }).finally(() => {
592
+ pending = void 0;
593
+ });
594
+ return pending;
595
+ };
596
+ const replay = () => {
597
+ run();
598
+ return true;
599
+ };
600
+ run();
601
+ const offPatch = ctx.on("loader/patch-context", function(first, second) {
602
+ const nextFn = typeof first === "function" ? first : second;
603
+ if (isPrimeMemoryRow(typeof first === "function" ? this : first)) run();
604
+ return nextFn === void 0 ? void 0 : nextFn();
605
+ });
606
+ const offInit = ctx.on("loader/entry-init", function(first) {
607
+ const candidate = this ?? first;
608
+ if (candidate !== void 0 && isPrimeMemoryRow(candidate)) run();
609
+ });
610
+ const offService = ctx.on("internal/service", (name) => {
611
+ if (name === "settings") run();
612
+ });
613
+ const lateSweep = setTimeout(() => {
614
+ run();
615
+ }, 1500);
616
+ return {
617
+ dispose: () => {
618
+ offPatch();
619
+ offInit();
620
+ offService();
621
+ clearTimeout(lateSweep);
622
+ for (const timer of timers) clearTimeout(timer);
623
+ },
624
+ replay
625
+ };
626
+ }
627
+ /**
628
+ * Row entry point: adapt the memory plugin on activation and on remount.
629
+ * @param ctx - this row's context.
630
+ */
631
+ function apply(ctx) {
632
+ ctx.inject(["modelSwitch"], (withProvider) => {
633
+ withProvider.inject(["webServer"], (scope) => scope.effect(() => {
634
+ const runtime = scope.modelSwitch;
635
+ const loader = scope.get("loader", false);
636
+ const routeOf = () => memoryRouteOf(runtime.currentSettings(), defaultProviderOf(loader));
637
+ const adapter = installPrimeMemoryCompat(scope, loader, routeOf);
638
+ const off = scope.on("model-switch/settings-update", () => {
639
+ if (adapter.replay()) scope.logger.info("model-switch: re-applied the dsh-prime-memory distillation route after a settings change");
640
+ });
641
+ return () => {
642
+ off();
643
+ adapter.dispose();
644
+ };
645
+ }, "model-switch: keep the dsh-prime-memory route aligned with the settings"));
646
+ });
647
+ }
648
+ //#endregion
649
+ export { installPrimeMemoryCompat as a, planPrimeMemoryRoute as c, readMemoryLive as d, writeStaticPin as f, inject as i, primeMemoryCompatStatus as l, chainOf as n, memoryLiveMatchesRoute as o, clearStaticPin as r, name as s, apply as t, pushMemoryRoute as u };