dsh-model-think-level 2.3.1 → 2.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.js CHANGED
@@ -107,7 +107,8 @@ function maskKeyValue(value) {
107
107
  }
108
108
 
109
109
  // src/key-index.ts
110
- import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
110
+ import { mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
111
+ import { randomUUID } from "node:crypto";
111
112
  import { homedir } from "node:os";
112
113
  import { dirname, join } from "node:path";
113
114
  function makeEntry(ref, alias, models, protocol, disabled, auto) {
@@ -119,6 +120,12 @@ function makeEntry(ref, alias, models, protocol, disabled, auto) {
119
120
  if (auto === true) entry.auto = true;
120
121
  return entry;
121
122
  }
123
+ function setOwnRouteValue(map, route, value) {
124
+ Object.defineProperty(map, route, { value, enumerable: true, configurable: true, writable: true });
125
+ }
126
+ function ownRouteValue(map, route) {
127
+ return map !== void 0 && Object.hasOwn(map, route) ? map[route] : void 0;
128
+ }
122
129
  function emptyKeyIndex() {
123
130
  return { version: 1, providers: {} };
124
131
  }
@@ -156,7 +163,7 @@ function parseKeyIndex(raw) {
156
163
  const auto = normalizeKeyAuto(record["auto"]);
157
164
  list.push(makeEntry(ref, alias, models, protocol, disabled, auto));
158
165
  }
159
- if (list.length > 0) out[route] = list;
166
+ if (list.length > 0) setOwnRouteValue(out, route, list);
160
167
  }
161
168
  const endpoints = parseEndpoints(root["endpoints"]);
162
169
  const balances = parseBalances(root["balances"]);
@@ -171,7 +178,7 @@ function parseBalances(raw) {
171
178
  for (const [route, value] of Object.entries(raw)) {
172
179
  if (route.length === 0) continue;
173
180
  const endpoint = normalizeBalanceEndpoint(value);
174
- if (endpoint !== void 0) out[route] = endpoint;
181
+ if (endpoint !== void 0) setOwnRouteValue(out, route, endpoint);
175
182
  }
176
183
  return Object.keys(out).length === 0 ? void 0 : out;
177
184
  }
@@ -181,7 +188,7 @@ function parseEndpoints(raw) {
181
188
  for (const [route, value] of Object.entries(raw)) {
182
189
  if (route.length === 0) continue;
183
190
  const pair = normalizeRouteEndpoints(value);
184
- if (pair !== void 0) out[route] = pair;
191
+ if (pair !== void 0) setOwnRouteValue(out, route, pair);
185
192
  }
186
193
  return Object.keys(out).length === 0 ? void 0 : out;
187
194
  }
@@ -217,12 +224,44 @@ function readKeyIndex(file = keyIndexFilePath()) {
217
224
  }
218
225
  return parseKeyIndex(raw);
219
226
  }
