dsh-keys-manager 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1742,6 +1742,28 @@ export declare class KeysManagerService {
1742
1742
  * foreign record disappeared while the process was down.
1743
1743
  */
1744
1744
  private repairBinding;
1745
+ /**
1746
+ * Startup repair for an extra route installed before the capability index
1747
+ * existed: its profile carries model rows with no `input` and no
1748
+ * `reasoningEfforts`, so DSH treats an image model as text-only and a
1749
+ * reasoning model as non-reasoning. Only the rows the pinned catalog describes
1750
+ * are filled, and only on a profile whose `models` still equal our own record —
1751
+ * a list the user edited in Models is theirs. A second pass finds every
1752
+ * indexed row filled and writes nothing, and a refused write only warns: the
1753
+ * route keeps working exactly as it did.
1754
+ *
1755
+ * A repair whose settings write landed but whose record never did (the store
1756
+ * flush was lost with the process) is healed from the profile itself: the
1757
+ * live `models` equal exactly the repaired rows, so only the record is synced
1758
+ * and the settings are left alone. Any other mismatch is a user list and stays
1759
+ * untouched.
1760
+ *
1761
+ * Every write below gates on {@link persistenceRefused}, not on `closing`
1762
+ * alone: `close()` raises `shutdownRequested` before it awaits the borrowed
1763
+ * windows and sets `closing` only afterwards, and this repair is not part of
1764
+ * that pre-close restoration, so it carries no capability to claim.
1765
+ */
1766
+ private repairModelCapabilities;
1745
1767
  /**
1746
1768
  * Re-derive a managed route's binding after its projection changed outside
1747
1769
  * this manager's account pool: a removal, a committed harvest that handed
package/lib/index.js CHANGED
@@ -17,6 +17,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
17
17
  import { createHash, randomBytes } from 'node:crypto';
18
18
  import { CURSOR_ROUTE, cursorCatalogModels } from 'dsh-llm-omp-transports';
19
19
  import * as transportModule from 'dsh-llm-omp-transports';
20
+ import { mergeModelCapabilities, repairModelCapabilities as repairModelRows, sanitizeReasoningEfforts } from './capabilities.js';
20
21
  import { KEY_LIMIT, TEST_SUCCESS_FINISH_KINDS, accountRef, applyFailureCooldown, bindingKey, classifyOAuthFailure, isSelectable, markKeySuccess, markKeyUsed, normalizeSettings, patchSettings, pickHealthyExcluding, pickRoundRobin, quotaRank, rankCandidates, shouldFailover, statusOfKey, statusOfProvider, validateKeyInput, validateKeyPatch, } from './core.js';
21
22
  import { signInCapable, signInProvider } from './oauth/providers.js';
22
23
  import { SignInCancelledError, runSignIn } from './oauth/signin.js';
@@ -343,9 +344,9 @@ function normalizeModel(model) {
343
344
  const modalities = input.filter((value) => value === 'text' || value === 'image');
344
345
  if (modalities.length > 0)
345
346
  next.input = [...new Set(modalities)];
346
- if (source.reasoningEfforts !== null && typeof source.reasoningEfforts === 'object') {
347
- next.reasoningEfforts = source.reasoningEfforts;
348
- }
347
+ const reasoningEfforts = sanitizeReasoningEfforts(source.reasoningEfforts);
348
+ if (reasoningEfforts !== undefined)
349
+ next.reasoningEfforts = reasoningEfforts;
349
350
  if (source.compat !== null && typeof source.compat === 'object') {
350
351
  next.compat = source.compat;
351
352
  }
@@ -369,9 +370,10 @@ function discoveredModel(model) {
369
370
  }
370
371
  /**
371
372
  * Normalize one discovery answer for a profile write: unusable and duplicate
372
- * rows dropped, capped at the same limit discovery itself applies.
373
+ * rows dropped, capped at the same limit discovery itself applies, and the
374
+ * modalities the remote listing never reports filled from the capability index.
373
375
  */
374
- function discoveredModels(discovered) {
376
+ function discoveredModels(provider, discovered) {
375
377
  const models = [];
376
378
  const seen = new Set();
377
379
  for (const model of discovered) {
@@ -383,7 +385,7 @@ function discoveredModels(discovered) {
383
385
  if (models.length >= 60)
384
386
  break;
385
387
  }
386
- return models;
388
+ return mergeModelCapabilities(provider, models);
387
389
  }
388
390
  /** Credential-bearing header names the carrier must never persist as plain settings. */
389
391
  const CREDENTIAL_HEADER_NAMES = new Set(['authorization', 'proxy-authorization', 'cookie', 'api-key', 'apikey', 'x-api-key']);
@@ -1144,6 +1146,9 @@ export class KeysManagerService {
1144
1146
  void this.repairBrokerBindings().catch(error => {
1145
1147
  this.warn(`startup broker binding repair failed: ${error instanceof Error ? error.message : String(error)}`);
1146
1148
  });
1149
+ void this.repairModelCapabilities().catch(error => {
1150
+ this.warn(`startup model capability repair failed: ${error instanceof Error ? error.message : String(error)}`);
1151
+ });
1147
1152
  this.settledDisposer = this.watchAuthorizationSettled();
1148
1153
  this.recordUpdatedDisposer = this.watchGrantRecordUpdated();
1149
1154
  this.refreshTransportAccountsIfIdle();
@@ -1768,6 +1773,9 @@ export class KeysManagerService {
1768
1773
  void this.repairBrokerBindings().catch(error => {
1769
1774
  this.warn(`broker binding repair after the settings mount failed: ${error instanceof Error ? error.message : String(error)}`);
1770
1775
  });
1776
+ void this.repairModelCapabilities().catch(error => {
1777
+ this.warn(`model capability repair after the settings mount failed: ${error instanceof Error ? error.message : String(error)}`);
1778
+ });
1771
1779
  }
1772
1780
  /** Unmount the settings service that a re-mount replaced. */
1773
1781
  detachSettings(settings) {
@@ -7178,6 +7186,77 @@ export class KeysManagerService {
7178
7186
  this.store.touch();
7179
7187
  }
7180
7188
  }
7189
+ /**
7190
+ * Startup repair for an extra route installed before the capability index
7191
+ * existed: its profile carries model rows with no `input` and no
7192
+ * `reasoningEfforts`, so DSH treats an image model as text-only and a
7193
+ * reasoning model as non-reasoning. Only the rows the pinned catalog describes
7194
+ * are filled, and only on a profile whose `models` still equal our own record —
7195
+ * a list the user edited in Models is theirs. A second pass finds every
7196
+ * indexed row filled and writes nothing, and a refused write only warns: the
7197
+ * route keeps working exactly as it did.
7198
+ *
7199
+ * A repair whose settings write landed but whose record never did (the store
7200
+ * flush was lost with the process) is healed from the profile itself: the
7201
+ * live `models` equal exactly the repaired rows, so only the record is synced
7202
+ * and the settings are left alone. Any other mismatch is a user list and stays
7203
+ * untouched.
7204
+ *
7205
+ * Every write below gates on {@link persistenceRefused}, not on `closing`
7206
+ * alone: `close()` raises `shutdownRequested` before it awaits the borrowed
7207
+ * windows and sets `closing` only afterwards, and this repair is not part of
7208
+ * that pre-close restoration, so it carries no capability to claim.
7209
+ */
7210
+ async repairModelCapabilities() {
7211
+ for (const record of Object.values(this.store.providers)) {
7212
+ // Every write below crosses an await, so shutdown is re-checked per
7213
+ // profile instead of once at entry: a close requested during the
7214
+ // previous write must not let this one start (F1).
7215
+ if (this.persistenceRefused())
7216
+ return;
7217
+ const extraId = record.extraId;
7218
+ if (extraId === null)
7219
+ continue;
7220
+ const live = this.profileAt(record.settingsNs, record.settingsPath);
7221
+ if (live === undefined)
7222
+ continue;
7223
+ const models = repairModelRows(extraId, record.models);
7224
+ if (models === undefined)
7225
+ continue;
7226
+ if (JSON.stringify(live.models) !== JSON.stringify(record.models)) {
7227
+ // The settings half of an earlier run landed, its record half did not
7228
+ // (F2): sync the record only, never the profile.
7229
+ if (JSON.stringify(live.models) !== JSON.stringify(models))
7230
+ continue;
7231
+ record.models = models;
7232
+ this.store.touch();
7233
+ continue;
7234
+ }
7235
+ try {
7236
+ // The guard re-reads the profile right before the write: a user save
7237
+ // landing while the read above was in flight keeps its own list, and
7238
+ // shutdown refuses the write at its last point, exactly as binding does.
7239
+ const written = await this.mutateSettings(record.settingsNs, [{ op: 'set', path: [...record.settingsPath, 'models'], value: models }], () => {
7240
+ if (this.persistenceRefused())
7241
+ return false;
7242
+ const current = this.profileAt(record.settingsNs, record.settingsPath);
7243
+ return current !== undefined && JSON.stringify(current.models) === JSON.stringify(record.models);
7244
+ });
7245
+ if (!written)
7246
+ continue;
7247
+ // The write settles across an await: a close or a store remount since
7248
+ // then leaves the record half to the recovery branch above instead of
7249
+ // persisting into a manager that moved on.
7250
+ if (this.persistenceRefused() || this.store.provider(record.provider) !== record)
7251
+ return;
7252
+ record.models = models;
7253
+ this.store.touch();
7254
+ }
7255
+ catch (error) {
7256
+ this.pushWarning(`Did not store the catalog capabilities on the ${record.provider} profile: ${error instanceof Error ? error.message : String(error)}`);
7257
+ }
7258
+ }
7259
+ }
7181
7260
  /**
7182
7261
  * Re-derive a managed route's binding after its projection changed outside
7183
7262
  * this manager's account pool: a removal, a committed harvest that handed
@@ -7290,7 +7369,7 @@ export class KeysManagerService {
7290
7369
  */
7291
7370
  async catalogModelsFor(settingsNs, provider) {
7292
7371
  try {
7293
- return discoveredModels(await this.ctx.llm.discoverModels(settingsNs, { provider }, AbortSignal.timeout(5_000)));
7372
+ return discoveredModels(provider, await this.ctx.llm.discoverModels(settingsNs, { provider }, AbortSignal.timeout(5_000)));
7294
7373
  }
7295
7374
  catch (error) {
7296
7375
  this.warn(`the installed catalog could not describe ${provider}: ${error instanceof Error ? error.message : String(error)}`);
@@ -7643,7 +7722,7 @@ export class KeysManagerService {
7643
7722
  */
7644
7723
  async discoverModels(extra, value) {
7645
7724
  if (extra.headerEnv !== undefined)
7646
- return { models: normalizeModels(extra.models) };
7725
+ return { models: mergeModelCapabilities(extra.id, normalizeModels(extra.models)) };
7647
7726
  let discovered = [];
7648
7727
  let failure;
7649
7728
  try {
@@ -7652,10 +7731,12 @@ export class KeysManagerService {
7652
7731
  catch (error) {
7653
7732
  failure = error instanceof Error ? error.message : String(error);
7654
7733
  }
7655
- const models = discoveredModels(discovered);
7734
+ const models = discoveredModels(extra.id, discovered);
7656
7735
  if (models.length > 0)
7657
7736
  return { models, failure };
7658
- return { models: normalizeModels(extra.models), failure };
7737
+ // A seed-installed route must behave like a discovered one, so the same index
7738
+ // fills its modalities and thinking ladders before the profile is written.
7739
+ return { models: mergeModelCapabilities(extra.id, normalizeModels(extra.models)), failure };
7659
7740
  }
7660
7741
  /**
7661
7742
  * Remote: install and adopt one extra built-in provider.
@@ -7711,6 +7792,10 @@ export class KeysManagerService {
7711
7792
  extraId,
7712
7793
  api: existing.api ?? extra.api,
7713
7794
  baseURL: existing.baseURL ?? extra.baseURL,
7795
+ // No capability merge here: this branch writes only `apiKeyEnv`/`headers`
7796
+ // and adopts the profile's own rows, so a merged record would disagree
7797
+ // with the profile it adopted and the startup repair — which only acts on
7798
+ // a record that still matches its profile — could never heal it.
7714
7799
  models: normalizeModels(existing.models).length > 0 ? normalizeModels(existing.models) : normalizeModels(extra.models),
7715
7800
  adoptedAt: Date.now(),
7716
7801
  cursor: 0,
@@ -7756,7 +7841,7 @@ export class KeysManagerService {
7756
7841
  // mutation for its whole 20 s timeout before the row appears (F3).
7757
7842
  const found = importedFrom === null
7758
7843
  ? await this.discoverModels(extra, input.value)
7759
- : { models: normalizeModels(extra.models) };
7844
+ : { models: mergeModelCapabilities(extra.id, normalizeModels(extra.models)) };
7760
7845
  const { models, failure } = found;
7761
7846
  // The sign-in branch never probed the endpoint, so it cannot report a
7762
7847
  // discovery result.