dsh-model-think-level 2.3.1 → 2.3.2

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);
@@ -6842,11 +6838,11 @@ function apply(ctx, config = {}) {
6842
6838
  if (api === void 0 || !LISTABLE_PROTOCOLS.has(api) || baseURL.length === 0) return;
6843
6839
  let document;
6844
6840
  try {
6845
- document = readKeyIndex(keyIndexFilePath());
6841
+ document = readKeyIndex(indexFile);
6846
6842
  } catch {
6847
6843
  return;
6848
6844
  }
6849
- const endpoints = document.endpoints?.[route];
6845
+ const endpoints = routeEndpointsOf(document, route);
6850
6846
  const listed = keyEntriesOf(document, route);
6851
6847
  const seat = enabledRefOf(profile);
6852
6848
  const keys = listed.map((entry) => ({ ref: entry.ref, entry }));
@@ -6860,6 +6856,7 @@ function apply(ctx, config = {}) {
6860
6856
  return void 0;
6861
6857
  }
6862
6858
  }));
6859
+ if (probeStopped) return;
6863
6860
  const askable = keys.flatMap((key, index) => {
6864
6861
  const value = values[index];
6865
6862
  return value === void 0 || value.length === 0 ? [] : [{ ...key, value }];
@@ -6873,6 +6870,7 @@ function apply(ctx, config = {}) {
6873
6870
  keys: askable,
6874
6871
  refOf: (key) => key.ref,
6875
6872
  probe: async (key) => {
6873
+ if (probeStopped) return { ref: key.ref, models: void 0 };
6876
6874
  const listings = await Promise.all(targetsOf(key.entry).map((target) => probeListing({
6877
6875
  baseURL: target.baseURL,
6878
6876
  api: target.api,
@@ -6881,6 +6879,7 @@ function apply(ctx, config = {}) {
6881
6879
  timeoutMs,
6882
6880
  send
6883
6881
  })));
6882
+ if (probeStopped) return { ref: key.ref, models: void 0 };
6884
6883
  const ids = [];
6885
6884
  for (const listing of listings) {
6886
6885
  if (listing === void 0) continue;
@@ -6890,38 +6889,47 @@ function apply(ctx, config = {}) {
6890
6889
  }
6891
6890
  if (ids.length === 0) return { ref: key.ref, models: void 0 };
6892
6891
  served.set(key.ref, ids);
6893
- lastKnownScopes.set(`${route}\0${key.ref}`, ids);
6894
- recordServes(route, key.ref, ids);
6895
6892
  return { ref: key.ref, models: ids };
6896
6893
  }
6897
6894
  });
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;
6895
+ if (probeStopped || served.size === 0) return;
6896
+ const releaseMutation = await acquireKeyMutation(indexFile);
6915
6897
  try {
6916
- writeKeyIndex(next, keyIndexFilePath());
6917
- } catch {
6918
- return;
6898
+ if (probeStopped) return;
6899
+ const currentProfile = providerProfileOf(settings.describe().find((entry) => entry.ns === PI_NS)?.value, route);
6900
+ if (currentProfile === void 0) return;
6901
+ const declared = Array.isArray(currentProfile["models"]) ? currentProfile["models"].filter(isRecord).map((model) => typeof model["id"] === "string" ? model["id"].trim() : "").filter(Boolean) : [];
6902
+ if (declared.length === 0) return;
6903
+ let next = readKeyIndex(indexFile);
6904
+ let mutated = false;
6905
+ for (const [ref, ids] of served) {
6906
+ lastKnownScopes.set(`${route}\0${ref}`, ids);
6907
+ recordServes(route, ref, ids);
6908
+ const entry = keyEntriesOf(next, route).find((candidate) => candidate.ref === ref);
6909
+ if (entry === void 0) continue;
6910
+ if (entry.models !== void 0 && entry.auto !== true) continue;
6911
+ const target = declared.filter((id) => ids.includes(id));
6912
+ const scope = target.length === declared.length ? void 0 : target;
6913
+ 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));
6914
+ if (unchanged) continue;
6915
+ next = withKeyAutoScope(next, route, ref, scope);
6916
+ mutated = true;
6917
+ }
6918
+ if (!mutated) return;
6919
+ try {
6920
+ writeKeyIndex(next, indexFile);
6921
+ } catch {
6922
+ return;
6923
+ }
6924
+ refreshKeyScopes();
6925
+ } finally {
6926
+ releaseMutation();
6919
6927
  }
6920
- refreshKeyScopes();
6921
6928
  };