227
+ var KEY_INDEX_HISTORY_LIMIT = 64;
228
+ function keyIndexHistoryPath(file = keyIndexFilePath()) {
229
+ return `${file}.history`;
230
+ }
231
+ function trimKeyIndexHistory(file) {
232
+ try {
233
+ const directory = keyIndexHistoryPath(file);
234
+ const snapshots = readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && /^\d{13}-[0-9a-f-]{36}\.json$/.test(entry.name)).map((entry) => entry.name).sort();
235
+ for (const name2 of snapshots.slice(0, Math.max(0, snapshots.length - KEY_INDEX_HISTORY_LIMIT))) {
236
+ unlinkSync(join(directory, name2));
237
+ }
238
+ } catch {
239
+ }
240
+ }
220
241
  function writeKeyIndex(document, file = keyIndexFilePath()) {
242
+ const text = `${JSON.stringify(document, null, 2)}
243
+ `;
244
+ let previous;
245
+ try {
246
+ previous = readFileSync(file, "utf8");
247
+ } catch (error) {
248
+ if (!(typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")) throw error;
249
+ }
250
+ if (previous === text) return;
221
251
  mkdirSync(dirname(file), { recursive: true });
222
- const temporary = `${file}.${process.pid}.tmp`;
223
- writeFileSync(temporary, `${JSON.stringify(document, null, 2)}
224
- `, "utf8");
252
+ if (previous !== void 0) {
253
+ readKeyIndex(file);
254
+ const directory = keyIndexHistoryPath(file);
255
+ mkdirSync(directory, { recursive: true, mode: 448 });
256
+ writeFileSync(
257
+ join(directory, `${Date.now()}-${randomUUID()}.json`),
258
+ previous,
259
+ { encoding: "utf8", flag: "wx", mode: 384 }
260
+ );
261
+ }
262
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
225
263
  try {
264
+ writeFileSync(temporary, text, { encoding: "utf8", flag: "wx", mode: 384 });
226
265
  renameSync(temporary, file);
227
266
  } catch (error) {
228
267
  try {
@@ -231,16 +270,27 @@ function writeKeyIndex(document, file = keyIndexFilePath()) {
231
270
  }
232
271
  throw error;
233
272
  }
273
+ if (previous !== void 0) trimKeyIndexHistory(file);
234
274
  }
235
275
  function updateKeyIndex(mutate, file = keyIndexFilePath()) {
236
- const next = mutate(readKeyIndex(file));
276
+ const current = readKeyIndex(file);
277
+ const next = mutate(current);
278
+ if (JSON.stringify(readKeyIndex(file)) !== JSON.stringify(current)) {
279
+ throw new Error("the key index changed while updating; retry the operation");
280
+ }
237
281
  writeKeyIndex(next, file);
238
282
  return next;
239
283
  }
240
284
  function keyEntriesOf(document, route) {
241
- const entries = document.providers[route];
285
+ const entries = ownRouteValue(document.providers, route);
242
286
  return Array.isArray(entries) ? entries : [];
243
287
  }
288
+ function routeEndpointsOf(document, route) {
289
+ return ownRouteValue(document.endpoints, route);
290
+ }
291
+ function routeBalanceOf(document, route) {
292
+ return ownRouteValue(document.balances, route);
293
+ }
244
294
  function hasKeyEntry(document, route, ref) {
245
295
  return keyEntriesOf(document, route).some((entry) => entry.ref === ref);
246
296
  }
@@ -301,7 +351,7 @@ function withRouteEndpoints(document, route, endpoints) {
301
351
  const map = { ...document.endpoints ?? {} };
302
352
  const cleaned = normalizeRouteEndpoints(endpoints);
303
353
  if (cleaned === void 0) delete map[route];
304
- else map[route] = cleaned;
354
+ else setOwnRouteValue(map, route, cleaned);
305
355
  const next = { version: 1, providers: document.providers, ...balancesOf(document) };
306
356
  return Object.keys(map).length === 0 ? next : { ...next, endpoints: map };
307
357
  }
@@ -309,7 +359,7 @@ function withRouteBalance(document, route, endpoint) {
309
359
  const map = { ...document.balances ?? {} };
310
360
  const cleaned = normalizeBalanceEndpoint(endpoint);
311
361
  if (cleaned === void 0) delete map[route];
312
- else map[route] = cleaned;
362
+ else setOwnRouteValue(map, route, cleaned);
313
363
  const next = { version: 1, providers: document.providers, ...endpointsOf(document) };
314
364
  return Object.keys(map).length === 0 ? next : { ...next, balances: map };
315
365
  }
@@ -323,20 +373,33 @@ function withoutKeyEntry(document, route, ref) {
323
373
  const list = keyEntriesOf(document, route).filter((entry) => entry.ref !== ref);
324
374
  const providers = { ...document.providers };
325
375
  if (list.length === 0) delete providers[route];
326
- else providers[route] = list;
376
+ else setOwnRouteValue(providers, route, list);
327
377
  return { version: 1, providers, ...endpointsOf(document), ...balancesOf(document) };
328
378
  }
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;
379
+
380
+ // src/key-mutation-queue.ts
381
+ import { resolve } from "node:path";
382
+ var KEY_MUTATION_QUEUES = /* @__PURE__ */ Symbol.for("dsh-model-think-level.key-mutation-queues");
383
+ var registry = globalThis;
384
+ var queues = registry[KEY_MUTATION_QUEUES] ??= /* @__PURE__ */ new Map();
385
+ async function acquireKeyMutation(file = keyIndexFilePath()) {
386
+ const absolute = resolve(file);
387
+ const key = process.platform === "win32" ? absolute.toLowerCase() : absolute;
388
+ const previous = queues.get(key) ?? Promise.resolve();
389
+ let releaseTurn = () => {
390
+ };
391
+ const turn = new Promise((done) => {
392
+ releaseTurn = done;
393
+ });
394
+ queues.set(key, turn);
395
+ await previous;
396
+ let released = false;
397
+ return () => {
398
+ if (released) return;
399
+ released = true;
400
+ if (queues.get(key) === turn) queues.delete(key);
401
+ releaseTurn();
402
+ };
340
403
  }
341
404
 
342
405
  // src/key-route-core.ts
@@ -3127,12 +3190,12 @@ var REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.fetch-overrides
3127
3190
  var DISPATCH_REGISTRY = /* @__PURE__ */ Symbol.for("dsh-model-think-level.dispatch-overrides");
3128
3191
  function dispatchRegistryOf() {
3129
3192
  const holder = globalThis;
3130
- let registry = holder[DISPATCH_REGISTRY];
3131
- if (registry === void 0) {
3132
- registry = { hooks: [] };
3133
- holder[DISPATCH_REGISTRY] = registry;
3193
+ let registry2 = holder[DISPATCH_REGISTRY];
3194
+ if (registry2 === void 0) {
3195
+ registry2 = { hooks: [] };
3196
+ holder[DISPATCH_REGISTRY] = registry2;
3134
3197
  }
3135
- return registry;
3198
+ return registry2;
3136
3199
  }
3137
3200
  function methodOf(input, init) {
3138
3201
  if (init?.method !== void 0 && init.method.length > 0) return init.method.toUpperCase();
@@ -3407,24 +3470,24 @@ async function withUnservedNote(response, bodyText, model, tried) {
3407
3470
  }
3408
3471
  function installHeaderOverlay(source) {
3409
3472
  const holder = globalThis;
3410
- let registry = holder[REGISTRY];
3473
+ let registry2 = holder[REGISTRY];
3411
3474
  const token = /* @__PURE__ */ Symbol("bre-header-overlay");
3412
- if (registry === void 0) {
3475
+ if (registry2 === void 0) {
3413
3476
  const base = globalThis.fetch;
3414
3477
  const entries = /* @__PURE__ */ new Map();
3415
3478
  const wrapper = makeWrapper(base, entries);
3416
- registry = { base, wrapper, entries };
3417
- holder[REGISTRY] = registry;
3479
+ registry2 = { base, wrapper, entries };
3480
+ holder[REGISTRY] = registry2;
3418
3481
  globalThis.fetch = wrapper;
3419
3482
  }
3420
- registry.entries.set(token, {
3483
+ registry2.entries.set(token, {
3421
3484
  index: () => source.current,
3422
3485
  // Delegate through the live source property so a resolver attached after
3423
3486
  // install is honoured, and its internal data stays current.
3424
3487
  keys: source.keys === void 0 ? void 0 : (context) => source.keys(context),
3425
3488
  modelListing: source.modelListing === void 0 ? void 0 : (context) => source.modelListing(context)
3426
3489
  });
3427
- const owned = registry;
3490
+ const owned = registry2;
3428
3491
  return {
3429
3492
  get active() {
3430
3493
  return owned.entries.has(token);
@@ -3438,12 +3501,12 @@ function installHeaderOverlay(source) {
3438
3501
  };
3439
3502
  }
3440
3503
  function headerOverlayInstalled() {
3441
- const registry = registryOf();
3442
- return registry !== void 0 && globalThis.fetch === registry.wrapper;
3504
+ const registry2 = registryOf();
3505
+ return registry2 !== void 0 && globalThis.fetch === registry2.wrapper;
3443
3506
  }
3444
3507
  function headerOverlayBypass() {
3445
- const registry = registryOf();
3446
- if (registry !== void 0 && globalThis.fetch === registry.wrapper) return registry.base;
3508
+ const registry2 = registryOf();
3509
+ if (registry2 !== void 0 && globalThis.fetch === registry2.wrapper) return registry2.base;
3447
3510
  return globalThis.fetch;
3448
3511
  }
3449
3512
 
@@ -3865,7 +3928,7 @@ function installPiAiHeaderTransforms(llm, source) {
3865
3928
  // src/headers-conflict.ts
3866
3929
  import { existsSync, readFileSync as readFileSync4 } from "node:fs";
3867
3930
  import { createRequire } from "node:module";
3868
- import { dirname as dirname4, join as join4, resolve } from "node:path";
3931
+ import { dirname as dirname4, join as join4, resolve as resolve2 } from "node:path";
3869
3932
  var SIBLING_PACKAGES = [
3870
3933
  "dsh-client-masquerade",
3871
3934
  "dsh-llm-headers",
@@ -3877,7 +3940,7 @@ function searchRoots() {
3877
3940
  const roots = /* @__PURE__ */ new Set();
3878
3941
  const entry = process.argv[1];
3879
3942
  if (typeof entry === "string" && entry.length > 0) {
3880
- let dir = dirname4(resolve(entry));
3943
+ let dir = dirname4(resolve2(entry));
3881
3944
  for (let depth = 0; depth < 8; depth += 1) {
3882
3945
  roots.add(join4(dir, "node_modules"));
3883
3946
  const parent = dirname4(dir);
@@ -4188,7 +4251,7 @@ function updateImageConfig(mutate, file = imageConfigFilePath()) {
4188
4251
 
4189
4252
  // src/image/generate.ts
4190
4253
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5, existsSync as existsSync2, statSync } from "node:fs";
4191
- import { dirname as dirname6, join as join6, resolve as resolve2 } from "node:path";
4254
+ import { dirname as dirname6, join as join6, resolve as resolve3 } from "node:path";
4192
4255
 
4193
4256
  // src/image/deadline.ts
4194
4257
  function createImageDeadline(timeoutMs, caller, errorFor) {
@@ -4219,7 +4282,7 @@ function createImageDeadline(timeoutMs, caller, errorFor) {
4219
4282
  return {
4220
4283
  signal: controller.signal,
4221
4284
  check,
4222
- run: (work) => new Promise((resolve3, reject) => {
4285
+ run: (work) => new Promise((resolve4, reject) => {
4223
4286
  let settled = false;
4224
4287
  const finish = (done) => {
4225
4288
  if (settled) return;
@@ -4241,7 +4304,7 @@ function createImageDeadline(timeoutMs, caller, errorFor) {
4241
4304
  Promise.resolve(work()).then((value) => {
4242
4305
  try {
4243
4306
  check();
4244
- finish(() => resolve3(value));
4307
+ finish(() => resolve4(value));
4245
4308
  } catch (error) {
4246
4309
  finish(() => reject(error));
4247
4310
  }
@@ -4443,7 +4506,7 @@ function resolveDestination(requested, fallbackDir, slug, now) {
4443
4506
  mkdirSync5(fallbackDir, { recursive: true });
4444
4507
  return destinationOf(fallbackDir, slug, now);
4445
4508
  }
4446
- const target = resolve2(requested.trim());
4509
+ const target = resolve3(requested.trim());
4447
4510
  let isDir = false;
4448
4511
  try {
4449
4512
  isDir = statSync(target).isDirectory();
@@ -4540,7 +4603,7 @@ async function generateWithinDeadline(deps, request, config, deadline) {
4540
4603
  ...(request.referenceFiles ?? []).map((file) => ({ name: file.name, bytes: file.bytes, mime: file.mime })),
4541
4604
  ...(request.referenceImages ?? []).map((path) => {
4542
4605
  deadline.check();
4543
- const absolute = resolve2(path);
4606
+ const absolute = resolve3(path);
4544
4607
  if (!existsSync2(absolute)) throw new GenerateError("reference", `\u53C2\u8003\u56FE\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BFB\uFF1A${path}`);
4545
4608
  try {
4546
4609
  return { name: absolute.split(/[\\/]/).pop() ?? "image", bytes: readFileSync6(absolute), mime: mimeOfPath(absolute) };
@@ -5050,7 +5113,7 @@ function imageToolHint(config) {
5050
5113
  }
5051
5114
 
5052
5115
  // src/image/legacy-cleanup.ts
5053
- import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
5116
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync6, readFileSync as readFileSync7, readdirSync as readdirSync2, statSync as statSync2, writeFileSync as writeFileSync6 } from "node:fs";
5054
5117
  import { dirname as dirname7, join as join7 } from "node:path";
5055
5118
  var MARK_BEGIN = `# >>> ${IMAGE_MCP_PATCH_MARK}:begin`;
5056
5119
  var MARK_END = `# <<< ${IMAGE_MCP_PATCH_MARK}:end`;
@@ -5061,7 +5124,7 @@ function resolveLegacyPatchFile(home = harnessHome()) {
5061
5124
  try {
5062
5125
  if (existsSync3(profilesDir)) {
5063
5126
  const candidates = [];
5064
- for (const name2 of readdirSync(profilesDir)) {
5127
+ for (const name2 of readdirSync2(profilesDir)) {
5065
5128
  const file = join7(profilesDir, name2, "cordis.patch.yml");
5066
5129
  if (!existsSync3(file)) continue;
5067
5130
  candidates.push({ file, mtime: statSync2(file).mtimeMs });
@@ -6177,7 +6240,7 @@ function providerProfileOf(section, route) {
6177
6240
  if (!isRecord(section)) return void 0;
6178
6241
  const providers = section["providers"];
6179
6242
  if (!isRecord(providers)) return void 0;
6180
- const profile = providers[route];
6243
+ const profile = Object.hasOwn(providers, route) ? providers[route] : void 0;
6181
6244
  return isRecord(profile) ? profile : void 0;
6182
6245
  }
6183
6246
  function enabledRefOf(profile) {
@@ -6185,17 +6248,17 @@ function enabledRefOf(profile) {
6185
6248
  return typeof ref === "string" && ref.length > 0 ? ref : void 0;
6186
6249
  }
6187
6250
  function readRouteKeyScopes(providers) {
6251
+ const scopes = /* @__PURE__ */ Object.create(null);
6188
6252
  let document;
6189
6253
  try {
6190
6254
  document = readKeyIndex(keyIndexFilePath());
6191
6255
  } catch {
6192
- return {};
6256
+ return scopes;
6193
6257
  }
6194
- const scopes = {};
6195
6258
  const routes = new Set(Object.keys(document.providers));
6196
6259
  for (const route of Object.keys(providers)) routes.add(route);
6197
6260
  for (const route of routes) {
6198
- const endpoints = document.endpoints?.[route];
6261
+ const endpoints = routeEndpointsOf(document, route);
6199
6262
  const listed = keyEntriesOf(document, route);
6200
6263
  const active = listed.filter((entry) => entry.disabled !== true);
6201
6264
  const ordered = active.map((entry) => {
@@ -6237,14 +6300,52 @@ function describeRecords(answer) {
6237
6300
  const candidate = isRecord(answer) && answer["value"] !== void 0 ? answer["value"] : answer;
6238
6301
  return isRecord(candidate) ? candidate : void 0;
6239
6302
  }
6240
- async function storeCredential(credentials, ref, value) {
6303
+ var PendingCredentialMutations = class {
6304
+ pending = /* @__PURE__ */ new Set();
6305
+ track(operation) {
6306
+ const settled = operation.then(
6307
+ () => {
6308
+ this.pending.delete(settled);
6309
+ },
6310
+ () => {
6311
+ this.pending.delete(settled);
6312
+ }
6313
+ );
6314
+ this.pending.add(settled);
6315
+ return operation;
6316
+ }
6317
+ releaseAfterSettled(release) {
6318
+ if (this.pending.size === 0) release();
6319
+ else void Promise.all([...this.pending]).then(release, release);
6320
+ }
6321
+ };
6322
+ async function awaitCredentialMutation(operation, pending, budgetMs) {
6323
+ pending.track(operation);
6324
+ let timer;
6325
+ try {
6326
+ return await Promise.race([
6327
+ operation,
6328
+ new Promise((_, reject) => {
6329
+ timer = setTimeout(() => reject(new Error(
6330
+ `the credential store did not answer within ${Math.round(budgetMs / 1e3)}s; the write result is unknown until it settles`
6331
+ )), budgetMs);
6332
+ })
6333
+ ]);
6334
+ } finally {
6335
+ if (timer !== void 0) clearTimeout(timer);
6336
+ }
6337
+ }
6338
+ async function storeCredential(credentials, ref, value, pending) {
6241
6339
  const set = credentials?.set;
6242
6340
  if (credentials === void 0 || typeof set !== "function") {
6243
6341
  return "this deployment cannot write the credential store";
6244
6342
  }
6245
6343
  invalidateCredentialDisplay(credentials, ref);
6246
6344
  try {
6247
- const answer = await set.call(credentials, ref, value);
6345
+ const operation = Promise.resolve().then(() => set.call(credentials, ref, value)).finally(() => {
6346
+ invalidateCredentialDisplay(credentials, ref);
6347
+ });
6348
+ const answer = await awaitCredentialMutation(operation, pending, CREDENTIAL_IPC_BUDGET_MS);
6248
6349
  if (!isRefusal(answer)) return void 0;
6249
6350
  return refusalMessage(answer) ?? `the credential store refused ${ref}`;
6250
6351
  } catch (error) {
@@ -6253,30 +6354,22 @@ async function storeCredential(credentials, ref, value) {
6253
6354
  invalidateCredentialDisplay(credentials, ref);
6254
6355
  }
6255
6356
  }
6256
- async function forgetCredential(credentials, ref, budgetMs) {
6357
+ async function forgetCredential(credentials, ref, pending, budgetMs = CREDENTIAL_IPC_BUDGET_MS) {
6257
6358
  const unset = credentials?.unset;
6258
6359
  if (credentials === void 0 || typeof unset !== "function") {
6259
6360
  return "this deployment cannot write the credential store";
6260
6361
  }
6261
6362
  invalidateCredentialDisplay(credentials, ref);
6262
- let timer;
6263
6363
  try {
6264
- const answer = await Promise.race([
6265
- unset.call(credentials, ref),
6266
- budgetMs === void 0 ? new Promise(() => {
6267
- }) : new Promise((_, reject) => {
6268
- timer = setTimeout(
6269
- () => reject(new Error(`the credential store did not answer within ${Math.round(budgetMs / 1e3)}s`)),
6270
- budgetMs
6271
- );
6272
- })
6273
- ]);
6364
+ const operation = Promise.resolve().then(() => unset.call(credentials, ref)).finally(() => {
6365
+ invalidateCredentialDisplay(credentials, ref);
6366
+ });
6367
+ const answer = await awaitCredentialMutation(operation, pending, budgetMs);
6274
6368
  if (!isRefusal(answer)) return void 0;
6275
6369
  return refusalMessage(answer) ?? `the credential store refused to forget ${ref}`;
6276
6370
  } catch (error) {
6277
6371
  return error instanceof Error ? error.message : String(error);
6278
6372
  } finally {
6279
- if (timer !== void 0) clearTimeout(timer);
6280
6373
  invalidateCredentialDisplay(credentials, ref);
6281
6374
  }
6282
6375
  }
@@ -6370,8 +6463,8 @@ async function displayCredentialFacts(credentials, refs, budgetMs) {
6370
6463
  try {
6371
6464
  await Promise.race([
6372
6465
  Promise.all([...selected.values()].map((read) => read.settled)),
6373
- new Promise((resolve3) => {
6374
- timer = setTimeout(resolve3, budgetMs);
6466
+ new Promise((resolve4) => {
6467
+ timer = setTimeout(resolve4, budgetMs);
6375
6468
  })
6376
6469
  ]);
6377
6470
  } finally {
@@ -6415,8 +6508,8 @@ async function credentialFacts(credentials, refs, budgetMs) {
6415
6508
  let timer;
6416
6509
  try {
6417
6510
  if (budgetMs === void 0) await settled;
6418
- else await Promise.race([settled, new Promise((resolve3) => {
6419
- timer = setTimeout(resolve3, budgetMs);
6511
+ else await Promise.race([settled, new Promise((resolve4) => {
6512
+ timer = setTimeout(resolve4, budgetMs);
6420
6513
  })]);
6421
6514
  } finally {
6422
6515
  if (timer !== void 0) clearTimeout(timer);
@@ -6543,7 +6636,6 @@ function apply(ctx, config = {}) {
6543
6636
  modalityAutofill: config.modalityAutofill !== false,
6544
6637
  probeTimeoutMs: config.probeTimeoutMs ?? PROBE_TIMEOUT_MS,
6545
6638
  bootRetryDelaysMs: config.bootRetryDelaysMs ?? [...BOOT_RETRY_DELAYS_MS],
6546
- routeSweepGraceMs: config.routeSweepGraceMs ?? ROUTE_SWEEP_GRACE_MS,
6547
6639
  defaultGuard: config.defaultGuard !== false,
6548
6640
  uaOverride: config.uaOverride !== false
6549
6641
  };
@@ -6726,110 +6818,14 @@ function apply(ctx, config = {}) {
6726
6818
  if (key.startsWith(prefix)) listingCache.delete(key);
6727
6819
  }
6728
6820
  };
6729
- const vanishedSince = /* @__PURE__ */ new Map();
6730
- const sweepTimers = /* @__PURE__ */ new Set();
6731
- ctx.effect(() => () => {
6732
- for (const timer of sweepTimers) clearTimeout(timer);
6733
- sweepTimers.clear();
6734
- }, "dsh-model-think-level: route-sweep timers");
6735
- let recheckTimer;
6736
- let recheckAt = 0;
6737
- const scheduleSweep = (at) => {
6738
- if (recheckTimer !== void 0) {
6739
- if (recheckAt <= at) return;
6740
- clearTimeout(recheckTimer);
6741
- sweepTimers.delete(recheckTimer);
6742
- }
6743
- recheckAt = at;
6744
- const timer = setTimeout(() => {
6745
- sweepTimers.delete(timer);
6746
- if (recheckTimer === timer) recheckTimer = void 0;
6747
- void Promise.resolve().then(() => sweepVanishedRoutes());
6748
- }, Math.max(0, at - Date.now()));
6749
- recheckTimer = timer;
6750
- sweepTimers.add(timer);
6751
- };
6752
- const sweepVanishedRoutes = () => {
6753
- const section = piSection();
6754
- if (!isRecord(section) || !isRecord(section["providers"])) return false;
6755
- const live = section["providers"];
6756
- const indexFile = keyIndexFilePath();
6757
- let index;
6758
- try {
6759
- index = readKeyIndex(indexFile);
6760
- } catch {
6761
- return true;
6762
- }
6763
- for (const route of vanishedSince.keys()) if (route in live) vanishedSince.delete(route);
6764
- const stale = /* @__PURE__ */ new Set();
6765
- for (const route of Object.keys(index.providers)) if (!(route in live)) stale.add(route);
6766
- for (const route of Object.keys(index.endpoints ?? {})) if (!(route in live)) stale.add(route);
6767
- for (const route of Object.keys(index.balances ?? {})) if (!(route in live)) stale.add(route);
6768
- if (stale.size === 0) return true;
6769
- const graceMs = resolved.routeSweepGraceMs;
6770
- const now = Date.now();
6771
- const due = /* @__PURE__ */ new Set();
6772
- for (const route of stale) {
6773
- const since = vanishedSince.get(route);
6774
- if (since === void 0) {
6775
- if (graceMs <= 0) due.add(route);
6776
- else vanishedSince.set(route, now);
6777
- } else if (now - since >= graceMs) {
6778
- due.add(route);
6779
- }
6780
- }
6781
- let earliest = Infinity;
6782
- for (const route of stale) {
6783
- if (due.has(route)) continue;
6784
- const since = vanishedSince.get(route);
6785
- if (since !== void 0) earliest = Math.min(earliest, since + graceMs);
6786
- }
6787
- if (earliest !== Infinity) scheduleSweep(earliest);
6788
- if (due.size === 0) return true;
6789
- const survivors = /* @__PURE__ */ new Set();
6790
- for (const [route, entries] of Object.entries(index.providers)) {
6791
- if (due.has(route)) continue;
6792
- for (const entry of entries) survivors.add(entry.ref);
6793
- }
6794
- for (const profile of Object.values(live)) {
6795
- if (!isRecord(profile)) continue;
6796
- const seat = enabledRefOf(profile);
6797
- if (seat !== void 0) survivors.add(seat);
6798
- }
6799
- const credentials = ctx.get("credentials");
6800
- let swept = false;
6801
- for (const route of due) {
6802
- const refs = keyEntriesOf(index, route).map((entry) => entry.ref);
6803
- const hadEndpoints = index.endpoints?.[route] !== void 0;
6804
- const hadBalance = index.balances?.[route] !== void 0;
6805
- try {
6806
- updateKeyIndex((current) => withoutRoute(current, route), indexFile);
6807
- } catch (error) {
6808
- console.error(`[dsh-model-think-level] key route cleanup for "${route}" failed: ${error instanceof Error ? error.message : String(error)}`);
6809
- continue;
6810
- }
6811
- vanishedSince.delete(route);
6812
- swept = true;
6813
- console.info(`[dsh-model-think-level] provider "${route}" left the settings document past its grace window; swept key-index metadata (${refs.length} key(s)${hadEndpoints ? ", extra endpoints" : ""}${hadBalance ? ", balance URL" : ""})`);
6814
- for (const ref of refs) {
6815
- forgetServes(route, ref);
6816
- const here = `${route}\0${ref}`;
6817
- lastKnownScopes.delete(here);
6818
- lastKnownRecords.delete(here);
6819
- if (survivors.has(ref)) continue;
6820
- void forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS).then((refused) => {
6821
- if (refused !== void 0) {
6822
- console.error(`[dsh-model-think-level] credential cleanup for "${ref}" failed: ${refused}`);
6823
- }
6824
- });
6825
- }
6826
- invalidateListings(route);
6827
- }
6828
- if (swept) refreshKeyScopes();
6829
- return true;
6830
- };
6831
6821
  const keyProbeRuns = /* @__PURE__ */ new Map();
6822
+ let probeStopped = false;
6823
+ ctx.effect(() => () => {
6824
+ probeStopped = true;
6825
+ });
6832
6826
  const probeRouteKeys = async (route) => {
6827
+ if (probeStopped) return;
6828
+ const indexFile = keyIndexFilePath();
6833
6829
  let profile;
6834
6830
  try {
6835
6831
  profile = providerProfileOf(piSection(true), route);
@@ -6840,16 +6836,19 @@ function apply(ctx, config = {}) {
6840
6836
  const api = normalizeKeyProtocol(profile["api"]);
6841
6837
  const baseURL = typeof profile["baseURL"] === "string" ? profile["baseURL"].trim() : "";
6842
6838
  if (api === void 0 || !LISTABLE_PROTOCOLS.has(api) || baseURL.length === 0) return;
6839
+ const declaredIds = Array.isArray(profile["models"]) ? profile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : [];
6840
+ if (declaredIds.length === 0) return;
6843
6841
  let document;
6844
6842
  try {
6845
- document = readKeyIndex(keyIndexFilePath());
6843
+ document = readKeyIndex(indexFile);
6846
6844
  } catch {
6847
6845
  return;
6848
6846
  }
6849
- const endpoints = document.endpoints?.[route];
6847
+ const endpoints = routeEndpointsOf(document, route);
6850
6848
  const listed = keyEntriesOf(document, route);
6849
+ const active = listed.filter((entry) => entry.disabled !== true);
6851
6850
  const seat = enabledRefOf(profile);
6852
- const keys = listed.map((entry) => ({ ref: entry.ref, entry }));
6851
+ const keys = active.map((entry) => ({ ref: entry.ref, entry }));
6853
6852
  if (seat !== void 0 && !listed.some((entry) => entry.ref === seat)) keys.push({ ref: seat, entry: void 0 });
6854
6853
  if (keys.length < 2) return;
6855
6854
  const credentials = ctx.get("credentials");
@@ -6860,6 +6859,7 @@ function apply(ctx, config = {}) {
6860
6859
  return void 0;
6861
6860
  }
6862
6861
  }));
6862
+ if (probeStopped) return;
6863
6863
  const askable = keys.flatMap((key, index) => {
6864
6864
  const value = values[index];
6865
6865
  return value === void 0 || value.length === 0 ? [] : [{ ...key, value }];
@@ -6873,6 +6873,7 @@ function apply(ctx, config = {}) {
6873
6873
  keys: askable,
6874
6874
  refOf: (key) => key.ref,
6875
6875
  probe: async (key) => {
6876
+ if (probeStopped) return { ref: key.ref, models: void 0 };
6876
6877
  const listings = await Promise.all(targetsOf(key.entry).map((target) => probeListing({
6877
6878
  baseURL: target.baseURL,
6878
6879
  api: target.api,
@@ -6881,6 +6882,7 @@ function apply(ctx, config = {}) {
6881
6882
  timeoutMs,
6882
6883
  send
6883
6884
  })));
6885
+ if (probeStopped) return { ref: key.ref, models: void 0 };
6884
6886
  const ids = [];
6885
6887
  for (const listing of listings) {
6886
6888
  if (listing === void 0) continue;
@@ -6890,44 +6892,110 @@ function apply(ctx, config = {}) {
6890
6892
  }
6891
6893
  if (ids.length === 0) return { ref: key.ref, models: void 0 };
6892
6894
  served.set(key.ref, ids);
6893
- lastKnownScopes.set(`${route}\0${key.ref}`, ids);
6894
- recordServes(route, key.ref, ids);
6895
6895
  return { ref: key.ref, models: ids };
6896
6896
  }
6897
6897
  });
6898
- if (served.size === 0) return;
6899
- const declared = Array.isArray(profile["models"]) ? profile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : [];
6900
- if (declared.length === 0) return;
6901
- let next = readKeyIndex(keyIndexFilePath());
6902
- let mutated = false;
6903
- for (const [ref, ids] of served) {
6904
- const entry = keyEntriesOf(next, route).find((candidate) => candidate.ref === ref);
6905
- if (entry === void 0) continue;
6906
- if (entry.models !== void 0 && entry.auto !== true) continue;
6907
- const target = declared.filter((id) => ids.includes(id));
6908
- const scope = target.length === declared.length ? void 0 : target;
6909
- const unchanged = scope === void 0 ? entry.models === void 0 : entry.models !== void 0 && entry.models.length === scope.length && scope.every((id) => entry.models?.includes(id));
6910
- if (unchanged) continue;
6911
- next = withKeyAutoScope(next, route, ref, scope);
6912
- mutated = true;
6913
- }
6914
- if (!mutated) return;
6898
+ if (probeStopped || served.size === 0) return;
6899
+ const releaseMutation = await acquireKeyMutation(indexFile);
6915
6900
  try {
6916
- writeKeyIndex(next, keyIndexFilePath());
6917
- } catch {
6918
- return;
6901
+ if (probeStopped) return;
6902
+ const currentProfile = providerProfileOf(settings.describe().find((entry) => entry.ns === PI_NS)?.value, route);
6903
+ if (currentProfile === void 0) return;
6904
+ const declared = Array.isArray(currentProfile["models"]) ? currentProfile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : [];
6905
+ if (declared.length === 0) return;
6906
+ let next = readKeyIndex(indexFile);
6907
+ let mutated = false;
6908
+ const emptied = [];
6909
+ for (const [ref, ids] of served) {
6910
+ lastKnownScopes.set(`${route}\0${ref}`, ids);
6911
+ recordServes(route, ref, ids);
6912
+ const entry = keyEntriesOf(next, route).find((candidate) => candidate.ref === ref);
6913
+ if (entry === void 0) continue;
6914
+ const target = declared.filter((id) => ids.includes(id));
6915
+ if (target.length === 0) {
6916
+ if (entry.disabled !== true) emptied.push(ref);
6917
+ continue;
6918
+ }
6919
+ const scope = target.length === declared.length ? void 0 : target;
6920
+ const unchanged = scope === void 0 ? entry.models === void 0 : entry.models !== void 0 && entry.models.length === scope.length && scope.every((id) => entry.models?.includes(id));
6921
+ if (unchanged) continue;
6922
+ next = withKeyAutoScope(next, route, ref, scope);
6923
+ mutated = true;
6924
+ }
6925
+ if (emptied.length > 0) {
6926
+ const after = keyEntriesOf(next, route);
6927
+ const activeLeft = after.filter((entry) => entry.disabled !== true && !emptied.includes(entry.ref)).length;
6928
+ const seatLeft = seat !== void 0 && !after.some((entry) => entry.ref === seat) ? 1 : 0;
6929
+ if (activeLeft + seatLeft > 0) {
6930
+ for (const ref of emptied) next = withKeyDisabled(next, route, ref, true);
6931
+ mutated = true;
6932
+ }
6933
+ }
6934
+ if (!mutated) return;
6935
+ try {
6936
+ writeKeyIndex(next, indexFile);
6937
+ } catch {
6938
+ return;
6939
+ }
6940
+ refreshKeyScopes();
6941
+ } finally {
6942
+ releaseMutation();
6919
6943
  }
6920
- refreshKeyScopes();
6921
6944
  };
6922
6945
  const runKeyProbe = (route) => {
6946
+ if (probeStopped) return Promise.resolve();
6923
6947
  const previous = keyProbeRuns.get(route) ?? Promise.resolve();
6924
- const run = previous.then(() => probeRouteKeys(route)).catch(() => {
6948
+ const run = previous.then(() => probeStopped ? void 0 : probeRouteKeys(route)).catch(() => {
6925
6949
  }).finally(() => {
6926
6950
  if (keyProbeRuns.get(route) === run) keyProbeRuns.delete(route);
6927
6951
  });
6928
6952
  keyProbeRuns.set(route, run);
6929
6953
  return run;
6930
6954
  };
6955
+ const PROBE_SAVE_DELAY_MS = 1e3;
6956
+ const probeSignatures = /* @__PURE__ */ new Map();
6957
+ const probeSavePending = /* @__PURE__ */ new Set();
6958
+ let probeSaveTimer;
6959
+ const probeSignatureOf = (profile) => JSON.stringify([
6960
+ profile["api"],
6961
+ profile["baseURL"],
6962
+ profile["apiKeyEnv"],
6963
+ profile["headers"],
6964
+ Array.isArray(profile["models"]) ? profile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean).sort() : []
6965
+ ]);
6966
+ const armProbeTimer = () => {
6967
+ if (probeStopped || probeSavePending.size === 0 || probeSaveTimer !== void 0) return;
6968
+ probeSaveTimer = setTimeout(() => {
6969
+ probeSaveTimer = void 0;
6970
+ const routes = Array.from(probeSavePending);
6971
+ probeSavePending.clear();
6972
+ for (const route of routes) void runKeyProbe(route);
6973
+ }, PROBE_SAVE_DELAY_MS);
6974
+ };
6975
+ const scheduleKeyProbes = (changed) => {
6976
+ if (probeStopped) return;
6977
+ const providers = providersOf();
6978
+ for (const route of Array.from(probeSignatures.keys())) {
6979
+ if (!Object.hasOwn(providers, route)) probeSignatures.delete(route);
6980
+ }
6981
+ for (const [route, profile] of Object.entries(providers)) {
6982
+ if (!isRecord(profile)) continue;
6983
+ const signature = probeSignatureOf(profile);
6984
+ if (probeSignatures.get(route) === signature) continue;
6985
+ probeSignatures.set(route, signature);
6986
+ probeSavePending.add(route);
6987
+ }
6988
+ if (changed !== void 0 && Object.hasOwn(providers, changed)) probeSavePending.add(changed);
6989
+ armProbeTimer();
6990
+ };
6991
+ for (const [route, profile] of Object.entries(providersOf())) {
6992
+ if (isRecord(profile)) probeSignatures.set(route, probeSignatureOf(profile));
6993
+ }
6994
+ ctx.effect(() => () => {
6995
+ if (probeSaveTimer !== void 0) clearTimeout(probeSaveTimer);
6996
+ probeSaveTimer = void 0;
6997
+ probeSavePending.clear();
6998
+ });
6931
6999
  const headerRetryTimers = /* @__PURE__ */ new Set();
6932
7000
  let headerRetryAttempt = 0;
6933
7001
  const stopHeaderRetries = () => {
@@ -6968,30 +7036,15 @@ function apply(ctx, config = {}) {
6968
7036
  if (ns === PI_NS) {
6969
7037
  refreshHeaders();
6970
7038
  refreshKeyScopes();
6971
- sweepVanishedRoutes();
6972
7039
  syncImageConfigNow();
6973
7040
  const source = catalogueSource();
6974
7041
  if (source !== catalogueSourceStamp) {
6975
7042
  catalogueSourceStamp = source;
6976
7043
  invalidateListings();
6977
7044
  }
7045
+ scheduleKeyProbes();
6978
7046
  }
6979
7047
  });
6980
- {
6981
- const bootRouteSweep = (attempt) => {
6982
- void Promise.resolve().then(() => sweepVanishedRoutes()).then((ready) => {
6983
- if (ready || attempt >= resolved.bootRetryDelaysMs.length) return;
6984
- const timer = setTimeout(() => {
6985
- sweepTimers.delete(timer);
6986
- bootRouteSweep(attempt + 1);
6987
- }, resolved.bootRetryDelaysMs[attempt]);
6988
- sweepTimers.add(timer);
6989
- }, (error) => {
6990
- console.error(`[dsh-model-think-level] route sweep failed: ${error instanceof Error ? error.message : String(error)}`);
6991
- });
6992
- };
6993
- bootRouteSweep(0);
6994
- }
6995
7048
  overlaySource.keys = async ({ route, model }) => {
6996
7049
  const scopes = keyScopes.current[route] ?? [];
6997
7050
  if (scopes.length === 0) return [];
@@ -7468,13 +7521,13 @@ function apply(ctx, config = {}) {
7468
7521
  }),
7469
7522
  "dsh-model-think-level: provider-key route"
7470
7523
  );
7471
- let keyMutationTail = Promise.resolve();
7472
7524
  ctx.effect(
7473
7525
  () => webServerCtx.webServer.register({
7474
7526
  kind: "exact",
7475
7527
  path: KEY_INDEX_PATH,
7476
7528
  handler: async (req, res) => {
7477
7529
  res.setHeader("cache-control", "no-store");
7530
+ res.setHeader("x-dsh-key-integrity", "20261101-explicit-delete+history64+shared-lease-drain");
7478
7531
  if (!isTrustedRequest(req)) {
7479
7532
  sendJson(res, 403, { ok: false, error: "forbidden" });
7480
7533
  return;
@@ -7485,21 +7538,25 @@ function apply(ctx, config = {}) {
7485
7538
  }
7486
7539
  const url = new URL(req.url ?? "/", "http://x");
7487
7540
  const route = url.searchParams.get("route") ?? "";
7541
+ const indexFile = keyIndexFilePath();
7542
+ const pendingMutations = new PendingCredentialMutations();
7488
7543
  let releaseMutation;
7489
7544
  try {
7490
7545
  if (req.method === "POST") {
7491
- const previous = keyMutationTail;
7492
- keyMutationTail = new Promise((resolve3) => {
7493
- releaseMutation = resolve3;
7494
- });
7495
- await previous;
7546
+ const release = await acquireKeyMutation(indexFile);
7547
+ let finished = false;
7548
+ releaseMutation = () => {
7549
+ if (finished) return;
7550
+ finished = true;
7551
+ pendingMutations.releaseAfterSettled(release);
7552
+ };
7496
7553
  }
7497
7554
  if (req.method === "GET" && url.searchParams.get("op") === "endpoints") {
7498
7555
  if (route.length === 0) {
7499
7556
  sendJson(res, 400, { ok: false, error: "a route is required" });
7500
7557
  return;
7501
7558
  }
7502
- const endpoints = readKeyIndex(keyIndexFilePath()).endpoints?.[route];
7559
+ const endpoints = routeEndpointsOf(readKeyIndex(indexFile), route);
7503
7560
  sendJson(res, 200, {
7504
7561
  ok: true,
7505
7562
  route,
@@ -7515,7 +7572,7 @@ function apply(ctx, config = {}) {
7515
7572
  sendJson(res, 400, { ok: false, error: "a route is required" });
7516
7573
  return;
7517
7574
  }
7518
- const endpoint = readKeyIndex(keyIndexFilePath()).balances?.[route];
7575
+ const endpoint = routeBalanceOf(readKeyIndex(indexFile), route);
7519
7576
  sendJson(res, 200, { ok: true, route, endpoint: endpoint ?? null });
7520
7577
  return;
7521
7578
  }
@@ -7536,7 +7593,6 @@ function apply(ctx, config = {}) {
7536
7593
  return;
7537
7594
  }
7538
7595
  const credentials = ctx.get("credentials");
7539
- const indexFile = keyIndexFilePath();
7540
7596
  const enabledNow = () => enabledRefOf(providerProfileOf(entryOf()?.value, route));
7541
7597
  const setEnabledKey = async (ref2) => {
7542
7598
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -7581,11 +7637,7 @@ function apply(ctx, config = {}) {
7581
7637
  if (fact?.masked !== void 0) view.masked = fact.masked;
7582
7638
  if (stored?.alias !== void 0) view.alias = stored.alias;
7583
7639
  if (stored?.models !== void 0) view.models = stored.models.filter((id) => declaredModels.has(id));
7584
- const observed = servesOfRoute(servesDocument(), route).get(ref2)?.filter((id) => declaredModels.has(id));
7585
- if (observed !== void 0 && observed.length > 0) {
7586
- ;
7587
- view.observed = observed;
7588
- }
7640
+ if (stored?.auto === true) view.auto = true;
7589
7641
  if (stored?.protocol !== void 0) view.protocol = stored.protocol;
7590
7642
  const rest = keyRest.stateOf(restKeyOf(route, ref2), now);
7591
7643
  if (rest !== void 0) {
@@ -7598,7 +7650,7 @@ function apply(ctx, config = {}) {
7598
7650
  }
7599
7651
  return view;
7600
7652
  });
7601
- const endpoints = document.endpoints?.[route];
7653
+ const endpoints = routeEndpointsOf(document, route);
7602
7654
  const probing = keyProbeRuns.has(route);
7603
7655
  return {
7604
7656
  ok: true,
@@ -7687,7 +7739,7 @@ function apply(ctx, config = {}) {
7687
7739
  }
7688
7740
  const seatBefore = active;
7689
7741
  const seatIsEmpty = seatBefore !== void 0 && seatBefore !== created && holdsNothing((await credentialFacts(credentials, [seatBefore], CREDENTIAL_IPC_BUDGET_MS))[seatBefore]);
7690
- const refused = await storeCredential(credentials, created, value);
7742
+ const refused = await storeCredential(credentials, created, value, pendingMutations);
7691
7743
  if (refused !== void 0) {
7692
7744
  refuse(refused);
7693
7745
  return;
@@ -7701,7 +7753,7 @@ function apply(ctx, config = {}) {
7701
7753
  if (failed !== void 0) throw new Error(failed);
7702
7754
  }
7703
7755
  } catch (error) {
7704
- const rollback = await forgetCredential(credentials, created, CREDENTIAL_IPC_BUDGET_MS);
7756
+ const rollback = await forgetCredential(credentials, created, pendingMutations, CREDENTIAL_IPC_BUDGET_MS);
7705
7757
  if (rollback === void 0 && indexed) {
7706
7758
  updateKeyIndex((document) => withoutKeyEntry(document, route, created), indexFile);
7707
7759
  }
@@ -7823,7 +7875,7 @@ function apply(ctx, config = {}) {
7823
7875
  refuse("a key must be printable ASCII without spaces");
7824
7876
  return;
7825
7877
  }
7826
- const refused = await storeCredential(credentials, ref, value);
7878
+ const refused = await storeCredential(credentials, ref, value, pendingMutations);
7827
7879
  if (refused !== void 0) {
7828
7880
  refuse(refused);
7829
7881
  return;
@@ -7853,17 +7905,17 @@ function apply(ctx, config = {}) {
7853
7905
  forgetServes(route, ref);
7854
7906
  invalidateCredentialDisplay(credentials, ref);
7855
7907
  if (configured) {
7856
- const refused = await forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS);
7908
+ const refused = await forgetCredential(credentials, ref, pendingMutations, CREDENTIAL_IPC_BUDGET_MS);
7857
7909
  if (refused !== void 0) throw new Error(refused);
7858
7910
  }
7859
7911
  } catch (error) {
7860
7912
  const failures = [];
7861
7913
  try {
7862
7914
  updateKeyIndex((current) => {
7915
+ const original = Object.hasOwn(document.providers, route) ? document.providers[route] : void 0;
7916
+ if (original !== void 0) return { ...current, providers: { ...current.providers, [route]: original } };
7863
7917
  const providers = { ...current.providers };
7864
- const original = document.providers[route];
7865
- if (original === void 0) delete providers[route];
7866
- else providers[route] = original;
7918
+ delete providers[route];
7867
7919
  return { ...current, providers };
7868
7920
  }, indexFile);
7869
7921
  } catch {
@@ -7878,8 +7930,8 @@ function apply(ctx, config = {}) {
7878
7930
  } else if (op === "probe") {
7879
7931
  const listed = keyEntriesOf(readKeyIndex(indexFile), route);
7880
7932
  const seat = enabledNow();
7881
- const distinct = new Set(listed.map((entry) => entry.ref));
7882
- if (seat !== void 0) distinct.add(seat);
7933
+ const distinct = new Set(listed.filter((entry) => entry.disabled !== true).map((entry) => entry.ref));
7934
+ if (seat !== void 0 && !listed.some((entry) => entry.ref === seat)) distinct.add(seat);
7883
7935
  if (distinct.size < 2) {
7884
7936
  refuse("a scope probe needs a second key; a single key serves whatever it serves");
7885
7937
  return;
@@ -7892,6 +7944,7 @@ function apply(ctx, config = {}) {
7892
7944
  refreshKeyScopes();
7893
7945
  if (["add", "remove", "value", "protocol", "endpoints", "enable"].includes(op)) {
7894
7946
  invalidateListings(route);
7947
+ scheduleKeyProbes(route);
7895
7948
  }
7896
7949
  releaseMutation?.();
7897
7950
  releaseMutation = void 0;
@@ -7936,7 +7989,7 @@ function apply(ctx, config = {}) {
7936
7989
  sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
7937
7990
  return;
7938
7991
  }
7939
- const endpoint = document.balances?.[route];
7992
+ const endpoint = routeBalanceOf(document, route);
7940
7993
  if (endpoint === void 0) {
7941
7994
  sendJson(res, 200, { ok: true, route, configured: false });
7942
7995
  return;
@@ -8185,8 +8238,8 @@ function apply(ctx, config = {}) {
8185
8238
  }
8186
8239
  let releaseMutation;
8187
8240
  const previous = fingerprintMutationTail;
8188
- fingerprintMutationTail = new Promise((resolve3) => {
8189
- releaseMutation = resolve3;
8241
+ fingerprintMutationTail = new Promise((resolve4) => {
8242
+ releaseMutation = resolve4;
8190
8243
  });
8191
8244
  await previous;
8192
8245
  try {