dsh-model-think-level 2.1.0 → 2.2.0

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.js CHANGED
@@ -11,13 +11,14 @@ var BALANCE_PATH = "/dsh-model-think-level/balance";
11
11
  var AUTOFILL_CONFIG_PATH = "/dsh-model-think-level/autofill-config";
12
12
  var HEADERS_CONFIG_PATH = "/dsh-model-think-level/headers-config";
13
13
  var FINGERPRINT_PATH = "/dsh-model-think-level/fingerprint";
14
+ var ORDER_PATH = "/dsh-model-think-level/ui-order";
15
+ var ORDER_FILE = "ui-order.json";
14
16
  var PI_AI_NS = "llm-pi-ai";
15
17
  var UNSET_MARKER = "reasoningEffortsUnset";
16
18
  var INPUT_UNSET_MARKER = "inputUnset";
17
19
  var INPUT_IMAGE_GEN_MARKER = "inputImageGen";
18
20
  var AUTOFILL_MARKER = "reasoningEffortsAutofilled";
19
21
  var IMAGE_CONFIG_PATH = "/dsh-model-think-level/image-config";
20
- var IMAGE_GENERATE_PATH = "/dsh-model-think-level/image-generate";
21
22
  var IMAGE_CONFIG_FILE = "image.json";
22
23
  var IMAGE_MCP_PATCH_ID = "dsh-image-mcp";
23
24
  var IMAGE_MCP_PATCH_MARK = "dsh-model-think-level:image-mcp";
@@ -325,6 +326,18 @@ function withoutKeyEntry(document, route, ref) {
325
326
  else providers[route] = list;
326
327
  return { version: 1, providers, ...endpointsOf(document), ...balancesOf(document) };
327
328
  }
329
+ function withoutRoute(document, route) {
330
+ const providers = { ...document.providers };
331
+ delete providers[route];
332
+ const endpoints = document.endpoints === void 0 ? void 0 : { ...document.endpoints };
333
+ if (endpoints !== void 0) delete endpoints[route];
334
+ const balances = document.balances === void 0 ? void 0 : { ...document.balances };
335
+ if (balances !== void 0) delete balances[route];
336
+ let next = { version: 1, providers };
337
+ if (endpoints !== void 0 && Object.keys(endpoints).length > 0) next = { ...next, endpoints };
338
+ if (balances !== void 0 && Object.keys(balances).length > 0) next = { ...next, balances };
339
+ return next;
340
+ }
328
341
 
329
342
  // src/key-route-core.ts
330
343
  function canServe(key, model, knowledge) {
@@ -666,6 +679,92 @@ function withoutServes(document, route, ref) {
666
679
  return { version: 1, providers };
667
680
  }
668
681
 
682
+ // src/order-store.ts
683
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "node:fs";
684
+ import { dirname as dirname3, join as join3 } from "node:path";
685
+ function emptyUiOrder() {
686
+ return { version: 1, savedAt: 0, providerOrder: [], modelOrder: {}, providersDisabled: [] };
687
+ }
688
+ function uiOrderFilePath(home = harnessHome()) {
689
+ return join3(home, "dsh-model-think-level", ORDER_FILE);
690
+ }
691
+ function normalizeId(value) {
692
+ if (typeof value !== "string") return void 0;
693
+ const id = value.trim();
694
+ return id.length === 0 ? void 0 : id;
695
+ }
696
+ function normalizeIds(value) {
697
+ if (!Array.isArray(value)) return [];
698
+ return [...new Set(value.map(normalizeId).filter((id) => id !== void 0))];
699
+ }
700
+ function parseUiOrder(raw) {
701
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return emptyUiOrder();
702
+ const record = raw;
703
+ const savedAt = typeof record["savedAt"] === "number" && Number.isFinite(record["savedAt"]) ? record["savedAt"] : 0;
704
+ const rawProviders = record["providerOrder"];
705
+ const rawModels = record["modelOrder"];
706
+ const modelOrder = {};
707
+ if (typeof rawModels === "object" && rawModels !== null && !Array.isArray(rawModels)) {
708
+ for (const [provider, value] of Object.entries(rawModels)) {
709
+ if (provider.length === 0) continue;
710
+ const ids = normalizeIds(value);
711
+ if (ids.length > 0) modelOrder[provider] = ids;
712
+ }
713
+ }
714
+ return {
715
+ version: 1,
716
+ savedAt,
717
+ providerOrder: normalizeIds(rawProviders),
718
+ modelOrder,
719
+ providersDisabled: normalizeIds(record["providersDisabled"])
720
+ };
721
+ }
722
+ function mergeUiOrder(current, patch, at) {
723
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) return current;
724
+ const record = patch;
725
+ const providers = record["providerOrder"];
726
+ const models = record["modelOrder"];
727
+ const disabled = record["providersDisabled"];
728
+ const savedAt = typeof record["savedAt"] === "number" && Number.isFinite(record["savedAt"]) ? record["savedAt"] : at;
729
+ const parsedModels = parseUiOrder({
730
+ version: 1,
731
+ savedAt,
732
+ providerOrder: Array.isArray(providers) ? providers : current.providerOrder,
733
+ modelOrder: typeof models === "object" && models !== null && !Array.isArray(models) ? models : current.modelOrder,
734
+ // An absent field keeps the stored set; an explicit empty ARRAY is a real
735
+ // "everything is on" and replaces it.
736
+ providersDisabled: Array.isArray(disabled) ? disabled : current.providersDisabled
737
+ });
738
+ return parsedModels;
739
+ }
740
+ function readUiOrder(file = uiOrderFilePath()) {
741
+ try {
742
+ return parseUiOrder(JSON.parse(readFileSync3(file, "utf8")));
743
+ } catch {
744
+ return emptyUiOrder();
745
+ }
746
+ }
747
+ function writeUiOrder(document, file = uiOrderFilePath()) {
748
+ mkdirSync3(dirname3(file), { recursive: true });
749
+ const temporary = `${file}.${process.pid}.tmp`;
750
+ writeFileSync3(temporary, `${JSON.stringify(document, null, 2)}
751
+ `, "utf8");
752
+ try {
753
+ renameSync3(temporary, file);
754
+ } catch (error) {
755
+ try {
756
+ unlinkSync3(temporary);
757
+ } catch {
758
+ }
759
+ throw error;
760
+ }
761
+ }
762
+ function commitUiOrder(patch, at, file = uiOrderFilePath()) {
763
+ const next = mergeUiOrder(readUiOrder(file), patch, at);
764
+ writeUiOrder(next, file);
765
+ return next;
766
+ }
767
+
669
768
  // src/multi-key-listing.ts
670
769
  var DEFAULT_PROBE_CONCURRENCY = 4;
671
770
  var MODEL_ORDER = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
@@ -2570,6 +2669,7 @@ function inferProtocol(route) {
2570
2669
  return "openai-completions";
2571
2670
  }
2572
2671
  var COMPAT_CAPABLE_PROTOCOL = "openai-completions";
2672
+ var RESPONSES_PROTOCOL = "openai-responses";
2573
2673
  var ANTHROPIC_PROTOCOL = "anthropic-messages";
