dsh-model-think-level 1.1.3 → 1.1.5

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
@@ -92,11 +92,31 @@ function parseKeyIndex(raw) {
92
92
  return { version: 1, providers: out };
93
93
  }
94
94
  function readKeyIndex(file = keyIndexFilePath()) {
95
+ let text;
95
96
  try {
96
- return parseKeyIndex(JSON.parse(readFileSync(file, "utf8")));
97
- } catch {
98
- return emptyKeyIndex();
97
+ text = readFileSync(file, "utf8");
98
+ } catch (error) {
99
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
100
+ return emptyKeyIndex();
101
+ }
102
+ throw error;
103
+ }
104
+ const raw = JSON.parse(text);
105
+ const record = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : void 0;
106
+ const providers = record?.["providers"];
107
+ if (record === void 0 || record["version"] !== void 0 && record["version"] !== 1 || typeof providers !== "object" || providers === null || Array.isArray(providers)) {
108
+ throw new Error("the key index is malformed; repair it before changing keys");
99
109
  }
110
+ for (const [route, entries] of Object.entries(providers)) {
111
+ if (route.length === 0 || !Array.isArray(entries) || entries.some((entry) => {
112
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return true;
113
+ const ref = entry["ref"];
114
+ return typeof ref !== "string" || ref.length === 0;
115
+ })) {
116
+ throw new Error("the key index is malformed; repair it before changing keys");
117
+ }
118
+ }
119
+ return parseKeyIndex(raw);
100
120
  }