6922
6929
  const runKeyProbe = (route) => {
6930
+ if (probeStopped) return Promise.resolve();
6923
6931
  const previous = keyProbeRuns.get(route) ?? Promise.resolve();
6924
- const run = previous.then(() => probeRouteKeys(route)).catch(() => {
6932
+ const run = previous.then(() => probeStopped ? void 0 : probeRouteKeys(route)).catch(() => {
6925
6933
  }).finally(() => {
6926
6934
  if (keyProbeRuns.get(route) === run) keyProbeRuns.delete(route);
6927
6935
  });
@@ -6968,7 +6976,6 @@ function apply(ctx, config = {}) {
6968
6976
  if (ns === PI_NS) {
6969
6977
  refreshHeaders();
6970
6978
  refreshKeyScopes();
6971
- sweepVanishedRoutes();
6972
6979
  syncImageConfigNow();
6973
6980
  const source = catalogueSource();
6974
6981
  if (source !== catalogueSourceStamp) {
@@ -6977,21 +6984,6 @@ function apply(ctx, config = {}) {
6977
6984
  }
6978
6985
  }
6979
6986
  });
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
6987
  overlaySource.keys = async ({ route, model }) => {
6996
6988
  const scopes = keyScopes.current[route] ?? [];
6997
6989
  if (scopes.length === 0) return [];
@@ -7468,13 +7460,13 @@ function apply(ctx, config = {}) {
7468
7460
  }),
7469
7461
  "dsh-model-think-level: provider-key route"
7470
7462
  );
7471
- let keyMutationTail = Promise.resolve();
7472
7463
  ctx.effect(
7473
7464
  () => webServerCtx.webServer.register({
7474
7465
  kind: "exact",
7475
7466
  path: KEY_INDEX_PATH,
7476
7467
  handler: async (req, res) => {
7477
7468
  res.setHeader("cache-control", "no-store");
7469
+ res.setHeader("x-dsh-key-integrity", "20261101-explicit-delete+history64+shared-lease-drain");
7478
7470
  if (!isTrustedRequest(req)) {
7479
7471
  sendJson(res, 403, { ok: false, error: "forbidden" });
7480
7472
  return;
@@ -7485,21 +7477,25 @@ function apply(ctx, config = {}) {
7485
7477
  }
7486
7478
  const url = new URL(req.url ?? "/", "http://x");
7487
7479
  const route = url.searchParams.get("route") ?? "";
7480
+ const indexFile = keyIndexFilePath();
7481
+ const pendingMutations = new PendingCredentialMutations();
7488
7482
  let releaseMutation;
7489
7483
  try {
7490
7484
  if (req.method === "POST") {
7491
- const previous = keyMutationTail;
7492
- keyMutationTail = new Promise((resolve3) => {
7493
- releaseMutation = resolve3;
7494
- });
7495
- await previous;
7485
+ const release = await acquireKeyMutation(indexFile);
7486
+ let finished = false;
7487
+ releaseMutation = () => {
7488
+ if (finished) return;
7489
+ finished = true;
7490
+ pendingMutations.releaseAfterSettled(release);
7491
+ };
7496
7492
  }
7497
7493
  if (req.method === "GET" && url.searchParams.get("op") === "endpoints") {
7498
7494
  if (route.length === 0) {
7499
7495
  sendJson(res, 400, { ok: false, error: "a route is required" });
7500
7496
  return;
7501
7497
  }
7502
- const endpoints = readKeyIndex(keyIndexFilePath()).endpoints?.[route];
7498
+ const endpoints = routeEndpointsOf(readKeyIndex(indexFile), route);
7503
7499
  sendJson(res, 200, {
7504
7500
  ok: true,
7505
7501
  route,
@@ -7515,7 +7511,7 @@ function apply(ctx, config = {}) {
7515
7511
  sendJson(res, 400, { ok: false, error: "a route is required" });
7516
7512
  return;
7517
7513
  }
7518
- const endpoint = readKeyIndex(keyIndexFilePath()).balances?.[route];
7514
+ const endpoint = routeBalanceOf(readKeyIndex(indexFile), route);
7519
7515
  sendJson(res, 200, { ok: true, route, endpoint: endpoint ?? null });
7520
7516
  return;
7521
7517
  }
@@ -7536,7 +7532,6 @@ function apply(ctx, config = {}) {
7536
7532
  return;
7537
7533
  }
7538
7534
  const credentials = ctx.get("credentials");
7539
- const indexFile = keyIndexFilePath();
7540
7535
  const enabledNow = () => enabledRefOf(providerProfileOf(entryOf()?.value, route));
7541
7536
  const setEnabledKey = async (ref2) => {
7542
7537
  for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -7598,7 +7593,7 @@ function apply(ctx, config = {}) {
7598
7593
  }
7599
7594
  return view;
7600
7595
  });
7601
- const endpoints = document.endpoints?.[route];
7596
+ const endpoints = routeEndpointsOf(document, route);
7602
7597
  const probing = keyProbeRuns.has(route);
7603
7598
  return {
7604
7599
  ok: true,
@@ -7687,7 +7682,7 @@ function apply(ctx, config = {}) {
7687
7682
  }
7688
7683
  const seatBefore = active;
7689
7684
  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);
7685
+ const refused = await storeCredential(credentials, created, value, pendingMutations);
7691
7686
  if (refused !== void 0) {
7692
7687
  refuse(refused);
7693
7688
  return;
@@ -7701,7 +7696,7 @@ function apply(ctx, config = {}) {
7701
7696
  if (failed !== void 0) throw new Error(failed);
7702
7697
  }
7703
7698
  } catch (error) {
7704
- const rollback = await forgetCredential(credentials, created, CREDENTIAL_IPC_BUDGET_MS);
7699
+ const rollback = await forgetCredential(credentials, created, pendingMutations, CREDENTIAL_IPC_BUDGET_MS);
7705
7700
  if (rollback === void 0 && indexed) {
7706
7701
  updateKeyIndex((document) => withoutKeyEntry(document, route, created), indexFile);
7707
7702
  }
@@ -7823,7 +7818,7 @@ function apply(ctx, config = {}) {
7823
7818
  refuse("a key must be printable ASCII without spaces");
7824
7819
  return;
7825
7820
  }
7826
- const refused = await storeCredential(credentials, ref, value);
7821
+ const refused = await storeCredential(credentials, ref, value, pendingMutations);
7827
7822
  if (refused !== void 0) {
7828
7823
  refuse(refused);
7829
7824
  return;
@@ -7853,17 +7848,17 @@ function apply(ctx, config = {}) {
7853
7848
  forgetServes(route, ref);
7854
7849
  invalidateCredentialDisplay(credentials, ref);
7855
7850
  if (configured) {
7856
- const refused = await forgetCredential(credentials, ref, CREDENTIAL_IPC_BUDGET_MS);
7851
+ const refused = await forgetCredential(credentials, ref, pendingMutations, CREDENTIAL_IPC_BUDGET_MS);
7857
7852
  if (refused !== void 0) throw new Error(refused);
7858
7853
  }
7859
7854
  } catch (error) {
7860
7855
  const failures = [];
7861
7856
  try {
7862
7857
  updateKeyIndex((current) => {
7858
+ const original = Object.hasOwn(document.providers, route) ? document.providers[route] : void 0;
7859
+ if (original !== void 0) return { ...current, providers: { ...current.providers, [route]: original } };
7863
7860
  const providers = { ...current.providers };
7864
- const original = document.providers[route];
7865
- if (original === void 0) delete providers[route];
7866
- else providers[route] = original;
7861
+ delete providers[route];
7867
7862
  return { ...current, providers };
7868
7863
  }, indexFile);
7869
7864
  } catch {
@@ -7936,7 +7931,7 @@ function apply(ctx, config = {}) {
7936
7931
  sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
7937
7932
  return;
7938
7933
  }
7939
- const endpoint = document.balances?.[route];
7934
+ const endpoint = routeBalanceOf(document, route);
7940
7935
  if (endpoint === void 0) {
7941
7936
  sendJson(res, 200, { ok: true, route, configured: false });
7942
7937
  return;
@@ -8185,8 +8180,8 @@ function apply(ctx, config = {}) {
8185
8180
  }
8186
8181
  let releaseMutation;
8187
8182
  const previous = fingerprintMutationTail;
8188
- fingerprintMutationTail = new Promise((resolve3) => {
8189
- releaseMutation = resolve3;
8183
+ fingerprintMutationTail = new Promise((resolve4) => {
8184
+ releaseMutation = resolve4;
8190
8185
  });
8191
8186
  await previous;
8192
8187
  try {