2574
2674
  function isSelfHostedEndpoint(baseURL) {
2575
2675
  if (baseURL === void 0 || baseURL.length === 0) return false;
@@ -2602,6 +2702,31 @@ function sanitizeCompatForProtocol(compat, api) {
2602
2702
  delete copy["forceAdaptiveThinking"];
2603
2703
  return Object.keys(copy).length === 0 ? void 0 : copy;
2604
2704
  }
2705
+ var COMPLETIONS_ONLY_COMPAT = [
2706
+ "supportsReasoningEffort",
2707
+ "thinkingFormat",
2708
+ "thinkingTokenBudgetField",
2709
+ "supportsThinkingTokenBudget",
2710
+ "vllmPriority"
2711
+ ];
2712
+ var ANTHROPIC_ONLY_COMPAT = ["forceAdaptiveThinking"];
2713
+ function stripForeignCompat(compat, api) {
2714
+ const norm2 = normalize(api);
2715
+ let foreign;
2716
+ if (norm2 === COMPAT_CAPABLE_PROTOCOL) foreign = ANTHROPIC_ONLY_COMPAT;
2717
+ else if (norm2 === RESPONSES_PROTOCOL) foreign = [...COMPLETIONS_ONLY_COMPAT, ...ANTHROPIC_ONLY_COMPAT];
2718
+ else if (norm2 === ANTHROPIC_PROTOCOL) foreign = COMPLETIONS_ONLY_COMPAT;
2719
+ else return void 0;
2720
+ let stripped = false;
2721
+ const copy = { ...compat };
2722
+ for (const key of foreign) {
2723
+ if (key in copy) {
2724
+ delete copy[key];
2725
+ stripped = true;
2726
+ }
2727
+ }
2728
+ return stripped ? copy : void 0;
2729
+ }
2605
2730
  function compatForRoute(entry, route) {
2606
2731
  const api = normalize(route.api);
2607
2732
  if (api === COMPAT_CAPABLE_PROTOCOL) {
@@ -3720,9 +3845,9 @@ function installPiAiHeaderTransforms(llm, source) {
3720
3845
  }
3721
3846
 
3722
3847
  // src/headers-conflict.ts
3723
- import { existsSync, readFileSync as readFileSync3 } from "node:fs";
3848
+ import { existsSync, readFileSync as readFileSync4 } from "node:fs";
3724
3849
  import { createRequire } from "node:module";
3725
- import { dirname as dirname3, join as join3, resolve } from "node:path";
3850
+ import { dirname as dirname4, join as join4, resolve } from "node:path";
3726
3851
  var SIBLING_PACKAGES = [
3727
3852
  "dsh-client-masquerade",
3728
3853
  "dsh-llm-headers",
@@ -3734,20 +3859,20 @@ function searchRoots() {
3734
3859
  const roots = /* @__PURE__ */ new Set();
3735
3860
  const entry = process.argv[1];
3736
3861
  if (typeof entry === "string" && entry.length > 0) {
3737
- let dir = dirname3(resolve(entry));
3862
+ let dir = dirname4(resolve(entry));
3738
3863
  for (let depth = 0; depth < 8; depth += 1) {
3739
- roots.add(join3(dir, "node_modules"));
3740
- const parent = dirname3(dir);
3864
+ roots.add(join4(dir, "node_modules"));
3865
+ const parent = dirname4(dir);
3741
3866
  if (parent === dir) break;
3742
3867
  dir = parent;
3743
3868
  }
3744
3869
  }
3745
- roots.add(join3(process.cwd(), "node_modules"));
3870
+ roots.add(join4(process.cwd(), "node_modules"));
3746
3871
  try {
3747
3872
  const require2 = createRequire(import.meta.url);
3748
3873
  for (const name2 of SIBLING_PACKAGES) {
3749
3874
  try {
3750
- roots.add(join3(dirname3(dirname3(dirname3(require2.resolve(`${name2}/package.json`)))), "node_modules"));
3875
+ roots.add(join4(dirname4(dirname4(dirname4(require2.resolve(`${name2}/package.json`)))), "node_modules"));
3751
3876
  } catch {
3752
3877
  }
3753
3878
  }
@@ -3756,14 +3881,14 @@ function searchRoots() {
3756
3881
  return [...roots];
3757
3882
  }
3758
3883
  function findAdapterFile() {
3759
- const relative = join3("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
3884
+ const relative = join4("@deepseek-ai", "dsh-llm-pi-ai", "lib", "index.js");
3760
3885
  const candidates = [];
3761
3886
  try {
3762
3887
  const require2 = createRequire(import.meta.url);
3763
3888
  candidates.push(require2.resolve("@deepseek-ai/dsh-llm-pi-ai"));
3764
3889
  } catch {
3765
3890
  }
3766
- for (const root of searchRoots()) candidates.push(join3(root, relative));
3891
+ for (const root of searchRoots()) candidates.push(join4(root, relative));
3767
3892
  for (const candidate of candidates) {
3768
3893
  if (existsSync(candidate)) return candidate;
3769
3894
  }
@@ -3774,7 +3899,7 @@ function adapterSourcePatched(source) {
3774
3899
  }
3775
3900
  function adapterPatchState(path) {
3776
3901
  try {
3777
- return adapterSourcePatched(readFileSync3(path, "utf8")) ? "patched" : "stock";
3902
+ return adapterSourcePatched(readFileSync4(path, "utf8")) ? "patched" : "stock";
3778
3903
  } catch {
3779
3904
  return "unknown";
3780
3905
  }
@@ -3785,8 +3910,8 @@ function findSiblings() {
3785
3910
  for (const root of searchRoots()) {
3786
3911
  for (const name2 of SIBLING_PACKAGES) {
3787
3912
  if (seen.has(name2)) continue;
3788
- const dir = join3(root, name2);
3789
- const manifest = join3(dir, "package.json");
3913
+ const dir = join4(root, name2);
3914
+ const manifest = join4(dir, "package.json");
3790
3915
  if (!existsSync(manifest)) continue;
3791
3916
  seen.add(name2);
3792
3917
  found.push({ name: name2, path: dir });
@@ -3818,8 +3943,8 @@ function detectHeaderConflicts() {
3818
3943
  }
3819
3944
 
3820
3945
  // src/image/config.ts
3821
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync3, unlinkSync as unlinkSync3, writeFileSync as writeFileSync3 } from "node:fs";
3822
- import { dirname as dirname4, join as join4 } from "node:path";
3946
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
3947
+ import { dirname as dirname5, join as join5 } from "node:path";
3823
3948
 
3824
3949
  // src/image/sizes.ts
3825
3950
  var IMAGE_SIZE_TIERS = [
@@ -3836,7 +3961,7 @@ var IMAGE_FALLBACK_PARAMS = {
3836
3961
  responseFormat: "b64_json"
3837
3962
  };
3838
3963
  function imageConfigFilePath(home = harnessHome()) {
3839
- return join4(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
3964
+ return join5(home, "dsh-model-think-level", IMAGE_CONFIG_FILE);
3840
3965
  }
3841
3966
  function emptyImageConfig(now = () => /* @__PURE__ */ new Date()) {
3842
3967
  return {
@@ -3933,7 +4058,7 @@ function parseImageModel(raw) {
3933
4058
  function readImageConfig(file = imageConfigFilePath()) {
3934
4059
  let text;
3935
4060
  try {
3936
- text = readFileSync4(file, "utf8");
4061
+ text = readFileSync5(file, "utf8");
3937
4062
  } catch {
3938
4063
  return emptyImageConfig();
3939
4064
  }
@@ -3944,15 +4069,15 @@ function readImageConfig(file = imageConfigFilePath()) {
3944
4069
  }
3945
4070
  }
3946
4071
  function writeImageConfig(document, file = imageConfigFilePath()) {
3947
- mkdirSync3(dirname4(file), { recursive: true });
4072
+ mkdirSync4(dirname5(file), { recursive: true });
3948
4073
  const temporary = `${file}.${process.pid}.tmp`;
3949
- writeFileSync3(temporary, `${JSON.stringify(document, null, 2)}
4074
+ writeFileSync4(temporary, `${JSON.stringify(document, null, 2)}
3950
4075
  `, "utf8");
3951
4076
  try {
3952
- renameSync3(temporary, file);
4077
+ renameSync4(temporary, file);
3953
4078
  } catch (error) {
3954
4079
  try {
3955
- unlinkSync3(temporary);
4080
+ unlinkSync4(temporary);
3956
4081
  } catch {
3957
4082
  }
3958
4083
  throw error;
@@ -4039,8 +4164,8 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
4039
4164
  }
4040
4165
 
4041
4166
  // src/image/generate.ts
4042
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4, existsSync as existsSync2, statSync } from "node:fs";
4043
- import { dirname as dirname5, join as join5, resolve as resolve2 } from "node:path";
4167
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, existsSync as existsSync2, statSync } from "node:fs";
4168
+ import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
4044
4169
  var GenerateError = class extends Error {
4045
4170
  kind;
4046
4171
  status;
@@ -4172,19 +4297,19 @@ function outputDirOf(deps, config) {
4172
4297
  const home = deps.home?.() ?? harnessHome();
4173
4298
  const dir = config.outputDir;
4174
4299
  if (/^([A-Za-z]:[\\/]|\/)/.test(dir)) return dir;
4175
- return join5(home, "dsh-model-think-level", dir);
4300
+ return join6(home, "dsh-model-think-level", dir);
4176
4301
  }
4177
4302
  function destinationOf(dir, slug, now) {
4178
- const base = join5(dir, `${slug}-${now()}.png`);
4303
+ const base = join6(dir, `${slug}-${now()}.png`);
4179
4304
  if (!existsSync2(base)) return base;
4180
4305
  for (let index = 2; ; index += 1) {
4181
- const candidate = join5(dir, `${slug}-${now()}-${index}.png`);
4306
+ const candidate = join6(dir, `${slug}-${now()}-${index}.png`);
4182
4307
  if (!existsSync2(candidate)) return candidate;
4183
4308
  }
4184
4309
  }
4185
4310
  function resolveDestination(requested, fallbackDir, slug, now) {
4186
4311
  if (requested === void 0 || requested.trim().length === 0) {
4187
- mkdirSync4(fallbackDir, { recursive: true });
4312
+ mkdirSync5(fallbackDir, { recursive: true });
4188
4313
  return destinationOf(fallbackDir, slug, now);
4189
4314
  }
4190
4315
  const target = resolve2(requested.trim());
@@ -4194,10 +4319,10 @@ function resolveDestination(requested, fallbackDir, slug, now) {
4194
4319
  } catch {
4195
4320
  }
4196
4321
  if (isDir || /[\\/]$/.test(target) || !target.toLowerCase().endsWith(".png")) {
4197
- mkdirSync4(target, { recursive: true });
4322
+ mkdirSync5(target, { recursive: true });
4198
4323
  return destinationOf(target, slug, now);
4199
4324
  }
4200
- mkdirSync4(dirname5(target), { recursive: true });
4325
+ mkdirSync5(dirname6(target), { recursive: true });
4201
4326
  if (!existsSync2(target)) return target;
4202
4327
  for (let index = 2; ; index += 1) {
4203
4328
  const candidate = target.replace(/\.png$/i, `-${index}.png`);
@@ -4265,7 +4390,7 @@ async function generateImage(deps, request) {
4265
4390
  const absolute = resolve2(path);
4266
4391
  if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4267
4392
  try {
4268
- return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync5(absolute), mime: mimeOfPath(absolute) };
4393
+ return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync6(absolute), mime: mimeOfPath(absolute) };
4269
4394
  } catch {
4270
4395
  throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4271
4396
  }
@@ -4342,7 +4467,7 @@ async function generateImage(deps, request) {
4342
4467
  for (const data of payloads) {
4343
4468
  const filePath = resolveDestination(request.outputPath, outputDirOf(deps, config), promptSlug(prompt), now);
4344
4469
  const bytes = Uint8Array.from(atob(data), (ch) => ch.charCodeAt(0));
4345
- writeFileSync4(filePath, bytes);
4470
+ writeFileSync5(filePath, bytes);
4346
4471
  images.push({ filePath, data });
4347
4472
  }
4348
4473
  if (revisions.length > 0 && deps.persistLastGood !== void 0) {
@@ -4736,19 +4861,19 @@ function imageToolHint(config) {
4736
4861
  }
4737
4862
 
4738
4863
  // src/image/legacy-cleanup.ts
4739
- import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync6, readdirSync, statSync as statSync2, writeFileSync as writeFileSync5 } from "node:fs";
4740
- import { dirname as dirname6, join as join6 } from "node:path";
4864
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
4865
+ import { dirname as dirname7, join as join7 } from "node:path";
4741
4866
  var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
4742
4867
  var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
4743
4868
  function resolveLegacyPatchFile(home = harnessHome()) {
4744
4869
  const explicit = process.env["DSH_PROFILE"];
4745
- if (explicit !== void 0 && explicit.length > 0) return join6(home, "profiles", explicit, "cordis.patch.yml");
4746
- const profilesDir = join6(home, "profiles");
4870
+ if (explicit !== void 0 && explicit.length > 0) return join7(home, "profiles", explicit, "cordis.patch.yml");
4871
+ const profilesDir = join7(home, "profiles");
4747
4872
  try {
4748
4873
  if (existsSync3(profilesDir)) {
4749
4874
  const candidates = [];
4750
4875
  for (const name2 of readdirSync(profilesDir)) {
4751
- const file = join6(profilesDir, name2, "cordis.patch.yml");
4876
+ const file = join7(profilesDir, name2, "cordis.patch.yml");
4752
4877
  if (!existsSync3(file)) continue;
4753
4878
  candidates.push({ file, mtime: statSync2(file).mtimeMs });
4754
4879
  }
@@ -4757,8 +4882,8 @@ function resolveLegacyPatchFile(home = harnessHome()) {
4757
4882
  }
4758
4883
  } catch {
4759
4884
  }
4760
- if (existsSync3(join6(home, "cordis.patch.yml"))) return join6(home, "cordis.patch.yml");
4761
- return join6(home, "profiles", "desktop", "cordis.patch.yml");
4885
+ if (existsSync3(join7(home, "cordis.patch.yml"))) return join7(home, "cordis.patch.yml");
4886
+ return join7(home, "profiles", "desktop", "cordis.patch.yml");
4762
4887
  }
4763
4888
  function markerRange(text) {
4764
4889
  const start = text.indexOf(MARK_BEGIN);
@@ -4785,7 +4910,7 @@ function mtimeOf(patchFile) {
4785
4910
  var ModifiedError = class extends Error {
4786
4911
  };
4787
4912
  function spliceOnce(patchFile, mtimeMs) {
4788
- const current = readFileSync6(patchFile, "utf8");
4913
+ const current = readFileSync7(patchFile, "utf8");
4789
4914
  const range = markerRange(current);
4790
4915
  if (range === void 0) return;
4791
4916
  let next = current.slice(0, range.start) + current.slice(range.end);
@@ -4799,9 +4924,9 @@ function spliceOnce(patchFile, mtimeMs) {
4799
4924
  } catch {
4800
4925
  }
4801
4926
  }
4802
- mkdirSync5(dirname6(patchFile), { recursive: true });
4803
- writeFileSync5(patchFile, next, "utf8");
4804
- const written = readFileSync6(patchFile, "utf8");
4927
+ mkdirSync6(dirname7(patchFile), { recursive: true });
4928
+ writeFileSync6(patchFile, next, "utf8");
4929
+ const written = readFileSync7(patchFile, "utf8");
4805
4930
  if (written !== next) throw new Error("the patch file did not hold the written bytes after the write");
4806
4931
  }
4807
4932
  function removeLegacyImageMcpPatch(home, patchFile) {
@@ -4813,7 +4938,7 @@ function removeLegacyImageMcpPatch(home, patchFile) {
4813
4938
  }
4814
4939
  let text;
4815
4940
  try {
4816
- text = readFileSync6(file, "utf8");
4941
+ text = readFileSync7(file, "utf8");
4817
4942
  } catch {
4818
4943
  return void 0;
4819
4944
  }
@@ -4914,6 +5039,39 @@ function buildAutofillPatch(providers, routeFilter = () => true, options = {}, r
4914
5039
  }
4915
5040
  return Object.keys(patchRoutes).length === 0 ? void 0 : { providers: patchRoutes };
4916
5041
  }
5042
+ function buildCompatCleanupPatch(providers) {
5043
+ if (!isRecord(providers)) return void 0;
5044
+ const patchRoutes = {};
5045
+ for (const [route, profile] of Object.entries(providers)) {
5046
+ if (!isRecord(profile)) continue;
5047
+ const api = typeof profile["api"] === "string" ? profile["api"] : "";
5048
+ if (api.length === 0) continue;
5049
+ const patchProfile = {};
5050
+ const routeCompat = isRecord(profile["compat"]) ? stripForeignCompat(profile["compat"], api) : void 0;
5051
+ if (routeCompat !== void 0) patchProfile["compat"] = routeCompat;
5052
+ const rawModels = Array.isArray(profile["models"]) ? profile["models"] : void 0;
5053
+ if (rawModels !== void 0 && rawModels.length > 0) {
5054
+ const nextModels = [];
5055
+ let changed = false;
5056
+ for (const row of rawModels) {
5057
+ if (!isRecord(row) || !isRecord(row["compat"])) {
5058
+ nextModels.push(row);
5059
+ continue;
5060
+ }
5061
+ const cleaned = stripForeignCompat(row["compat"], api);
5062
+ if (cleaned === void 0) {
5063
+ nextModels.push(row);
5064
+ continue;
5065
+ }
5066
+ changed = true;
5067
+ nextModels.push({ ...row, compat: cleaned });
5068
+ }
5069
+ if (changed) patchProfile["models"] = nextModels;
5070
+ }
5071
+ if (Object.keys(patchProfile).length > 0) patchRoutes[route] = patchProfile;
5072
+ }
5073
+ return Object.keys(patchRoutes).length === 0 ? void 0 : { providers: patchRoutes };
5074
+ }
4917
5075
  function stripNewCompatKeysDeep(patch) {
4918
5076
  const providers = isRecord(patch["providers"]) ? patch["providers"] : void 0;
4919
5077
  if (providers === void 0) return void 0;
@@ -4953,9 +5111,9 @@ function backfillRolePin(model, providers, route) {
4953
5111
  }
4954
5112
 
4955
5113
  // src/fingerprint/bank.ts
4956
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "node:fs";
5114
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "node:fs";
4957
5115
  import { fileURLToPath } from "node:url";
4958
- import { dirname as dirname7, join as join7 } from "node:path";
5116
+ import { dirname as dirname8, join as join8 } from "node:path";
4959
5117
 
4960
5118
  // src/fingerprint/core.ts
4961
5119
  var VALUE_MIN = 1;
@@ -5240,10 +5398,10 @@ function parseBank(raw) {
5240
5398
  }
5241
5399
  function bankCandidates() {
5242
5400
  const candidates = [];
5243
- let dir = dirname7(fileURLToPath(import.meta.url));
5401
+ let dir = dirname8(fileURLToPath(import.meta.url));
5244
5402
  for (let depth = 0; depth < 5; depth += 1) {
5245
- candidates.push(join7(dir, "assets", "unified_bank.json"));
5246
- const parent = dirname7(dir);
5403
+ candidates.push(join8(dir, "assets", "unified_bank.json"));
5404
+ const parent = dirname8(dir);
5247
5405
  if (parent === dir) break;
5248
5406
  dir = parent;
5249
5407
  }
@@ -5260,7 +5418,7 @@ function bankPath() {
5260
5418
  var cached;
5261
5419
  function loadBankSync() {
5262
5420
  if (cached !== void 0) return cached;
5263
- cached = parseBank(JSON.parse(readFileSync7(bankPath(), "utf8")));
5421
+ cached = parseBank(JSON.parse(readFileSync8(bankPath(), "utf8")));
5264
5422
  return cached;
5265
5423
  }
5266
5424
  function summarizeBank(bank) {
@@ -5529,8 +5687,8 @@ async function runChallenge(options) {
5529
5687
  }
5530
5688
 
5531
5689
  // src/fingerprint/store.ts
5532
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync8, renameSync as renameSync4, unlinkSync as unlinkSync4, writeFileSync as writeFileSync6 } from "node:fs";
5533
- import { dirname as dirname8, join as join8 } from "node:path";
5690
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync9, renameSync as renameSync5, unlinkSync as unlinkSync5, writeFileSync as writeFileSync7 } from "node:fs";
5691
+ import { dirname as dirname9, join as join9 } from "node:path";
5534
5692
  var STATUSES = /* @__PURE__ */ new Set(["identified", "doubtful", "failed"]);
5535
5693
  function emptyFingerprintStore(bankBuiltAt2 = "") {
5536
5694
  return { version: 1, bankBuiltAt: bankBuiltAt2, records: {} };
@@ -5539,7 +5697,7 @@ function recordKeyOf(provider, model) {
5539
5697
  return `${provider}\0${model}`;
5540
5698
  }
5541
5699
  function fingerprintFilePath(home = harnessHome()) {
5542
- return join8(home, "dsh-model-think-level", "fingerprint.json");
5700
+ return join9(home, "dsh-model-think-level", "fingerprint.json");
5543
5701
  }
5544
5702
  function finiteNumber(value, fallback) {
5545
5703
  return typeof value === "number" && Number.isFinite(value) ? value : fallback;
@@ -5657,7 +5815,7 @@ function parseFingerprintStore(raw, bankBuiltAt2 = "") {
5657
5815
  function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
5658
5816
  let text;
5659
5817
  try {
5660
- text = readFileSync8(file, "utf8");
5818
+ text = readFileSync9(file, "utf8");
5661
5819
  } catch (error) {
5662
5820
  if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
5663
5821
  return emptyFingerprintStore(bankBuiltAt2);
@@ -5673,15 +5831,15 @@ function readFingerprintStore(bankBuiltAt2 = "", file = fingerprintFilePath()) {
5673
5831
  return parseFingerprintStore(raw, bankBuiltAt2);
5674
5832
  }
5675
5833
  function writeFingerprintStore(document, file = fingerprintFilePath()) {
5676
- mkdirSync6(dirname8(file), { recursive: true });
5834
+ mkdirSync7(dirname9(file), { recursive: true });
5677
5835
  const temporary = `${file}.${process.pid}.tmp`;
5678
- writeFileSync6(temporary, `${JSON.stringify(document, null, 2)}
5836
+ writeFileSync7(temporary, `${JSON.stringify(document, null, 2)}
5679
5837
  `, "utf8");
5680
5838
  try {
5681
- renameSync4(temporary, file);
5839
+ renameSync5(temporary, file);
5682
5840
  } catch (error) {
5683
5841
  try {
5684
- unlinkSync4(temporary);
5842
+ unlinkSync5(temporary);
5685
5843
  } catch {
5686
5844
  }
5687
5845
  throw error;
@@ -5739,7 +5897,8 @@ var inject = ["settings", "llm"];
5739
5897
  var PI_NS = PI_AI_NS;
5740
5898
  var BOOT_RETRY_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
5741
5899
  var PROBE_TIMEOUT_MS = 15e3;
5742
- var BALANCE_TIMEOUT_MS = 3e4;
5900
+ var BALANCE_TIMEOUT_MS = 8e3;
5901
+ var CREDENTIAL_IPC_BUDGET_MS = 1e4;
5743
5902
  var FINGERPRINT_CHALLENGE_TIMEOUT_MS = 12e4;
5744
5903
  function fingerprintTimingOf(outcomes) {
5745
5904
  const accepted = outcomes.filter((outcome) => outcome.ok && typeof outcome.durationMs === "number");
@@ -5858,25 +6017,42 @@ async function storeCredential(credentials, ref, value) {
5858
6017
  if (credentials === void 0 || typeof set !== "function") {
5859
6018
  return "this deployment cannot write the credential store";
5860
6019
  }
6020
+ invalidateCredentialDisplay(credentials, ref);
5861
6021
  try {
5862
6022
  const answer = await set.call(credentials, ref, value);
5863
6023
  if (!isRefusal(answer)) return void 0;
5864
6024
  return refusalMessage(answer) ?? `the credential store refused ${ref}`;
5865
6025
  } catch (error) {
5866
6026
  return error instanceof Error ? error.message : String(error);
6027
+ } finally {
6028
+ invalidateCredentialDisplay(credentials, ref);
5867
6029
  }
5868
6030
  }
5869
- async function forgetCredential(credentials, ref) {
6031
+ async function forgetCredential(credentials, ref, budgetMs) {
5870
6032
  const unset = credentials?.unset;
5871
6033
  if (credentials === void 0 || typeof unset !== "function") {
5872
6034
  return "this deployment cannot write the credential store";
5873
6035
  }
6036
+ invalidateCredentialDisplay(credentials, ref);
6037
+ let timer;
5874
6038
  try {
5875
- const answer = await unset.call(credentials, ref);
6039
+ const answer = await Promise.race([
6040
+ unset.call(credentials, ref),
6041
+ budgetMs === void 0 ? new Promise(() => {
6042
+ }) : new Promise((_, reject) => {
6043
+ timer = setTimeout(
6044
+ () => reject(new Error(`the credential store did not answer within ${Math.round(budgetMs / 1e3)}s`)),
6045
+ budgetMs
6046
+ );
6047
+ })
6048
+ ]);
5876
6049
  if (!isRefusal(answer)) return void 0;
5877
6050
  return refusalMessage(answer) ?? `the credential store refused to forget ${ref}`;
5878
6051
  } catch (error) {
5879
6052
  return error instanceof Error ? error.message : String(error);
6053
+ } finally {
6054
+ if (timer !== void 0) clearTimeout(timer);
6055
+ invalidateCredentialDisplay(credentials, ref);
5880
6056
  }
5881
6057
  }
5882
6058
  var HostReadError = class extends Error {
@@ -5904,6 +6080,87 @@ async function resolveCredential(credentials, ref) {
5904
6080
  function holdsNothing(fact) {
5905
6081
  return fact !== void 0 && fact.configured === false && fact.masked === void 0;
5906
6082
  }
6083
+ var CREDENTIAL_DISPLAY_TTL_MS = 5e3;
6084
+ var CREDENTIAL_DISPLAY_MAX_REFS = 512;
6085
+ var credentialDisplayReads = /* @__PURE__ */ new WeakMap();
6086
+ function invalidateCredentialDisplay(credentials, ref) {
6087
+ if (credentials !== void 0) credentialDisplayReads.get(credentials)?.delete(ref);
6088
+ }
6089
+ async function displayCredentialFacts(credentials, refs, budgetMs) {
6090
+ if (credentials === void 0 || refs.length === 0) return {};
6091
+ let cache = credentialDisplayReads.get(credentials);
6092
+ if (cache === void 0) {
6093
+ cache = /* @__PURE__ */ new Map();
6094
+ credentialDisplayReads.set(credentials, cache);
6095
+ }
6096
+ const now = Date.now();
6097
+ for (const [ref, read] of cache) if (read.expiresAt <= now) cache.delete(ref);
6098
+ const selected = /* @__PURE__ */ new Map();
6099
+ const missing = [];
6100
+ for (const ref of new Set(refs)) {
6101
+ let read = cache.get(ref);
6102
+ if (read === void 0) {
6103
+ read = { expiresAt: now + CREDENTIAL_DISPLAY_TTL_MS, settled: Promise.resolve() };
6104
+ cache.set(ref, read);
6105
+ missing.push(ref);
6106
+ }
6107
+ selected.set(ref, read);
6108
+ }
6109
+ const described = missing.length === 0 || typeof credentials.describe !== "function" ? Promise.resolve(void 0) : (async () => {
6110
+ try {
6111
+ const answer = await credentials.describe?.(missing);
6112
+ return isRefusal(answer) ? void 0 : describeRecords(answer);
6113
+ } catch {
6114
+ return void 0;
6115
+ }
6116
+ })();
6117
+ for (const ref of missing) {
6118
+ const read = selected.get(ref);
6119
+ const resolved = (async () => {
6120
+ try {
6121
+ const value = await resolveCredential(credentials, ref);
6122
+ const masked = value === void 0 ? void 0 : maskKeyValue(value);
6123
+ read.resolved = masked === void 0 || masked.length === 0 ? { configured: value !== void 0 } : { configured: true, masked };
6124
+ return true;
6125
+ } catch {
6126
+ return false;
6127
+ }
6128
+ })();
6129
+ const metadata = described.then((records) => {
6130
+ const info = records?.[ref];
6131
+ if (isRecord(info) && typeof info["configured"] === "boolean") read.described = info["configured"];
6132
+ return typeof credentials.describe !== "function" || read.described !== void 0;
6133
+ });
6134
+ read.settled = Promise.all([resolved, metadata]).then(([resolvedOK, describedOK]) => {
6135
+ if (cache.get(ref) !== read) return;
6136
+ read.expiresAt = resolvedOK && describedOK ? Date.now() + CREDENTIAL_DISPLAY_TTL_MS : 0;
6137
+ });
6138
+ }
6139
+ while (cache.size > CREDENTIAL_DISPLAY_MAX_REFS) {
6140
+ const oldest = cache.keys().next().value;
6141
+ if (oldest === void 0) break;
6142
+ cache.delete(oldest);
6143
+ }
6144
+ let timer;
6145
+ try {
6146
+ await Promise.race([
6147
+ Promise.all([...selected.values()].map((read) => read.settled)),
6148
+ new Promise((resolve3) => {
6149
+ timer = setTimeout(resolve3, budgetMs);
6150
+ })
6151
+ ]);
6152
+ } finally {
6153
+ if (timer !== void 0) clearTimeout(timer);
6154
+ }
6155
+ const out = {};
6156
+ for (const [ref, read] of selected) {
6157
+ if (cache.get(ref) !== read) continue;
6158
+ const configured = read.described ?? read.resolved?.configured;
6159
+ if (configured === void 0) continue;
6160
+ out[ref] = read.resolved?.masked === void 0 ? { configured } : { configured, masked: read.resolved.masked };
6161
+ }
6162
+ return out;
6163
+ }
5907
6164
  async function credentialFacts(credentials, refs, budgetMs) {
5908
6165
  const described = {};
5909
6166
  const resolvedFacts = {};
@@ -5948,8 +6205,8 @@ async function credentialFacts(credentials, refs, budgetMs) {
5948
6205
  }
5949
6206
  return out;
5950
6207
  }
5951
- async function credentialConfigured(credentials, refs) {
5952
- const facts = await credentialFacts(credentials, refs);
6208
+ async function credentialConfigured(credentials, refs, budgetMs) {
6209
+ const facts = await credentialFacts(credentials, refs, budgetMs);
5953
6210
  const out = {};
5954
6211
  for (const ref of refs) {
5955
6212
  const configured = facts[ref]?.configured;
@@ -6065,32 +6322,33 @@ function apply(ctx, config = {}) {
6065
6322
  uaOverride: config.uaOverride !== false
6066
6323
  };
6067
6324
  const settings = ctx.settings;
6068
- let piSectionCache;
6069
- let piSectionCached = false;
6070
- const piSection = (required = false) => {
6071
- if (piSectionCached) return piSectionCache;
6072
- let value;
6325
+ let piDescriptorCache;
6326
+ let piDescriptorCached = false;
6327
+ const piDescriptor = (required = false) => {
6328
+ if (piDescriptorCached) return piDescriptorCache;
6329
+ let descriptor;
6073
6330
  try {
6074
- value = settings.describe().find((entry) => entry.ns === PI_NS)?.value;
6331
+ descriptor = settings.describe().find((entry) => entry.ns === PI_NS);
6075
6332
  } catch {
6076
6333
  if (required) throw new HostReadError("the llm-pi-ai settings could not be read");
6077
6334
  return void 0;
6078
6335
  }
6079
- if (value === void 0) {
6336
+ if (descriptor === void 0 || !isRecord(descriptor.value)) {
6080
6337
  if (required) throw new HostReadError("the llm-pi-ai settings entry is unavailable");
6081
6338
  return void 0;
6082
6339
  }
6083
- piSectionCache = value;
6084
- piSectionCached = true;
6085
- return value;
6340
+ piDescriptorCache = descriptor;
6341
+ piDescriptorCached = true;
6342
+ return descriptor;
6086
6343
  };
6344
+ const piSection = (required = false) => piDescriptor(required)?.value;
6087
6345
  ctx.on("settings/document-updated", (ns) => {
6088
- if (ns === PI_NS) piSectionCached = false;
6346
+ if (ns === PI_NS) piDescriptorCached = false;
6089
6347
  });
6090
6348
  if (resolved.autofill) {
6091
6349
  const autofillOnce = async () => {
6092
- const descriptor = settings.describe().find((entry) => entry.ns === PI_NS);
6093
- if (!isRecord(descriptor?.value)) return false;
6350
+ const descriptor = piDescriptor();
6351
+ if (descriptor === void 0) return false;
6094
6352
  const user = descriptor?.user;
6095
6353
  const userProviders = isRecord(user) && isRecord(user["providers"]) ? user["providers"] : void 0;
6096
6354
  if (userProviders === void 0) return true;
@@ -6127,6 +6385,44 @@ function apply(ctx, config = {}) {
6127
6385
  };
6128
6386
  bootFill(0);
6129
6387
  }
6388
+ {
6389
+ const logGuardFailure = (error) => {
6390
+ console.error(`[dsh-model-think-level] compat cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
6391
+ };
6392
+ const guardTimers = /* @__PURE__ */ new Set();
6393
+ ctx.effect(() => () => {
6394
+ for (const timer of guardTimers) clearTimeout(timer);
6395
+ guardTimers.clear();
6396
+ }, "dsh-model-think-level: compat-guard boot retries");
6397
+ const sweepOnce = async () => {
6398
+ const descriptor = piDescriptor();
6399
+ if (descriptor === void 0) return false;
6400
+ const user = descriptor.user;
6401
+ const userProviders = isRecord(user) && isRecord(user["providers"]) ? user["providers"] : void 0;
6402
+ if (userProviders === void 0) return true;
6403
+ const patch = buildCompatCleanupPatch(userProviders);
6404
+ if (patch === void 0) return true;
6405
+ try {
6406
+ await settings.update(PI_NS, patch, descriptor.revision);
6407
+ } catch (error) {
6408
+ logGuardFailure(error);
6409
+ piDescriptorCached = false;
6410
+ return false;
6411
+ }
6412
+ return true;
6413
+ };
6414
+ const bootSweep = (attempt) => {
6415
+ void sweepOnce().then((ready) => {
6416
+ if (ready || attempt >= resolved.bootRetryDelaysMs.length) return;
6417
+ const timer = setTimeout(() => {
6418
+ guardTimers.delete(timer);
6419
+ bootSweep(attempt + 1);
6420
+ }, resolved.bootRetryDelaysMs[attempt]);
6421
+ guardTimers.add(timer);
6422
+ }, logGuardFailure);
6423
+ };
6424
+ bootSweep(0);
6425
+ }
6130
6426
  if (resolved.defaultGuard) {
6131
6427
  ctx.inject(["llm"], (llmCtx) => {
6132
6428
  const llm = llmCtx.llm;
@@ -6193,46 +6489,71 @@ function apply(ctx, config = {}) {
6193
6489
  profile["headers"]
6194
6490
  ]).sort(([a], [b]) => String(a).localeCompare(String(b))));
6195
6491
  let catalogueSourceStamp = catalogueSource();
6196
- const invalidateListings = () => {
6197
- probeRouteCache.clear();
6198
- listingCache.clear();
6199
- };
6200
- const keyProbeRuns = /* @__PURE__ */ new Map();
6201
- const keyProbeTimers = /* @__PURE__ */ new Map();
6202
- ctx.effect(() => () => {
6203
- for (const timer of keyProbeTimers.values()) clearTimeout(timer);
6204
- keyProbeTimers.clear();
6205
- }, "dsh-model-think-level: scope probe timers");
6206
- const KEY_PROBE_DELAY_MS = 600;
6207
- const keyProbeStamps = /* @__PURE__ */ new Map();
6208
- let keyProbeStampsReady = false;
6209
- const keyProbeSignature = (profile) => JSON.stringify([
6210
- profile["api"],
6211
- profile["baseURL"],
6212
- profile["apiKeyEnv"],
6213
- profile["headers"],
6214
- Array.isArray(profile["models"]) ? profile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : []
6215
- ]);
6216
- const reconcileKeyProbeStamps = () => {
6217
- const providers = providersOf();
6218
- if (!keyProbeStampsReady) {
6219
- keyProbeStampsReady = true;
6220
- for (const [route, profile] of Object.entries(providers)) {
6221
- if (isRecord(profile)) keyProbeStamps.set(route, keyProbeSignature(profile));
6222
- }
6492
+ const invalidateListings = (route) => {
6493
+ if (route === void 0) {
6494
+ probeRouteCache.clear();
6495
+ listingCache.clear();
6223
6496
  return;
6224
6497
  }
6225
- for (const route of Array.from(keyProbeStamps.keys())) {
6226
- if (!isRecord(providers[route])) keyProbeStamps.delete(route);
6498
+ const prefix = `${route}\0`;
6499
+ for (const key of Array.from(listingCache.keys())) {
6500
+ if (key.startsWith(prefix)) listingCache.delete(key);
6227
6501
  }
6228
- for (const [route, profile] of Object.entries(providers)) {
6502
+ };
6503
+ const sweepVanishedRoutes = () => {
6504
+ if (piSection() === void 0) return false;
6505
+ const live = providersOf();
6506
+ const indexFile = keyIndexFilePath();
6507
+ let index;
6508
+ try {
6509
+ index = readKeyIndex(indexFile);
6510
+ } catch {
6511
+ return true;
6512
+ }
6513
+ const stale = /* @__PURE__ */ new Set();
6514
+ for (const route of Object.keys(index.providers)) if (!(route in live)) stale.add(route);
6515
+ for (const route of Object.keys(index.endpoints ?? {})) if (!(route in live)) stale.add(route);
6516
+ for (const route of Object.keys(index.balances ?? {})) if (!(route in live)) stale.add(route);
6517
+ if (stale.size === 0) return true;
6518
+ const survivors = /* @__PURE__ */ new Set();
6519
+ for (const [route, entries] of Object.entries(index.providers)) {
6520
+ if (stale.has(route)) continue;
6521
+ for (const entry of entries) survivors.add(entry.ref);
6522
+ }
6523
+ for (const profile of Object.values(live)) {
6229
6524
  if (!isRecord(profile)) continue;
6230
- const signature = keyProbeSignature(profile);
6231
- if (keyProbeStamps.get(route) === signature) continue;
6232
- keyProbeStamps.set(route, signature);
6233
- scheduleKeyProbe(route);
6525
+ const seat = enabledRefOf(profile);
6526
+ if (seat !== void 0) survivors.add(seat);
6234
6527
  }
6528
+ const credentials = ctx.get("credentials");
6529
+ let swept = false;
6530
+ for (const route of stale) {
6531
+ const refs = keyEntriesOf(index, route).map((entry) => entry.ref);
6532
+ try {
6533
+ updateKeyIndex((current) => withoutRoute(current, route), indexFile);
6534
+ } catch (error) {
6535
+ console.error(`[dsh-model-think-level] key route cleanup for "${route}" failed: ${error instanceof Error ? error.message : String(error)}`);
6536
+ continue;
6537
+ }
6538
+ swept = true;
6539
+ for (const ref of refs) {
6540
+ forgetServes(route, ref);
6541
+ const here = `${route}\0${ref}`;
6542
+ lastKnownScopes.delete(here);
6543
+ lastKnownRecords.delete(here);
6544
+ if (survivors.has(ref)) continue;
6545
+ void forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS).then((refused) => {
6546
+ if (refused !== void 0) {
6547
+ console.error(`[dsh-model-think-level] credential cleanup for "${ref}" failed: ${refused}`);
6548
+ }
6549
+ });
6550
+ }
6551
+ invalidateListings(route);
6552
+ }
6553
+ if (swept) refreshKeyScopes();
6554
+ return true;
6235
6555
  };
6556
+ const keyProbeRuns = /* @__PURE__ */ new Map();
6236
6557
  const probeRouteKeys = async (route) => {
6237
6558
  let profile;
6238
6559
  try {
@@ -6255,7 +6576,7 @@ function apply(ctx, config = {}) {
6255
6576
  const seat = enabledRefOf(profile);
6256
6577
  const keys = listed.map((entry) => ({ ref: entry.ref, entry }));
6257
6578
  if (seat !== void 0 && !listed.some((entry) => entry.ref === seat)) keys.push({ ref: seat, entry: void 0 });
6258
- if (keys.length === 0) return;
6579
+ if (keys.length < 2) return;
6259
6580
  const credentials = ctx.get("credentials");
6260
6581
  const values = await Promise.all(keys.map(async (key) => {
6261
6582
  try {
@@ -6332,14 +6653,6 @@ function apply(ctx, config = {}) {
6332
6653
  keyProbeRuns.set(route, run);
6333
6654
  return run;
6334
6655
  };
6335
- const scheduleKeyProbe = (route) => {
6336
- if (keyProbeTimers.has(route)) return;
6337
- const timer = setTimeout(() => {
6338
- keyProbeTimers.delete(route);
6339
- void runKeyProbe(route);
6340
- }, KEY_PROBE_DELAY_MS);
6341
- keyProbeTimers.set(route, timer);
6342
- };
6343
6656
  const headerRetryTimers = /* @__PURE__ */ new Set();
6344
6657
  let headerRetryAttempt = 0;
6345
6658
  const stopHeaderRetries = () => {
@@ -6380,15 +6693,35 @@ function apply(ctx, config = {}) {
6380
6693
  if (ns === PI_NS) {
6381
6694
  refreshHeaders();
6382
6695
  refreshKeyScopes();
6696
+ sweepVanishedRoutes();
6383
6697
  syncImageConfigNow();
6384
6698
  const source = catalogueSource();
6385
6699
  if (source !== catalogueSourceStamp) {
6386
6700
  catalogueSourceStamp = source;
6387
6701
  invalidateListings();
6388
6702
  }
6389
- reconcileKeyProbeStamps();
6390
6703
  }
6391
6704
  });
6705
+ {
6706
+ const sweepTimers = /* @__PURE__ */ new Set();
6707
+ ctx.effect(() => () => {
6708
+ for (const timer of sweepTimers) clearTimeout(timer);
6709
+ sweepTimers.clear();
6710
+ }, "dsh-model-think-level: route-sweep boot retries");
6711
+ const bootRouteSweep = (attempt) => {
6712
+ void Promise.resolve().then(() => sweepVanishedRoutes()).then((ready) => {
6713
+ if (ready || attempt >= resolved.bootRetryDelaysMs.length) return;
6714
+ const timer = setTimeout(() => {
6715
+ sweepTimers.delete(timer);
6716
+ bootRouteSweep(attempt + 1);
6717
+ }, resolved.bootRetryDelaysMs[attempt]);
6718
+ sweepTimers.add(timer);
6719
+ }, (error) => {
6720
+ console.error(`[dsh-model-think-level] route sweep failed: ${error instanceof Error ? error.message : String(error)}`);
6721
+ });
6722
+ };
6723
+ bootRouteSweep(0);
6724
+ }
6392
6725
  overlaySource.keys = async ({ route, model }) => {
6393
6726
  const scopes = keyScopes.current[route] ?? [];
6394
6727
  if (scopes.length === 0) return [];
@@ -6933,7 +7266,7 @@ function apply(ctx, config = {}) {
6933
7266
  const listed = keyEntriesOf(document, route);
6934
7267
  const refs = listed.map((entry) => entry.ref);
6935
7268
  const probed = seat !== void 0 && !refs.includes(seat) ? [...refs, seat] : refs;
6936
- const facts = await credentialFacts(credentials, probed, 250);
7269
+ const facts = await displayCredentialFacts(credentials, probed, 250);
6937
7270
  if (seat !== void 0 && !refs.includes(seat) && !holdsNothing(facts[seat])) refs.push(seat);
6938
7271
  const now = Date.now();
6939
7272
  const entries = refs.map((ref2) => {
@@ -6967,7 +7300,7 @@ function apply(ctx, config = {}) {
6967
7300
  return view;
6968
7301
  });
6969
7302
  const endpoints = document.endpoints?.[route];
6970
- const probing = keyProbeTimers.has(route) || keyProbeRuns.has(route);
7303
+ const probing = keyProbeRuns.has(route);
6971
7304
  return {
6972
7305
  ok: true,
6973
7306
  route,
@@ -7021,7 +7354,7 @@ function apply(ctx, config = {}) {
7021
7354
  let seatEmpty = false;
7022
7355
  if (active !== void 0) {
7023
7356
  try {
7024
- seatEmpty = holdsNothing((await credentialFacts(credentials, [active]))[active]);
7357
+ seatEmpty = holdsNothing((await credentialFacts(credentials, [active], CREDENTIAL_IPC_BUDGET_MS))[active]);
7025
7358
  } catch {
7026
7359
  seatEmpty = false;
7027
7360
  }
@@ -7039,13 +7372,13 @@ function apply(ctx, config = {}) {
7039
7372
  }
7040
7373
  const listedRefs = keyEntriesOf(readKeyIndex(indexFile), route).map((entry) => entry.ref);
7041
7374
  const slotCandidates = active !== void 0 && listedRefs.includes(active) ? [active, ...listedRefs.filter((candidate) => candidate !== active)] : listedRefs;
7042
- const slotFacts = slotCandidates.length > 0 ? await credentialFacts(credentials, slotCandidates) : {};
7375
+ const slotFacts = slotCandidates.length > 0 ? await credentialFacts(credentials, slotCandidates, CREDENTIAL_IPC_BUDGET_MS) : {};
7043
7376
  const emptySlot = slotCandidates.find((candidate) => holdsNothing(slotFacts[candidate]));
7044
7377
  let created = emptySlot !== void 0 && await resolveCredential(credentials, emptySlot) === void 0 ? emptySlot : void 0;
7045
7378
  if (created === void 0) {
7046
7379
  created = nextKeyRef(route, taken);
7047
7380
  for (; ; ) {
7048
- const facts = await credentialFacts(credentials, [created]);
7381
+ const facts = await credentialFacts(credentials, [created], CREDENTIAL_IPC_BUDGET_MS);
7049
7382
  const configured = facts[created]?.configured;
7050
7383
  if (configured === void 0) throw new HostReadError("the credential store could not confirm a free reference");
7051
7384
  if (!configured && await resolveCredential(credentials, created) === void 0) break;
@@ -7054,7 +7387,7 @@ function apply(ctx, config = {}) {
7054
7387
  }
7055
7388
  }
7056
7389
  const seatBefore = active;
7057
- const seatIsEmpty = seatBefore !== void 0 && seatBefore !== created && holdsNothing((await credentialFacts(credentials, [seatBefore]))[seatBefore]);
7390
+ const seatIsEmpty = seatBefore !== void 0 && seatBefore !== created && holdsNothing((await credentialFacts(credentials, [seatBefore], CREDENTIAL_IPC_BUDGET_MS))[seatBefore]);
7058
7391
  const refused = await storeCredential(credentials, created, value);
7059
7392
  if (refused !== void 0) {
7060
7393
  refuse(refused);
@@ -7069,7 +7402,7 @@ function apply(ctx, config = {}) {
7069
7402
  if (failed !== void 0) throw new Error(failed);
7070
7403
  }
7071
7404
  } catch (error) {
7072
- const rollback = await forgetCredential(credentials, created);
7405
+ const rollback = await forgetCredential(credentials, created, CREDENTIAL_IPC_BUDGET_MS);
7073
7406
  if (rollback === void 0 && indexed) {
7074
7407
  updateKeyIndex((document) => withoutKeyEntry(document, route, created), indexFile);
7075
7408
  }
@@ -7204,7 +7537,7 @@ function apply(ctx, config = {}) {
7204
7537
  refuse("that key is not listed for this provider");
7205
7538
  return;
7206
7539
  }
7207
- const configured = (await credentialConfigured(credentials, [ref]))[ref];
7540
+ const configured = (await credentialConfigured(credentials, [ref], CREDENTIAL_IPC_BUDGET_MS))[ref];
7208
7541
  if (configured === void 0) throw new HostReadError("the credential store could not read the reference");
7209
7542
  const wasEnabled = ref === enabledNow();
7210
7543
  const remaining = keyEntriesOf(document, route).map((candidate) => candidate.ref).filter((candidate) => candidate !== ref);
@@ -7219,8 +7552,9 @@ function apply(ctx, config = {}) {
7219
7552
  try {
7220
7553
  updateKeyIndex((document2) => withoutKeyEntry(document2, route, ref), indexFile);
7221
7554
  forgetServes(route, ref);
7555
+ invalidateCredentialDisplay(credentials, ref);
7222
7556
  if (configured) {
7223
- const refused = await forgetCredential(credentials, ref);
7557
+ const refused = await forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS);
7224
7558
  if (refused !== void 0) throw new Error(refused);
7225
7559
  }
7226
7560
  } catch (error) {
@@ -7242,16 +7576,23 @@ function apply(ctx, config = {}) {
7242
7576
  }
7243
7577
  throw new Error([error instanceof Error ? error.message : String(error), ...failures].join("; "));
7244
7578
  }
7579
+ } else if (op === "probe") {
7580
+ const listed = keyEntriesOf(readKeyIndex(indexFile), route);
7581
+ const seat = enabledNow();
7582
+ const distinct = new Set(listed.map((entry) => entry.ref));
7583
+ if (seat !== void 0) distinct.add(seat);
7584
+ if (distinct.size < 2) {
7585
+ refuse("a scope probe needs a second key; a single key serves whatever it serves");
7586
+ return;
7587
+ }
7588
+ void runKeyProbe(route);
7245
7589
  } else {
7246
7590
  refuse(`unknown key operation "${op}"`);
7247
7591
  return;
7248
7592
  }
7249
7593
  refreshKeyScopes();
7250
7594
  if (["add", "remove", "value", "protocol", "endpoints", "enable"].includes(op)) {
7251
- invalidateListings();
7252
- }
7253
- if (["add", "value", "protocol", "endpoints"].includes(op)) {
7254
- scheduleKeyProbe(route);
7595
+ invalidateListings(route);
7255
7596
  }
7256
7597
  releaseMutation?.();
7257
7598
  releaseMutation = void 0;
@@ -7402,6 +7743,39 @@ function apply(ctx, config = {}) {
7402
7743
  }),
7403
7744
  "dsh-model-think-level: autofill config route"
7404
7745
  );
7746
+ ctx.effect(
7747
+ () => webServerCtx.webServer.register({
7748
+ kind: "exact",
7749
+ path: ORDER_PATH,
7750
+ handler: async (req, res) => {
7751
+ res.setHeader("cache-control", "no-store");
7752
+ if (!isTrustedRequest(req)) {
7753
+ sendJson(res, 403, { ok: false, error: "forbidden" });
7754
+ return;
7755
+ }
7756
+ if (req.method === "GET") {
7757
+ sendJson(res, 200, { ok: true, data: readUiOrder(uiOrderFilePath()) });
7758
+ return;
7759
+ }
7760
+ if (req.method !== "POST") {
7761
+ sendJson(res, 405, { ok: false, error: "method not allowed" });
7762
+ return;
7763
+ }
7764
+ const body = await readJsonBody(req, 65536);
7765
+ if (body === void 0) {
7766
+ sendJson(res, 400, { ok: false, error: "the body is not a JSON document" });
7767
+ return;
7768
+ }
7769
+ try {
7770
+ const data = commitUiOrder(body, Date.now());
7771
+ sendJson(res, 200, { ok: true, data });
7772
+ } catch (error) {
7773
+ sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
7774
+ }
7775
+ }
7776
+ }),
7777
+ "dsh-model-think-level: ui-order route"
7778
+ );
7405
7779
  ctx.effect(
7406
7780
  () => webServerCtx.webServer.register({
7407
7781
  kind: "exact",
@@ -7698,53 +8072,6 @@ function apply(ctx, config = {}) {
7698
8072
  sendJson(res, 400, { ok: false, error: "a JSON body is required" });
7699
8073
  return;
7700
8074
  }
7701
- const op = typeof body["op"] === "string" ? body["op"] : "save";
7702
- if (op === "test") {
7703
- const id = typeof body["id"] === "string" ? body["id"] : "";
7704
- const config2 = readImageConfig();
7705
- const model = resolveImageModel(config2, id);
7706
- if (model === void 0) {
7707
- sendJson(res, 400, { ok: false, error: `no image model "${id}"` });
7708
- return;
7709
- }
7710
- if (model.api !== "images") {
7711
- sendJson(res, 200, { ok: true, status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
7712
- return;
7713
- }
7714
- const smallest = [...model.params.sizes].sort((a, b) => {
7715
- const area = (size) => size.split("x").reduce((sum, part) => sum * (Number(part) || 0), 1);
7716
- return area(a) - area(b);
7717
- })[0] ?? "1024x1024";
7718
- try {
7719
- await generateImage(imageGenerateDeps, {
7720
- model: model.id,
7721
- prompt: "endpoint test",
7722
- size: smallest,
7723
- n: 1
7724
- });
7725
- updateImageConfig((document) => ({
7726
- ...document,
7727
- models: document.models.map((entry) => entry.id === model.id ? { ...entry, endpoint: { kind: "images", status: "ok", checkedAt: (/* @__PURE__ */ new Date()).toISOString() } } : entry)
7728
- }));
7729
- sendJson(res, 200, { ok: true, status: "ok", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
7730
- } catch (error) {
7731
- const kind = error instanceof Error && "kind" in error ? String(error.kind) : "upstream";
7732
- if (kind === "endpoint") {
7733
- updateImageConfig((document) => ({
7734
- ...document,
7735
- models: document.models.map((entry) => entry.id === model.id ? { ...entry, endpoint: { kind: "images", status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() } } : entry)
7736
- }));
7737
- sendJson(res, 200, { ok: true, status: "unsupported", checkedAt: (/* @__PURE__ */ new Date()).toISOString() });
7738
- return;
7739
- }
7740
- sendJson(res, 200, {
7741
- ok: false,
7742
- error: error instanceof Error ? error.message : String(error),
7743
- status: model.endpoint.status
7744
- });
7745
- }
7746
- return;
7747
- }
7748
8075
  try {
7749
8076
  updateImageConfig((document) => {
7750
8077
  let next = document;
@@ -7778,51 +8105,6 @@ function apply(ctx, config = {}) {
7778
8105
  }),
7779
8106
  "dsh-model-think-level: image config route"
7780
8107
  );
7781
- ctx.effect(
7782
- () => webServerCtx.webServer.register({
7783
- kind: "exact",
7784
- path: IMAGE_GENERATE_PATH,
7785
- handler: async (req, res) => {
7786
- res.setHeader("cache-control", "no-store");
7787
- if (!isTrustedRequest(req)) {
7788
- sendJson(res, 403, { ok: false, error: "forbidden" });
7789
- return;
7790
- }
7791
- if (req.method !== "POST") {
7792
- sendJson(res, 405, { ok: false, error: "method not allowed" });
7793
- return;
7794
- }
7795
- const body = await readJsonBody(req, 65536);
7796
- if (!isRecord(body) || typeof body["prompt"] !== "string" || body["prompt"].trim().length === 0) {
7797
- sendJson(res, 400, { ok: false, error: 'a "prompt" string is required' });
7798
- return;
7799
- }
7800
- const referenceImages = Array.isArray(body["referenceImages"]) ? body["referenceImages"].filter((entry) => typeof entry === "string") : void 0;
7801
- try {
7802
- const result = await generateImage(imageGenerateDeps, {
7803
- ...typeof body["model"] === "string" ? { model: body["model"] } : {},
7804
- prompt: body["prompt"],
7805
- ...typeof body["size"] === "string" ? { size: body["size"] } : {},
7806
- ...typeof body["quality"] === "string" ? { quality: body["quality"] } : {},
7807
- ...typeof body["n"] === "number" ? { n: body["n"] } : {},
7808
- ...referenceImages !== void 0 && referenceImages.length > 0 ? { referenceImages } : {}
7809
- });
7810
- sendJson(res, 200, {
7811
- ok: true,
7812
- // Every image this run produced, in order — the pane's preview
7813
- // and scripted callers read the paths from here.
7814
- images: result.images.map((image) => image.filePath),
7815
- model: result.model,
7816
- paramsUsed: result.paramsUsed,
7817
- ...result.revisions.length > 0 ? { warning: `\u53C2\u6570\u56DE\u9000\uFF1A${result.revisions.join("\u3001")}` } : {}
7818
- });
7819
- } catch (error) {
7820
- sendJson(res, 200, { ok: false, error: error instanceof Error ? error.message : String(error) });
7821
- }
7822
- }
7823
- }),
7824
- "dsh-model-think-level: image generate route"
7825
- );
7826
8108
  });
7827
8109
  }
7828
8110
  export {