101
121
  function writeKeyIndex(document, file = keyIndexFilePath()) {
102
122
  mkdirSync(dirname(file), { recursive: true });
@@ -1488,18 +1508,12 @@ function sanitizeCompatForProtocol(compat, api) {
1488
1508
  delete copy["supportsMidConvoEffort"];
1489
1509
  delete copy["allowedFallbackModels"];
1490
1510
  if (norm === ANTHROPIC_PROTOCOL) {
1491
- for (const key of ["thinkingFormat", "supportsReasoningEffort", "thinkingTokenBudgetField", "supportsThinkingTokenBudget", "vllmPriority", "supportsMaxOutputTokens"]) delete copy[key];
1511
+ for (const key of ["thinkingFormat", "supportsReasoningEffort", "thinkingTokenBudgetField", "supportsThinkingTokenBudget", "vllmPriority"]) delete copy[key];
1492
1512
  if (copy["forceAdaptiveThinking"] === void 0) return void 0;
1493
1513
  return { forceAdaptiveThinking: copy["forceAdaptiveThinking"] };
1494
1514
  }
1495
- if (norm === "openai-responses") {
1496
- for (const key of ["thinkingFormat", "supportsReasoningEffort", "thinkingTokenBudgetField", "supportsThinkingTokenBudget", "vllmPriority"]) delete copy[key];
1497
- if (copy["supportsMaxOutputTokens"] === void 0) return void 0;
1498
- return { supportsMaxOutputTokens: copy["supportsMaxOutputTokens"] };
1499
- }
1500
1515
  if (norm !== COMPAT_CAPABLE_PROTOCOL) return void 0;
1501
1516
  delete copy["forceAdaptiveThinking"];
1502
- delete copy["supportsMaxOutputTokens"];
1503
1517
  return Object.keys(copy).length === 0 ? void 0 : copy;
1504
1518
  }
1505
1519
  function compatForRoute(entry, route) {
@@ -2504,13 +2518,36 @@ async function forgetCredential(credentials, ref) {
2504
2518
  return error instanceof Error ? error.message : String(error);
2505
2519
  }
2506
2520
  }
2521
+ var HostReadError = class extends Error {
2522
+ };
2523
+ async function resolveCredential(credentials, ref) {
2524
+ if (credentials === void 0 || typeof credentials.resolve !== "function") {
2525
+ throw new HostReadError("the credential store is unavailable");
2526
+ }
2527
+ let hit;
2528
+ try {
2529
+ hit = await credentials.resolve(ref);
2530
+ } catch {
2531
+ throw new HostReadError("the credential store could not read the reference");
2532
+ }
2533
+ if (isRefusal(hit) || hit !== void 0 && !isRecord(hit)) {
2534
+ throw new HostReadError("the credential store could not read the reference");
2535
+ }
2536
+ if (hit === void 0) return void 0;
2537
+ const value = hit["value"];
2538
+ if (value !== void 0 && typeof value !== "string") {
2539
+ throw new HostReadError("the credential store returned an invalid value");
2540
+ }
2541
+ return typeof value === "string" && value.length > 0 ? value : void 0;
2542
+ }
2507
2543
  async function credentialFacts(credentials, refs) {
2508
2544
  const out = {};
2509
2545
  if (credentials === void 0 || refs.length === 0) return out;
2510
2546
  const describe = credentials.describe;
2511
2547
  if (typeof describe === "function") {
2512
2548
  try {
2513
- const records = describeRecords(await describe.call(credentials, [...refs]));
2549
+ const answer = await describe.call(credentials, [...refs]);
2550
+ const records = isRefusal(answer) ? void 0 : describeRecords(answer);
2514
2551
  for (const ref of refs) {
2515
2552
  const info = records?.[ref];
2516
2553
  if (isRecord(info) && typeof info["configured"] === "boolean") {
@@ -2520,11 +2557,9 @@ async function credentialFacts(credentials, refs) {
2520
2557
  } catch {
2521
2558
  }
2522
2559
  }
2523
- const resolve2 = credentials.resolve;
2524
2560
  for (const ref of refs) {
2525
2561
  try {
2526
- const hit = await resolve2.call(credentials, ref);
2527
- const value = hit !== void 0 && typeof hit.value === "string" ? hit.value : void 0;
2562
+ const value = await resolveCredential(credentials, ref);
2528
2563
  const configured = out[ref]?.configured ?? (value !== void 0 && value.length > 0);
2529
2564
  const masked = value === void 0 ? void 0 : maskKeyValue(value);
2530
2565
  out[ref] = masked === void 0 || masked.length === 0 ? { configured } : { configured, masked };
@@ -2729,15 +2764,19 @@ function apply(ctx, config = {}) {
2729
2764
  const settings = ctx.settings;
2730
2765
  let piSectionCache;
2731
2766
  let piSectionCached = false;
2732
- const piSection = () => {
2767
+ const piSection = (required = false) => {
2733
2768
  if (piSectionCached) return piSectionCache;
2734
2769
  let value;
2735
2770
  try {
2736
2771
  value = settings.describe().find((entry) => entry.ns === PI_NS)?.value;
2737
2772
  } catch {
2773
+ if (required) throw new HostReadError("the llm-pi-ai settings could not be read");
2774
+ return void 0;
2775
+ }
2776
+ if (value === void 0) {
2777
+ if (required) throw new HostReadError("the llm-pi-ai settings entry is unavailable");
2738
2778
  return void 0;
2739
2779
  }
2740
- if (value === void 0) return void 0;
2741
2780
  piSectionCache = value;
2742
2781
  piSectionCached = true;
2743
2782
  return value;
@@ -2791,11 +2830,15 @@ function apply(ctx, config = {}) {
2791
2830
  if (llm === void 0 || typeof llm.prepareCall !== "function" || typeof llm.stream !== "function") return;
2792
2831
  const origPrepare = llm.prepareCall;
2793
2832
  const origStream = llm.stream;
2794
- llm.prepareCall = (callConfig, signal) => origPrepare.call(llm, guardCallConfig(callConfig, piSection()), signal);
2795
- llm.stream = (options) => origStream.call(llm, guardCallConfig(options, piSection()));
2833
+ let disposed = false;
2834
+ const prepare = (callConfig, signal) => origPrepare.call(llm, disposed ? callConfig : guardCallConfig(callConfig, piSection()), signal);
2835
+ const stream = (options) => origStream.call(llm, disposed ? options : guardCallConfig(options, piSection()));
2836
+ llm.prepareCall = prepare;
2837
+ llm.stream = stream;
2796
2838
  ctx.effect(() => () => {
2797
- llm.prepareCall = origPrepare;
2798
- llm.stream = origStream;
2839
+ disposed = true;
2840
+ if (llm.prepareCall === prepare) llm.prepareCall = origPrepare;
2841
+ if (llm.stream === stream) llm.stream = origStream;
2799
2842
  }, "dsh-model-think-level: default-guard");
2800
2843
  });
2801
2844
  }
@@ -2859,7 +2902,7 @@ function apply(ctx, config = {}) {
2859
2902
  } else {
2860
2903
  installPiAiBridge(availableLlm);
2861
2904
  }
2862
- const headerConflicts = detectHeaderConflicts();
2905
+ const environmentConflicts = detectHeaderConflicts();
2863
2906
  ctx.inject(["webServer"], (webServerCtx) => {
2864
2907
  ctx.effect(
2865
2908
  () => webServerCtx.webServer.register({
@@ -2887,7 +2930,13 @@ function apply(ctx, config = {}) {
2887
2930
  return;
2888
2931
  }
2889
2932
  const route = url.searchParams.get("route") ?? "";
2890
- const section = piSection();
2933
+ let section;
2934
+ try {
2935
+ section = piSection(true);
2936
+ } catch {
2937
+ sendJson(res, 502, { ok: false, error: "the llm-pi-ai settings could not be read" });
2938
+ return;
2939
+ }
2891
2940
  const profile = isRecord(section) && isRecord(section["providers"]) ? section["providers"][route] : void 0;
2892
2941
  if (!isRecord(profile)) {
2893
2942
  sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route "${route}"` });
@@ -2918,10 +2967,10 @@ function apply(ctx, config = {}) {
2918
2967
  let apiKey;
2919
2968
  if (apiKeyEnv !== void 0) {
2920
2969
  try {
2921
- const credentials = ctx.get("credentials");
2922
- const hit = credentials === void 0 ? void 0 : await credentials.resolve(apiKeyEnv);
2923
- apiKey = hit !== void 0 && typeof hit.value === "string" && hit.value.length > 0 ? hit.value : void 0;
2970
+ apiKey = await resolveCredential(ctx.get("credentials"), apiKeyEnv);
2924
2971
  } catch {
2972
+ sendJson(res, 502, { ok: false, error: "the credential store could not read the reference" });
2973
+ return;
2925
2974
  }
2926
2975
  }
2927
2976
  try {
@@ -3018,7 +3067,13 @@ function apply(ctx, config = {}) {
3018
3067
  }
3019
3068
  const url = new URL(req.url ?? "/", "http://x");
3020
3069
  const route = url.searchParams.get("route") ?? "";
3021
- const section = piSection();
3070
+ let section;
3071
+ try {
3072
+ section = piSection(true);
3073
+ } catch {
3074
+ sendJson(res, 502, { ok: false, error: "the llm-pi-ai settings could not be read" });
3075
+ return;
3076
+ }
3022
3077
  const profile = isRecord(section) && isRecord(section["providers"]) ? section["providers"][route] : void 0;
3023
3078
  if (!isRecord(profile)) {
3024
3079
  sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route "${route}"` });
@@ -3026,7 +3081,13 @@ function apply(ctx, config = {}) {
3026
3081
  }
3027
3082
  const apiKeyEnv = typeof profile["apiKeyEnv"] === "string" ? profile["apiKeyEnv"] : void 0;
3028
3083
  const named = url.searchParams.get("ref") ?? "";
3029
- const ref = named.length > 0 ? named === apiKeyEnv || hasKeyEntry(readKeyIndex(keyIndexFilePath()), route, named) ? named : void 0 : apiKeyEnv;
3084
+ let ref;
3085
+ try {
3086
+ ref = named.length > 0 ? named === apiKeyEnv || hasKeyEntry(readKeyIndex(keyIndexFilePath()), route, named) ? named : void 0 : apiKeyEnv;
3087
+ } catch {
3088
+ sendJson(res, 500, { ok: false, error: "the key index could not be read" });
3089
+ return;
3090
+ }
3030
3091
  if (ref === void 0) {
3031
3092
  sendJson(res, 404, {
3032
3093
  ok: false,
@@ -3036,11 +3097,10 @@ function apply(ctx, config = {}) {
3036
3097
  }
3037
3098
  let value;
3038
3099
  try {
3039
- const credentials = ctx.get("credentials");
3040
- const hit = credentials === void 0 ? void 0 : await credentials.resolve(ref);
3041
- value = hit !== void 0 && typeof hit.value === "string" && hit.value.length > 0 ? hit.value : void 0;
3100
+ value = await resolveCredential(ctx.get("credentials"), ref);
3042
3101
  } catch {
3043
- value = void 0;
3102
+ sendJson(res, 502, { ok: false, error: "the credential store could not read the reference" });
3103
+ return;
3044
3104
  }
3045
3105
  if (value === void 0) {
3046
3106
  sendJson(res, 404, { ok: false, error: `no credential is configured for ${ref}` });
@@ -3051,6 +3111,7 @@ function apply(ctx, config = {}) {
3051
3111
  }),
3052
3112
  "dsh-model-think-level: provider-key route"
3053
3113
  );
3114
+ let keyMutationTail = Promise.resolve();
3054
3115
  ctx.effect(
3055
3116
  () => webServerCtx.webServer.register({
3056
3117
  kind: "exact",
@@ -3067,70 +3128,79 @@ function apply(ctx, config = {}) {
3067
3128
  }
3068
3129
  const url = new URL(req.url ?? "/", "http://x");
3069
3130
  const route = url.searchParams.get("route") ?? "";
3070
- const entryOf = () => {
3071
- try {
3072
- const found = settings.describe().find((candidate) => candidate.ns === PI_NS);
3073
- return found === void 0 ? void 0 : { value: found.value, revision: found.revision };
3074
- } catch {
3075
- return void 0;
3131
+ let releaseMutation;
3132
+ try {
3133
+ if (req.method === "POST") {
3134
+ const previous = keyMutationTail;
3135
+ keyMutationTail = new Promise((resolve2) => {
3136
+ releaseMutation = resolve2;
3137
+ });
3138
+ await previous;
3076
3139
  }
3077
- };
3078
- if (route.length === 0 || providerProfileOf(entryOf()?.value, route) === void 0) {
3079
- sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route "${route}"` });
3080
- return;
3081
- }
3082
- const credentials = ctx.get("credentials");
3083
- const indexFile = keyIndexFilePath();
3084
- const enabledNow = () => enabledRefOf(providerProfileOf(entryOf()?.value, route));
3085
- const setEnabledKey = async (ref2) => {
3086
- for (let attempt = 0; attempt < 2; attempt += 1) {
3087
- const entry = entryOf();
3088
- if (entry === void 0) return "the llm-pi-ai settings entry is unavailable";
3140
+ const entryOf = () => {
3089
3141
  try {
3090
- await settings.mutate(
3091
- PI_NS,
3092
- ref2 === void 0 ? [{ op: "unset", path: ["providers", route, "apiKeyEnv"] }] : [{ op: "set", path: ["providers", route, "apiKeyEnv"], value: ref2 }],
3093
- entry.revision
3094
- );
3095
- return void 0;
3096
- } catch (error) {
3097
- if (attempt === 0 && isConflictError(error)) continue;
3098
- return error instanceof Error ? error.message : String(error);
3142
+ const found = settings.describe().find((candidate) => candidate.ns === PI_NS);
3143
+ if (found === void 0) throw new HostReadError("the llm-pi-ai settings entry is unavailable");
3144
+ return { value: found.value, revision: found.revision };
3145
+ } catch {
3146
+ throw new HostReadError("the llm-pi-ai settings could not be read");
3099
3147
  }
3148
+ };
3149
+ if (route.length === 0 || providerProfileOf(entryOf()?.value, route) === void 0) {
3150
+ sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route "${route}"` });
3151
+ return;
3100
3152
  }
3101
- return "the settings document kept changing; try again";
3102
- };
3103
- const payload = async () => {
3104
- const enabledRef = enabledNow();
3105
- const listed = keyEntriesOf(readKeyIndex(indexFile), route);
3106
- const refs = listed.map((entry) => entry.ref);
3107
- if (enabledRef !== void 0 && !refs.includes(enabledRef)) refs.push(enabledRef);
3108
- const facts = await credentialFacts(credentials, refs);
3109
- const entries = refs.map((ref2) => {
3110
- const fact = facts[ref2];
3111
- const view = {
3112
- ref: ref2,
3113
- enabled: ref2 === enabledRef,
3114
- configured: fact?.configured ?? null
3115
- };
3116
- if (fact?.masked !== void 0) view.masked = fact.masked;
3117
- const stored = listed.find((candidate) => candidate.ref === ref2);
3118
- if (stored?.alias !== void 0) view.alias = stored.alias;
3119
- return view;
3120
- });
3121
- return { ok: true, route, enabledRef: enabledRef ?? null, entries };
3122
- };
3123
- if (req.method === "GET") {
3124
- sendJson(res, 200, await payload());
3125
- return;
3126
- }
3127
- const body = await readJsonBody(req);
3128
- const op = isRecord(body) && typeof body["op"] === "string" ? body["op"] : "";
3129
- const ref = isRecord(body) && typeof body["ref"] === "string" ? body["ref"] : void 0;
3130
- const alias = isRecord(body) ? normalizeKeyAlias(body["alias"]) : void 0;
3131
- const value = isRecord(body) && typeof body["value"] === "string" ? body["value"] : void 0;
3132
- const refuse = (error) => sendJson(res, 400, { ok: false, error });
3133
- try {
3153
+ const credentials = ctx.get("credentials");
3154
+ const indexFile = keyIndexFilePath();
3155
+ const enabledNow = () => enabledRefOf(providerProfileOf(entryOf()?.value, route));
3156
+ const setEnabledKey = async (ref2) => {
3157
+ for (let attempt = 0; attempt < 2; attempt += 1) {
3158
+ const entry = entryOf();
3159
+ if (entry === void 0) return "the llm-pi-ai settings entry is unavailable";
3160
+ try {
3161
+ await settings.mutate(
3162
+ PI_NS,
3163
+ ref2 === void 0 ? [{ op: "unset", path: ["providers", route, "apiKeyEnv"] }] : [{ op: "set", path: ["providers", route, "apiKeyEnv"], value: ref2 }],
3164
+ entry.revision
3165
+ );
3166
+ return void 0;
3167
+ } catch (error) {
3168
+ if (attempt === 0 && isConflictError(error)) continue;
3169
+ return error instanceof Error ? error.message : String(error);
3170
+ }
3171
+ }
3172
+ return "the settings document kept changing; try again";
3173
+ };
3174
+ const payload = async () => {
3175
+ const enabledRef = enabledNow();
3176
+ const listed = keyEntriesOf(readKeyIndex(indexFile), route);
3177
+ const refs = listed.map((entry) => entry.ref);
3178
+ if (enabledRef !== void 0 && !refs.includes(enabledRef)) refs.push(enabledRef);
3179
+ const facts = await credentialFacts(credentials, refs);
3180
+ const entries = refs.map((ref2) => {
3181
+ const fact = facts[ref2];
3182
+ const view = {
3183
+ ref: ref2,
3184
+ enabled: ref2 === enabledRef,
3185
+ configured: fact?.configured ?? null
3186
+ };
3187
+ if (fact?.masked !== void 0) view.masked = fact.masked;
3188
+ const stored = listed.find((candidate) => candidate.ref === ref2);
3189
+ if (stored?.alias !== void 0) view.alias = stored.alias;
3190
+ return view;
3191
+ });
3192
+ return { ok: true, route, enabledRef: enabledRef ?? null, entries };
3193
+ };
3194
+ if (req.method === "GET") {
3195
+ sendJson(res, 200, await payload());
3196
+ return;
3197
+ }
3198
+ const body = await readJsonBody(req);
3199
+ const op = isRecord(body) && typeof body["op"] === "string" ? body["op"] : "";
3200
+ const ref = isRecord(body) && typeof body["ref"] === "string" ? body["ref"] : void 0;
3201
+ const alias = isRecord(body) ? normalizeKeyAlias(body["alias"]) : void 0;
3202
+ const value = isRecord(body) && typeof body["value"] === "string" ? body["value"] : void 0;
3203
+ const refuse = (error) => sendJson(res, 400, { ok: false, error });
3134
3204
  if (op === "add") {
3135
3205
  if (!isLegalKeyValue(value)) {
3136
3206
  refuse("a key must be printable ASCII without spaces");
@@ -3139,19 +3209,37 @@ function apply(ctx, config = {}) {
3139
3209
  const taken = keyEntriesOf(readKeyIndex(indexFile), route).map((candidate) => candidate.ref);
3140
3210
  const active = enabledNow();
3141
3211
  if (active !== void 0 && !taken.includes(active)) taken.push(active);
3142
- const created = nextKeyRef(route, taken);
3212
+ let created = nextKeyRef(route, taken);
3213
+ for (; ; ) {
3214
+ const facts = await credentialFacts(credentials, [created]);
3215
+ const configured = facts[created]?.configured;
3216
+ if (configured === void 0) throw new HostReadError("the credential store could not confirm a free reference");
3217
+ if (!configured && await resolveCredential(credentials, created) === void 0) break;
3218
+ taken.push(created);
3219
+ created = nextKeyRef(route, taken);
3220
+ }
3143
3221
  const refused = await storeCredential(credentials, created, value);
3144
3222
  if (refused !== void 0) {
3145
3223
  refuse(refused);
3146
3224
  return;
3147
3225
  }
3148
- updateKeyIndex((document) => withKeyEntry(document, route, created, alias), indexFile);
3149
- if (enabledNow() === void 0) {
3150
- const failed = await setEnabledKey(created);
3151
- if (failed !== void 0) {
3152
- refuse(failed);
3153
- return;
3226
+ let indexed = false;
3227
+ try {
3228
+ updateKeyIndex((document) => withKeyEntry(document, route, created, alias), indexFile);
3229
+ indexed = true;
3230
+ if (enabledNow() === void 0) {
3231
+ const failed = await setEnabledKey(created);
3232
+ if (failed !== void 0) throw new Error(failed);
3154
3233
  }
3234
+ } catch (error) {
3235
+ const rollback = await forgetCredential(credentials, created);
3236
+ if (rollback === void 0 && indexed) {
3237
+ updateKeyIndex((document) => withoutKeyEntry(document, route, created), indexFile);
3238
+ }
3239
+ if (rollback !== void 0) {
3240
+ throw new Error(`${error instanceof Error ? error.message : String(error)}; credential rollback failed for ${created}: ${rollback}`);
3241
+ }
3242
+ throw error;
3155
3243
  }
3156
3244
  } else if (op === "enable") {
3157
3245
  const listed = readKeyIndex(indexFile);
@@ -3204,32 +3292,56 @@ function apply(ctx, config = {}) {
3204
3292
  refuse("that key is not listed for this provider");
3205
3293
  return;
3206
3294
  }
3207
- if (ref === enabledNow()) {
3208
- const remaining = keyEntriesOf(document, route).map((candidate) => candidate.ref).filter((candidate) => candidate !== ref);
3209
- const failed = await setEnabledKey(remaining[0]);
3295
+ const configured = (await credentialConfigured(credentials, [ref]))[ref];
3296
+ if (configured === void 0) throw new HostReadError("the credential store could not read the reference");
3297
+ const wasEnabled = ref === enabledNow();
3298
+ const remaining = keyEntriesOf(document, route).map((candidate) => candidate.ref).filter((candidate) => candidate !== ref);
3299
+ const replacement = remaining[0];
3300
+ if (wasEnabled) {
3301
+ const failed = await setEnabledKey(replacement);
3210
3302
  if (failed !== void 0) {
3211
3303
  refuse(failed);
3212
3304
  return;
3213
3305
  }
3214
3306
  }
3215
- const configured = (await credentialConfigured(credentials, [ref]))[ref];
3216
- if (configured !== false) {
3217
- const refused = await forgetCredential(credentials, ref);
3218
- if (refused !== void 0) {
3219
- refuse(refused);
3220
- return;
3307
+ try {
3308
+ updateKeyIndex((document2) => withoutKeyEntry(document2, route, ref), indexFile);
3309
+ if (configured) {
3310
+ const refused = await forgetCredential(credentials, ref);
3311
+ if (refused !== void 0) throw new Error(refused);
3312
+ }
3313
+ } catch (error) {
3314
+ const failures = [];
3315
+ try {
3316
+ updateKeyIndex((current) => {
3317
+ const providers = { ...current.providers };
3318
+ const original = document.providers[route];
3319
+ if (original === void 0) delete providers[route];
3320
+ else providers[route] = original;
3321
+ return { version: 1, providers };
3322
+ }, indexFile);
3323
+ } catch {
3324
+ failures.push("key index rollback failed");
3325
+ }
3326
+ if (wasEnabled && enabledNow() === replacement) {
3327
+ const failed = await setEnabledKey(ref);
3328
+ if (failed !== void 0) failures.push(`profile rollback failed: ${failed}`);
3221
3329
  }
3330
+ throw new Error([error instanceof Error ? error.message : String(error), ...failures].join("; "));
3222
3331
  }
3223
- updateKeyIndex((document2) => withoutKeyEntry(document2, route, ref), indexFile);
3224
3332
  } else {
3225
3333
  refuse(`unknown key operation "${op}"`);
3226
3334
  return;
3227
3335
  }
3336
+ sendJson(res, 200, await payload());
3228
3337
  } catch (error) {
3229
- sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
3230
- return;
3338
+ sendJson(res, error instanceof HostReadError ? 502 : 500, {
3339
+ ok: false,
3340
+ error: error instanceof Error ? error.message : String(error)
3341
+ });
3342
+ } finally {
3343
+ releaseMutation?.();
3231
3344
  }
3232
- sendJson(res, 200, await payload());
3233
3345
  }
3234
3346
  }),
3235
3347
  "dsh-model-think-level: key index route"
@@ -3288,7 +3400,7 @@ function apply(ctx, config = {}) {
3288
3400
  /** Same-origin differences for any configured request header. */
3289
3401
  headerConflicts: index.headerConflicts,
3290
3402
  /** What was found of the plugins that rewrite the same surface. */
3291
- environment: headerConflicts
3403
+ environment: environmentConflicts
3292
3404
  }
3293
3405
  });
3294
3406
  }