@cortexkit/pi-claustrum-auth 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1428 -1121
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -140,10 +140,10 @@ function isBalanceFailure(service, body) {
140
140
  }
141
141
  // ../core/src/billing.ts
142
142
  import { randomUUID } from "node:crypto";
143
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
143
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
144
144
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
145
145
 
146
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/opencode2/sse.js
146
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/opencode2/sse.js
147
147
  function parseBlock(block) {
148
148
  const data = [];
149
149
  let event;
@@ -197,7 +197,7 @@ function watchServerSentEvents(onEvent, onError) {
197
197
  }
198
198
  });
199
199
  }
200
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/handle.js
200
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/routing-accessor/handle.js
201
201
  function routingHandle(sessionId) {
202
202
  const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
203
203
  if (typeof routing !== "function")
@@ -206,7 +206,7 @@ function routingHandle(sessionId) {
206
206
  return typeof handle === "object" && handle !== null ? handle : undefined;
207
207
  }
208
208
 
209
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/cache-policy.js
209
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/routing-accessor/cache-policy.js
210
210
  var CACHE_WARM_STOP_REASONS = [
211
211
  "cost-cap",
212
212
  "count-cap",
@@ -293,7 +293,7 @@ function sessionCachePolicy(sessionId) {
293
293
  }
294
294
  }
295
295
 
296
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
296
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
297
297
  function isObject(value) {
298
298
  return typeof value === "object" && value !== null;
299
299
  }
@@ -347,6 +347,87 @@ function billingUsage(value) {
347
347
  }
348
348
  return Object.keys(usage).length > 0 ? usage : undefined;
349
349
  }
350
+ function selectionFor(answer, candidates) {
351
+ if (!isObject(answer))
352
+ return;
353
+ const accountId = answer.account_id;
354
+ const credentialId = answer.credential_id;
355
+ if (typeof accountId !== "string")
356
+ return;
357
+ if (credentialId !== undefined && typeof credentialId !== "string") {
358
+ return;
359
+ }
360
+ const candidate = candidates.find((route) => route.accountId === accountId && (credentialId === undefined || route.credentialId === credentialId));
361
+ if (!candidate)
362
+ return;
363
+ const hold = answer.hold;
364
+ const retryAfterMs = isObject(hold) ? hold.retry_after_ms : undefined;
365
+ if (typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
366
+ return { candidate, hold: { retry_after_ms: retryAfterMs } };
367
+ }
368
+ return { candidate };
369
+ }
370
+ function refusalFor(value) {
371
+ if (!isObject(value))
372
+ return;
373
+ const code = value.code;
374
+ if (code !== "account_limit_exhausted" && code !== "account_selection_refused" && code !== "account_selection_final") {
375
+ return;
376
+ }
377
+ const refused = { code };
378
+ const routingCode = value.routing_code;
379
+ if (typeof routingCode === "string" && /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
380
+ refused.routingCode = routingCode;
381
+ }
382
+ const retryAfterSecs = value.retry_after_secs;
383
+ if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs >= 0) {
384
+ refused.retryAfterSecs = retryAfterSecs;
385
+ }
386
+ const resetsAtMs = value.resets_at_ms;
387
+ if (typeof resetsAtMs === "number" && Number.isSafeInteger(resetsAtMs) && resetsAtMs > 0) {
388
+ refused.resetsAtMs = resetsAtMs;
389
+ }
390
+ return { refused };
391
+ }
392
+ async function askRouting(input) {
393
+ let timer;
394
+ try {
395
+ const handle = routingHandle(input.sessionId);
396
+ if (!handle)
397
+ return;
398
+ const accountFor = handle.accountFor;
399
+ if (typeof accountFor !== "function")
400
+ return;
401
+ const requested = input.deadlineMs ?? 1500;
402
+ const deadlineMs = Number.isNaN(requested) ? 1500 : Math.min(2000, Math.max(1, requested));
403
+ const expired = new Promise((resolve) => {
404
+ timer = setTimeout(() => resolve(undefined), deadlineMs);
405
+ timer.unref();
406
+ });
407
+ const request = {
408
+ provider: input.provider,
409
+ modelId: input.modelId
410
+ };
411
+ const cap = input.holdWaitMaxS;
412
+ if (typeof cap === "number" && Number.isFinite(cap)) {
413
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
414
+ }
415
+ if (input.refusals === true)
416
+ request.refusals = true;
417
+ const pending = accountFor.call(handle, request, { deadlineMs });
418
+ if (!isObject(pending) || typeof pending.then !== "function")
419
+ return;
420
+ const answer = await Promise.race([pending, expired]);
421
+ if (input.refusals === true && isObject(answer) && "refused" in answer) {
422
+ return refusalFor(answer.refused);
423
+ }
424
+ return selectionFor(answer, input.candidates);
425
+ } catch {
426
+ return;
427
+ } finally {
428
+ clearTimeout(timer);
429
+ }
430
+ }
350
431
  function reportRouting(input) {
351
432
  try {
352
433
  const handle = routingHandle(input.sessionId);
@@ -448,6 +529,17 @@ function reportRouting(input) {
448
529
  };
449
530
  break;
450
531
  }
532
+ case "credential_refused": {
533
+ const { credentialId, providerCode } = input;
534
+ if (!isNonEmptyString(credentialId) || typeof providerCode !== "string" || !/^[a-z0-9._-]{1,64}$/.test(providerCode))
535
+ return;
536
+ payload = {
537
+ ...identity,
538
+ outcome: "credential_refused",
539
+ provider_code: providerCode
540
+ };
541
+ break;
542
+ }
451
543
  default:
452
544
  return;
453
545
  }
@@ -711,7 +803,7 @@ function observeBillingResponse(record, response) {
711
803
  // ../core/src/fetch.ts
712
804
  import { randomUUID as randomUUID8 } from "node:crypto";
713
805
 
714
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/request-history.js
806
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/request-history.js
715
807
  function sameAccount(a, b) {
716
808
  return a.namespace === b.namespace && a.accountId === b.accountId && a.incarnation === b.incarnation;
717
809
  }
@@ -809,7 +901,7 @@ var REQUEST_EXCLUSION_EFFECTS = Object.freeze({
809
901
  chargeSwitch: false
810
902
  });
811
903
 
812
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/activity.js
904
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/activity.js
813
905
  function effectiveCacheTtlMs(ttlMs) {
814
906
  return ttlMs !== undefined && Number.isFinite(ttlMs) && ttlMs >= 0 ? ttlMs : 300000;
815
907
  }
@@ -854,7 +946,7 @@ function createSessionActivityStore() {
854
946
  }
855
947
  };
856
948
  }
857
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/scope.js
949
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/scope.js
858
950
  function scopeCovers(scope, model, familyOf) {
859
951
  switch (scope.kind) {
860
952
  case "pool":
@@ -865,20 +957,20 @@ function scopeCovers(scope, model, familyOf) {
865
957
  return scope.model === model;
866
958
  }
867
959
  }
868
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/hold.js
960
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/hold.js
869
961
  var MAX_SAME_ACCOUNT_HOLD_MS = 3621000;
870
962
  function readMaxSameAccountWait(value) {
871
963
  return value === 0 || value === 15 || value === "max" ? value : 15;
872
964
  }
873
965
 
874
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/jitter.js
966
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/jitter.js
875
967
  import { createHash } from "node:crypto";
876
968
  function holdDelayMs(sessionId, delayMs) {
877
969
  const seconds = createHash("sha256").update(sessionId).digest().readUInt32BE(0);
878
970
  return 1000 * (Math.max(1, Math.ceil(delayMs / 1000)) + seconds % 21);
879
971
  }
880
972
 
881
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/terminal.js
973
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/terminal.js
882
974
  function scanTerminalReset(input, now) {
883
975
  if (!Number.isFinite(input.maxAgeMs) || input.maxAgeMs < 0)
884
976
  return;
@@ -979,7 +1071,7 @@ function terminalRefusalDecision(facts, axes, history, metadata) {
979
1071
  return { ...wait, action: "hold", account: kept.account };
980
1072
  }
981
1073
 
982
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/wake.js
1074
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/wake.js
983
1075
  function waitCheckpoint(accountKey, decidedAt, windows) {
984
1076
  return {
985
1077
  accountKey: { ...accountKey },
@@ -1001,7 +1093,7 @@ function liftedWindowsForWake(wake, account, windows, now) {
1001
1093
  return windows.filter((window) => canLift(window) && windows.filter((other) => other.confirmed && other.window === window.window).every(canLift)).map((window) => window.window);
1002
1094
  }
1003
1095
 
1004
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/decide.js
1096
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/decide.js
1005
1097
  function finiteFuture(value, now) {
1006
1098
  return value !== undefined && Number.isFinite(value) && value > now;
1007
1099
  }
@@ -1266,7 +1358,7 @@ function decideAfterLimit(facts, axes) {
1266
1358
  return refusal(facts, axes, history, "quota");
1267
1359
  return pass("no-override");
1268
1360
  }
1269
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/duration.js
1361
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/duration.js
1270
1362
  function formatDuration(ms) {
1271
1363
  if (!Number.isFinite(ms))
1272
1364
  return "unknown";
@@ -1286,7 +1378,7 @@ function formatDuration(ms) {
1286
1378
  return `${remainingMinutes}m`;
1287
1379
  }
1288
1380
  var formatReset = ({ resetAt, now }) => formatDuration(resetAt - now);
1289
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/envelope.js
1381
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/envelope.js
1290
1382
  var envelopeError = Symbol.for("@cortexkit/common-auth/limits-envelope-error");
1291
1383
 
1292
1384
  class LimitsEnvelopeConflictError extends Error {
@@ -1373,7 +1465,7 @@ class EnvelopeGuard {
1373
1465
  return true;
1374
1466
  }
1375
1467
  }
1376
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/wording.js
1468
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/wording.js
1377
1469
  var openCode1Patterns = [
1378
1470
  /429|500|502|503|504|524/i,
1379
1471
  /rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,
@@ -1439,7 +1531,7 @@ function hasUnsafeWording(text) {
1439
1531
  return openCode1Patterns.some((pattern) => pattern.test(text)) || pi140Pattern.test(text);
1440
1532
  }
1441
1533
 
1442
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/labels.js
1534
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/labels.js
1443
1535
  var emailPattern = /[^\s@]+@[^\s@]+\.[^\s@]+/;
1444
1536
  function containsEmail(text) {
1445
1537
  return emailPattern.test(text);
@@ -1448,7 +1540,7 @@ function sanitizeRefusalLabel(label) {
1448
1540
  return containsEmail(label) || hasUnsafeWording(label) ? "this account" : label;
1449
1541
  }
1450
1542
 
1451
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/families.js
1543
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/families.js
1452
1544
  class ClaudeIncompleteError extends Error {
1453
1545
  code = "ECONNRESET";
1454
1546
  syscall = "sticky-routing";
@@ -1566,7 +1658,7 @@ function buildRefusal(input) {
1566
1658
  body
1567
1659
  };
1568
1660
  }
1569
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/identity.js
1661
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/identity.js
1570
1662
  function isIdentityCompatible(a, b) {
1571
1663
  return sameAccount(a.account, b.account) && (a.identity === undefined || b.identity === undefined || a.identity === b.identity);
1572
1664
  }
@@ -1582,7 +1674,7 @@ function validateIdentityFence(observed, authoritative, authorizeEpoch) {
1582
1674
  return "credential-epoch";
1583
1675
  return;
1584
1676
  }
1585
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/marker.js
1677
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/marker.js
1586
1678
  var ANTIGRAVITY_FAILURE_LADDER = Object.freeze({
1587
1679
  kind: "failure-ladder",
1588
1680
  mergeLaw: "max-until",
@@ -1653,7 +1745,7 @@ function markFromSignal(signal, axes, history) {
1653
1745
  ...axes.kind === "hint" && axes.causes?.some((cause) => cause === signal.kind) ? { cause: signal.kind } : {}
1654
1746
  } : undefined;
1655
1747
  }
1656
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/merge-laws.js
1748
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/merge-laws.js
1657
1749
  function mergeTimedMarkEntries(law, entries, now, clearRevision = 0) {
1658
1750
  const candidates = entries.filter((e) => e.baseRevision >= clearRevision);
1659
1751
  if (law !== "max-until") {
@@ -1675,7 +1767,7 @@ function mergeAccessState(a, b) {
1675
1767
  }
1676
1768
  return a.committedRevision > b.committedRevision ? a : b;
1677
1769
  }
1678
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/namespace.js
1770
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/namespace.js
1679
1771
  var LIMITS_HISTORY_BOUND = 1024;
1680
1772
  function storedCause(cause) {
1681
1773
  return cause === "rate-limit" || cause === "payment-balance" ? cause : undefined;
@@ -1868,7 +1960,7 @@ function applyLimitsCommands(initial, commands, context) {
1868
1960
  }
1869
1961
  return { snapshot, outcomes };
1870
1962
  }
1871
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/path.js
1963
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/path.js
1872
1964
  import { realpathSync } from "node:fs";
1873
1965
  import { basename, dirname, join, resolve } from "node:path";
1874
1966
  function canonicalLimitsPath(path) {
@@ -1890,7 +1982,7 @@ function canonicalLimitsPath(path) {
1890
1982
  }
1891
1983
  }
1892
1984
  }
1893
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/persistence.js
1985
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/persistence.js
1894
1986
  class LimitsPersistenceRefusal extends Error {
1895
1987
  code;
1896
1988
  constructor(code) {
@@ -1899,7 +1991,7 @@ class LimitsPersistenceRefusal extends Error {
1899
1991
  this.name = "LimitsPersistenceRefusal";
1900
1992
  }
1901
1993
  }
1902
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/envelope-loss.js
1994
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/envelope-loss.js
1903
1995
  import { AsyncResource } from "node:async_hooks";
1904
1996
  import { randomUUID as randomUUID2 } from "node:crypto";
1905
1997
  import { isDeepStrictEqual } from "node:util";
@@ -2024,7 +2116,7 @@ class EnvelopeHistory {
2024
2116
  }, now);
2025
2117
  }
2026
2118
  }
2027
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/presets.js
2119
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/presets.js
2028
2120
  function immutable(value) {
2029
2121
  if (value && typeof value === "object") {
2030
2122
  for (const child of Object.values(value))
@@ -2264,7 +2356,7 @@ var limitPresets = immutable({
2264
2356
  "window-router": windowRouter,
2265
2357
  "status-vault-order": statusVaultOrder
2266
2358
  });
2267
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/registry.js
2359
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/registry.js
2268
2360
  import { AsyncResource as AsyncResource2 } from "node:async_hooks";
2269
2361
  var LIMITS_REGISTRY_KEY = Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1");
2270
2362
  var PREFIX = "@cortexkit/common-auth/limits-registry/schema-v";
@@ -2729,20 +2821,20 @@ async function acquireLimitsRegistry(options) {
2729
2821
  // ../core/src/limits.ts
2730
2822
  import { randomUUID as randomUUID7 } from "node:crypto";
2731
2823
 
2732
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
2824
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
2733
2825
  import { randomUUID as randomUUID6 } from "node:crypto";
2734
2826
 
2735
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
2827
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
2736
2828
  import { createHash as createHash2 } from "node:crypto";
2737
2829
  import { stat as stat3 } from "node:fs/promises";
2738
2830
  import { resolve as resolve8 } from "node:path";
2739
2831
 
2740
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
2832
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
2741
2833
  import { lstat, stat } from "node:fs/promises";
2742
2834
  import { resolve as resolve2 } from "node:path";
2743
- async function identity(path, followSymlinks) {
2835
+ async function identity(path, probe) {
2744
2836
  try {
2745
- const metadata = await (followSymlinks ? stat(path) : lstat(path));
2837
+ const metadata = await probe(path);
2746
2838
  return metadata.isFile() ? metadata : undefined;
2747
2839
  } catch (error) {
2748
2840
  return error.code === "ENOENT" ? "absent" : undefined;
@@ -2755,15 +2847,15 @@ function sameIdentity(left, right) {
2755
2847
  }
2756
2848
 
2757
2849
  class FileReadCache {
2758
- #followSymlinks;
2850
+ #probe;
2759
2851
  #entries = new Map;
2760
2852
  constructor(options = {}) {
2761
- this.#followSymlinks = options.followSymlinks ?? false;
2853
+ this.#probe = options.followSymlinks ? (path) => (options.stat ?? stat)(path) : (path) => (options.lstat ?? lstat)(path);
2762
2854
  }
2763
2855
  async read(paths, read, validateHit) {
2764
2856
  const resolvedPaths = paths.map((path) => resolve2(path));
2765
2857
  const key = JSON.stringify(resolvedPaths);
2766
- const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
2858
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#probe)));
2767
2859
  const identities = probed.every((entry) => entry !== undefined) ? probed : undefined;
2768
2860
  const cached = this.#entries.get(key);
2769
2861
  if (identities && cached && identities.every((entry, index) => {
@@ -2787,12 +2879,12 @@ class FileReadCache {
2787
2879
  }
2788
2880
  }
2789
2881
 
2790
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
2882
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
2791
2883
  import { randomUUID as randomUUID4 } from "node:crypto";
2792
2884
  import { mkdir, open, rename as rename2, rm } from "node:fs/promises";
2793
2885
  import { dirname as dirname3 } from "node:path";
2794
2886
 
2795
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/private-files.js
2887
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/private-files.js
2796
2888
  import { randomUUID as randomUUID3 } from "node:crypto";
2797
2889
  import { lstat as lstat2, readFile, rename, unlink } from "node:fs/promises";
2798
2890
  import { tmpdir } from "node:os";
@@ -3087,7 +3179,7 @@ async function writePrivateAtomic(path, bytes, options = {}) {
3087
3179
  }
3088
3180
  }
3089
3181
 
3090
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
3182
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/atomic-write.js
3091
3183
  class AtomicSyncError extends Error {
3092
3184
  constructor(cause) {
3093
3185
  super("file or directory sync failed", { cause });
@@ -3148,7 +3240,7 @@ async function writeJsonAtomicTracked(path, value, options, onRenamed) {
3148
3240
  await rm(tempPath, { force: true }).catch(() => {});
3149
3241
  }
3150
3242
  }
3151
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/lock-constants.js
3243
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/lock-constants.js
3152
3244
  var WRITER_LOCK_CONSTANTS = Object.freeze({
3153
3245
  sidebar: Object.freeze({
3154
3246
  name: "sidebar-write",
@@ -3163,679 +3255,1095 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
3163
3255
  renew: true
3164
3256
  })
3165
3257
  });
3166
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3258
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3167
3259
  import { randomUUID as randomUUID5 } from "node:crypto";
3168
- import { link, lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
3169
- import { dirname as dirname4, join as join4 } from "node:path";
3260
+ import { link, lstat as lstat3, mkdir as mkdir2, open as open3, readdir, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2, unlink as unlink2 } from "node:fs/promises";
3261
+ import { basename as basename2, dirname as dirname5, join as join4 } from "node:path";
3262
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/logger/engine.js
3263
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
3264
+ import { open as open2 } from "node:fs/promises";
3265
+ import { dirname as dirname4, resolve as resolve4 } from "node:path";
3170
3266
 
3171
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/lock-record.js
3172
- import { resolve as resolve4 } from "node:path";
3173
- class DisappearedLockRecordError extends Error {
3174
- path;
3175
- code = "ENOENT";
3176
- constructor(path, cause) {
3177
- super(`Lock record disappeared: ${path}`, { cause });
3178
- this.path = path;
3179
- }
3180
- }
3181
- function isWindowsAccessDeniedRead(error, paths) {
3182
- return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path) => resolve4(path) === error.path);
3183
- }
3184
- function isWindowsAccessDeniedCreate(error, paths, stage) {
3185
- return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path) => resolve4(path) === error.path);
3267
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/logger/redact.js
3268
+ var SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
3269
+ var TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
3270
+ var MASK = "***REDACTED***";
3271
+ var MAX_ERROR_DEPTH = 8;
3272
+ function isError(value) {
3273
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
3186
3274
  }
3187
- async function readLockRecord(path, read) {
3188
- try {
3189
- return await read();
3190
- } catch (error) {
3191
- if (!isWindowsAccessDeniedRead(error, [path]))
3192
- throw error;
3275
+ function createRedactor(options = {}) {
3276
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
3277
+ function isSecretKey(key) {
3278
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
3279
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
3280
+ }
3281
+ function errorEntries(error) {
3282
+ const fields = error;
3283
+ const entries = [
3284
+ ["name", error.name],
3285
+ ["message", error.message],
3286
+ ["stack", error.stack]
3287
+ ];
3288
+ for (const key of ["code", "status", "cause"])
3289
+ if (fields[key] !== undefined)
3290
+ entries.push([key, fields[key]]);
3291
+ const listed = new Set(entries.map(([key]) => key));
3292
+ for (const entry of Object.entries(error))
3293
+ if (!listed.has(entry[0]))
3294
+ entries.push(entry);
3295
+ return entries;
3296
+ }
3297
+ function walk(value, keys, seen, errorDepth = 0) {
3298
+ if (typeof value === "string") {
3299
+ return patterns.reduce((text, pattern) => text.replace(pattern, MASK), value);
3300
+ }
3301
+ if (!value || typeof value !== "object")
3302
+ return value;
3303
+ if (seen.has(value))
3304
+ return "[Circular]";
3305
+ seen.add(value);
3193
3306
  try {
3194
- return await read();
3195
- } catch (recheckError) {
3196
- if (recheckError.code === "ENOENT")
3197
- throw new DisappearedLockRecordError(path, error);
3198
- throw error;
3307
+ if (Array.isArray(value))
3308
+ return value.map((item) => walk(item, keys, seen, errorDepth));
3309
+ const error = isError(value);
3310
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
3311
+ return "[Truncated]";
3312
+ const childDepth = error ? errorDepth + 1 : errorDepth;
3313
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
3314
+ key,
3315
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
3316
+ ]));
3317
+ } finally {
3318
+ seen.delete(value);
3199
3319
  }
3200
3320
  }
3321
+ return {
3322
+ redact: (value) => walk(value, true, new WeakSet),
3323
+ redactStrings: (value) => walk(value, false, new WeakSet)
3324
+ };
3201
3325
  }
3326
+ var defaultRedactor = createRedactor();
3327
+ var redact = defaultRedactor.redact;
3328
+ var redactStrings = defaultRedactor.redactStrings;
3202
3329
 
3203
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
3204
- import { join as join3, resolve as resolve5 } from "node:path";
3205
- function lockPathFor(target, name) {
3206
- return `${target}.${name}.lock`;
3207
- }
3208
-
3209
- class LockContentionError extends Error {
3210
- details;
3211
- constructor(details) {
3212
- super(`Timed out acquiring ${details.name} lock for ${details.target}`);
3213
- this.name = "LockContentionError";
3214
- this.details = details;
3215
- }
3216
- }
3217
-
3218
- class LockOwnershipError extends Error {
3219
- details;
3220
- constructor(details) {
3221
- super(`Lost ${details.name} lock for ${details.target}`);
3222
- this.name = "LockOwnershipError";
3223
- this.details = details;
3224
- }
3225
- }
3226
- function isChangingLockRecord(error, target, name) {
3227
- const path = resolve5(lockPathFor(target, name));
3228
- const paths = [path, join3(path, "owner.json")];
3229
- return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path], "create") || isWindowsAccessDeniedCreate(error, [`${path}.evicting`], "directory-create"));
3330
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/logger/engine.js
3331
+ var ORDER = {
3332
+ error: 0,
3333
+ warn: 1,
3334
+ info: 2,
3335
+ debug: 3,
3336
+ trace: 4
3337
+ };
3338
+ var MAX_BYTES = 5 * 1024 * 1024;
3339
+ var ROTATE_KEEP = 3;
3340
+ function chmodPrivate(path) {
3341
+ try {
3342
+ chmodSync(path, 384);
3343
+ } catch {}
3230
3344
  }
3231
- async function withLock(target, options, fn) {
3232
- const started = performance.now();
3233
- let changingRecordError;
3234
- for (;; ) {
3235
- options.signal?.throwIfAborted();
3236
- let lock;
3237
- try {
3238
- lock = await acquireRefreshFileLock({
3239
- path: target,
3240
- name: options.name,
3241
- ttlMs: options.ttlMs,
3242
- renew: options.renew ?? false,
3243
- ...options.onStep ? { onStep: options.onStep } : {},
3244
- ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
3245
- });
3246
- changingRecordError = undefined;
3247
- } catch (error) {
3248
- if (!isChangingLockRecord(error, target, options.name))
3249
- throw error;
3250
- lock = null;
3251
- changingRecordError ??= error;
3252
- }
3253
- if (lock) {
3254
- try {
3255
- options.signal?.throwIfAborted();
3256
- return await fn(lock);
3257
- } finally {
3258
- await lock.release(options.signal);
3345
+ function rotateIfNeeded(f) {
3346
+ try {
3347
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
3348
+ return;
3349
+ for (let i = ROTATE_KEEP - 1;i >= 1; i--) {
3350
+ if (existsSync(`${f}.${i}`)) {
3351
+ const rotated = `${f}.${i + 1}`;
3352
+ renameSync(`${f}.${i}`, rotated);
3353
+ chmodPrivate(rotated);
3259
3354
  }
3260
3355
  }
3261
- const remaining = options.timeoutMs - (performance.now() - started);
3262
- if (remaining <= 0) {
3263
- if (changingRecordError)
3264
- throw changingRecordError;
3265
- throw new LockContentionError({
3266
- target,
3267
- name: options.name,
3268
- timeoutMs: options.timeoutMs
3269
- });
3270
- }
3271
- await new Promise((resolve) => setTimeout(resolve, Math.min(25, Math.ceil(remaining))));
3272
- }
3356
+ const rotated = `${f}.1`;
3357
+ renameSync(f, rotated);
3358
+ chmodPrivate(rotated);
3359
+ } catch {}
3273
3360
  }
3274
-
3275
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3276
- var leaseCreationTestHooks;
3277
- async function createExclusiveText(path, text) {
3278
- const tempPath = `${path}.${randomUUID5()}.tmp`;
3279
- let handle;
3361
+ async function closeWindowsFile(sink) {
3362
+ const { file, handle } = sink;
3363
+ sink.file = undefined;
3364
+ sink.handle = undefined;
3365
+ if (file && handle)
3366
+ await privateOperation(file, "log-close", () => handle.close());
3367
+ }
3368
+ async function openWindowsFile(sink, file) {
3369
+ await ensurePrivateDirectory(dirname4(file));
3280
3370
  try {
3281
- handle = await open2(tempPath, "wx", 384);
3282
- try {
3283
- if (leaseCreationTestHooks?.beforeWrite)
3284
- await leaseCreationTestHooks.beforeWrite(tempPath);
3285
- await handle.writeFile(text, "utf8");
3286
- } finally {
3287
- await handle.close();
3288
- }
3371
+ await verifyPrivate(file, "file", true);
3372
+ } catch (error) {
3373
+ if (error.code !== "ENOENT")
3374
+ throw error;
3289
3375
  try {
3290
- if (leaseCreationTestHooks?.beforeLink)
3291
- await leaseCreationTestHooks.beforeLink(tempPath, path);
3292
- await link(tempPath, path);
3293
- } catch (error) {
3294
- const code = error.code;
3295
- if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP" && code !== "EXDEV")
3296
- throw error;
3297
- await writeExclusiveText(path, text);
3376
+ await createPrivateBytes(file, "");
3377
+ } catch (creationError) {
3378
+ if (creationError.code !== "EEXIST")
3379
+ throw creationError;
3380
+ await verifyPrivate(file, "file", true);
3298
3381
  }
3299
- } finally {
3300
- if (handle)
3301
- await rm2(tempPath, { force: true }).catch(() => {});
3302
3382
  }
3383
+ sink.handle = await privateOperation(file, "log-open", () => open2(file, "a"));
3384
+ sink.file = file;
3385
+ return sink.handle;
3303
3386
  }
3304
- async function writeExclusiveText(path, text) {
3305
- const handle = await open2(path, "wx", 384);
3306
- let createdStat;
3307
- try {
3308
- createdStat = await handle.stat();
3309
- } catch {
3310
- createdStat = undefined;
3311
- }
3387
+ async function flushWindowsFile(sink, file, text) {
3388
+ file = resolve4(file);
3312
3389
  try {
3313
- if (leaseCreationTestHooks?.beforeWrite)
3314
- await leaseCreationTestHooks.beforeWrite(path);
3315
- await handle.writeFile(text, "utf8");
3316
- } catch (error) {
3317
- try {
3318
- const current = await lstat3(path).catch(() => {
3319
- return;
3320
- });
3321
- if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
3322
- await rm2(path, { force: true }).catch(() => {});
3390
+ if (sink.file !== file)
3391
+ await closeWindowsFile(sink);
3392
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
3393
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
3394
+ if (info.size >= MAX_BYTES) {
3395
+ await closeWindowsFile(sink);
3396
+ for (let i = ROTATE_KEEP - 1;i >= 0; i--) {
3397
+ const source = i === 0 ? file : `${file}.${i}`;
3398
+ const target = `${file}.${i + 1}`;
3399
+ try {
3400
+ await verifyPrivate(source, "file", true);
3401
+ } catch (error) {
3402
+ if (error.code === "ENOENT")
3403
+ continue;
3404
+ throw error;
3405
+ }
3406
+ try {
3407
+ await verifyPrivate(target, "file", true);
3408
+ } catch (error) {
3409
+ if (error.code !== "ENOENT")
3410
+ throw error;
3411
+ }
3412
+ await replaceWindowsFile(source, target);
3413
+ await verifyPrivate(target, "file");
3323
3414
  }
3324
- } catch {}
3415
+ handle = await openWindowsFile(sink, file);
3416
+ }
3417
+ await privateOperation(file, "log-append", () => handle.appendFile(text, "utf8"));
3418
+ } catch (error) {
3419
+ await closeWindowsFile(sink).catch(() => {});
3325
3420
  throw error;
3326
- } finally {
3327
- await handle.close();
3328
3421
  }
3329
3422
  }
3330
- var setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
3331
- var clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
3332
- function isLostMarkerRaceError(error) {
3333
- const code = error?.code;
3334
- return code === "ENOENT" || !windowsPrivateFiles && (code === "EINVAL" || code === "ENOTDIR");
3335
- }
3336
- var evictionMarkerTestHooks;
3337
- function sameMarkerDirectory(created, current) {
3338
- if (created.dev !== current.dev || created.ino !== current.ino)
3339
- return false;
3340
- if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
3341
- return false;
3342
- return true;
3343
- }
3344
- var OWNERLESS_MARKER_GRACE_MS = 1000;
3345
- function acquireRefreshFileLock(options) {
3346
- return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
3423
+ function safeSerialize(data) {
3424
+ try {
3425
+ return ` ${JSON.stringify(data)}`;
3426
+ } catch {
3427
+ return " [unserializable]";
3428
+ }
3347
3429
  }
3348
- async function acquireRefreshFileLockWithClock(options) {
3349
- const lockPath = lockPathFor(options.path, options.name);
3350
- const legacyOwnerPath = join4(lockPath, "owner.json");
3351
- const ownerId = randomUUID5();
3352
- const now = options.now ?? Date.now;
3353
- let renewTimer = null;
3354
- let released = false;
3355
- let releaseConfirmed = false;
3356
- let loss;
3357
- let resolveLoss;
3358
- const lostPromise = new Promise((resolve) => {
3359
- resolveLoss = resolve;
3360
- });
3361
- function notifyTimerStep(event) {
3362
- try {
3363
- const result = options.onRenewalTimer?.(event);
3364
- if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
3365
- Promise.resolve(result).catch(() => {});
3366
- }
3367
- } catch {}
3430
+ function createEngine(options) {
3431
+ let logFileSource;
3432
+ let initLevelSource;
3433
+ let runtimeLevel;
3434
+ let redactor = createRedactor();
3435
+ let captureSink;
3436
+ let buffer = [];
3437
+ let timer;
3438
+ let orderedSink = Promise.resolve();
3439
+ let sinkError;
3440
+ const windowsFile = {};
3441
+ function queueWindows(operation) {
3442
+ const next = orderedSink.then(operation);
3443
+ orderedSink = next.catch((error) => {
3444
+ sinkError = error;
3445
+ });
3446
+ return next;
3368
3447
  }
3369
- function cancelRenewalTimer() {
3370
- if (!renewTimer)
3371
- return;
3372
- clearRefreshLockRenewalTimeout(renewTimer);
3373
- renewTimer = null;
3374
- notifyTimerStep("cancelled");
3448
+ function configure(next) {
3449
+ if (windowsPrivateFiles && next.file !== logFileSource)
3450
+ queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {});
3451
+ logFileSource = next.file;
3452
+ initLevelSource = next.level;
3453
+ redactor = createRedactor(next);
3454
+ captureSink = next.captureSink;
3375
3455
  }
3376
- function recordLoss(reason, owner) {
3377
- if (loss || released)
3456
+ function setLogLevel(l) {
3457
+ if (l === undefined || l in ORDER)
3458
+ runtimeLevel = l;
3459
+ }
3460
+ function logFilePath() {
3461
+ if (logFileSource === undefined)
3378
3462
  return;
3379
- loss = Object.freeze({
3380
- reason,
3381
- expectedOwnerId: ownerId,
3382
- ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
3383
- ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
3384
- });
3385
- cancelRenewalTimer();
3386
- resolveLoss(loss);
3463
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
3464
+ return resolved || undefined;
3387
3465
  }
3388
- let terminalIOError;
3389
- let renewalInFlight = null;
3390
- const evictPath = `${lockPath}.evicting`;
3391
- const evictOwnerPath = join4(evictPath, "owner.json");
3392
- const evictOwnerId = randomUUID5();
3393
- const EVICT_TTL = 5000;
3394
- const MAX_STEAL_ATTEMPTS = 8;
3395
- function isChangingLockCreate(error) {
3396
- return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
3466
+ function configuredLevel() {
3467
+ if (runtimeLevel)
3468
+ return runtimeLevel;
3469
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
3470
+ if (floor && floor in ORDER)
3471
+ return floor;
3472
+ return "info";
3397
3473
  }
3398
- async function readOwner() {
3399
- if (windowsPrivateFiles) {
3400
- try {
3401
- return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
3402
- } catch (error) {
3403
- if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
3404
- throw error;
3405
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3406
- return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
3407
- }
3474
+ function flushLogs(close = true) {
3475
+ if (timer) {
3476
+ clearTimeout(timer);
3477
+ timer = undefined;
3478
+ }
3479
+ if (!buffer.length) {
3480
+ if (windowsPrivateFiles)
3481
+ return queueWindows(async () => {
3482
+ if (close)
3483
+ await closeWindowsFile(windowsFile);
3484
+ if (sinkError)
3485
+ throw sinkError;
3486
+ });
3487
+ return;
3408
3488
  }
3489
+ let file;
3409
3490
  try {
3410
- return JSON.parse(await readFile2(lockPath, "utf8"));
3411
- } catch (error) {
3412
- const code = error.code;
3413
- if (code !== "EISDIR")
3414
- throw error;
3415
- return JSON.parse(await readFile2(legacyOwnerPath, "utf8"));
3491
+ file = logFilePath();
3492
+ } catch {
3493
+ buffer = [];
3494
+ if (windowsPrivateFiles && close)
3495
+ return queueWindows(() => closeWindowsFile(windowsFile));
3496
+ return;
3497
+ }
3498
+ const text = buffer.join("");
3499
+ buffer = [];
3500
+ if (!file) {
3501
+ if (windowsPrivateFiles && close)
3502
+ return queueWindows(() => closeWindowsFile(windowsFile));
3503
+ return;
3416
3504
  }
3417
- }
3418
- async function writeOwner() {
3419
3505
  if (windowsPrivateFiles) {
3420
- const owner = await readOwner();
3421
- const remaining = Number(owner?.expiresAt) - now();
3422
- await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3423
- `, {
3424
- deadline: performance.now() + Math.max(0, remaining),
3425
- beforeRename: async () => {
3426
- const current = await readOwner();
3427
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
3428
- throw new LockOwnershipError({
3429
- target: options.path,
3430
- name: options.name
3431
- });
3432
- }
3506
+ return queueWindows(async () => {
3507
+ try {
3508
+ await flushWindowsFile(windowsFile, file, text);
3509
+ } finally {
3510
+ if (close)
3511
+ await closeWindowsFile(windowsFile);
3433
3512
  }
3434
3513
  });
3435
- return;
3436
3514
  }
3437
- const tempPath = `${lockPath}.${randomUUID5()}.tmp`;
3438
- let handle;
3439
- let created = false;
3440
3515
  try {
3441
- handle = await open2(tempPath, "wx", 384);
3442
- created = true;
3443
- await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3444
- `, "utf8");
3445
- await handle.chmod(384);
3446
- await handle.close();
3447
- handle = undefined;
3448
- const current = await readOwner();
3449
- if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
3450
- throw new LockOwnershipError({
3451
- target: options.path,
3452
- name: options.name
3453
- });
3454
- }
3455
- await rename3(tempPath, lockPath);
3456
- created = false;
3457
- } finally {
3458
- await handle?.close().catch(() => {});
3459
- if (created)
3460
- await rm2(tempPath, { force: true }).catch(() => {});
3461
- }
3462
- }
3463
- async function createLease() {
3464
- const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3465
- `;
3466
- if (windowsPrivateFiles)
3467
- await createPrivateBytes(lockPath, bytes);
3468
- else
3469
- await createExclusiveText(lockPath, bytes);
3516
+ rotateIfNeeded(file);
3517
+ if (existsSync(file))
3518
+ chmodPrivate(file);
3519
+ appendFileSync(file, text, { encoding: "utf8", mode: 384 });
3520
+ } catch {}
3470
3521
  }
3471
- async function leaseContention(error) {
3472
- const code = error.code;
3473
- if (code !== "EEXIST" && code !== "EISDIR")
3474
- return false;
3475
- if (windowsPrivateFiles) {
3476
- if (options.onStep)
3477
- await options.onStep("lease-contention-read-ready");
3522
+ function schedule() {
3523
+ if (!timer)
3524
+ timer = setTimeout(() => {
3525
+ timer = undefined;
3526
+ const flushed = flushLogs(false);
3527
+ if (flushed instanceof Promise)
3528
+ flushed.catch(() => {});
3529
+ }, 500);
3530
+ }
3531
+ function emit(channel, level, message, data) {
3532
+ if (logFileSource === undefined && captureSink === undefined)
3533
+ return;
3534
+ try {
3535
+ if (ORDER[level] > ORDER[configuredLevel()])
3536
+ return;
3537
+ const scrubbedMessage = redactor.redactStrings(message);
3538
+ let scrubbedData;
3478
3539
  try {
3479
- if (code === "EISDIR") {
3480
- await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3481
- await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
3482
- } else
3483
- await readOwner();
3484
- } catch (readError) {
3485
- if (readError.code !== "ENOENT")
3486
- throw readError;
3540
+ scrubbedData = redactor.redact(data);
3541
+ } catch {
3542
+ scrubbedData = "[unserializable]";
3487
3543
  }
3488
- }
3489
- return true;
3544
+ const line = `[${new Date().toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === undefined ? "" : safeSerialize(scrubbedData)) + `
3545
+ `;
3546
+ try {
3547
+ captureSink?.({
3548
+ channel,
3549
+ level,
3550
+ message: scrubbedMessage,
3551
+ data: scrubbedData
3552
+ });
3553
+ } catch {}
3554
+ if (logFileSource === undefined)
3555
+ return;
3556
+ buffer.push(line);
3557
+ if (buffer.length >= 50) {
3558
+ const flushed = flushLogs(false);
3559
+ if (flushed instanceof Promise)
3560
+ flushed.catch(() => {});
3561
+ } else
3562
+ schedule();
3563
+ } catch {}
3490
3564
  }
3491
- async function tryAcquire() {
3565
+ function createLogger(channel) {
3566
+ return {
3567
+ error: (m, d) => emit(channel, "error", m, d),
3568
+ warn: (m, d) => emit(channel, "warn", m, d),
3569
+ info: (m, d) => emit(channel, "info", m, d),
3570
+ debug: (m, d) => emit(channel, "debug", m, d),
3571
+ trace: (m, d) => emit(channel, "trace", m, d)
3572
+ };
3573
+ }
3574
+ function reset() {
3492
3575
  if (windowsPrivateFiles)
3493
- await ensurePrivateDirectory(dirname4(lockPath));
3576
+ queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {});
3577
+ sinkError = undefined;
3578
+ buffer = [];
3579
+ if (timer) {
3580
+ clearTimeout(timer);
3581
+ timer = undefined;
3582
+ }
3583
+ logFileSource = undefined;
3584
+ initLevelSource = undefined;
3585
+ runtimeLevel = undefined;
3586
+ redactor = createRedactor();
3587
+ captureSink = undefined;
3588
+ }
3589
+ if (options)
3590
+ configure(options);
3591
+ return { configure, createLogger, setLogLevel, flushLogs, reset };
3592
+ }
3593
+ var defaultEngine = createEngine();
3594
+ function createLogger(channel) {
3595
+ return defaultEngine.createLogger(channel);
3596
+ }
3597
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/lock-record.js
3598
+ import { resolve as resolve5 } from "node:path";
3599
+ class DisappearedLockRecordError extends Error {
3600
+ path;
3601
+ code = "ENOENT";
3602
+ constructor(path, cause) {
3603
+ super(`Lock record disappeared: ${path}`, { cause });
3604
+ this.path = path;
3605
+ }
3606
+ }
3607
+ function isWindowsAccessDeniedRead(error, paths) {
3608
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path) => resolve5(path) === error.path);
3609
+ }
3610
+ function isWindowsAccessDeniedCreate(error, paths, stage) {
3611
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path) => resolve5(path) === error.path);
3612
+ }
3613
+ async function readLockRecord(path, read) {
3614
+ try {
3615
+ return await read();
3616
+ } catch (error) {
3617
+ if (!isWindowsAccessDeniedRead(error, [path]))
3618
+ throw error;
3494
3619
  try {
3495
- await createLease();
3496
- return true;
3497
- } catch (error) {
3498
- const code = error.code;
3499
- if (await leaseContention(error))
3500
- return false;
3501
- if (code === "ENOENT") {
3502
- if (windowsPrivateFiles)
3503
- await ensurePrivateDirectory(dirname4(lockPath));
3504
- else
3505
- await mkdir2(dirname4(lockPath), { recursive: true });
3506
- try {
3507
- await createLease();
3508
- return true;
3509
- } catch (retryError) {
3510
- if (await leaseContention(retryError))
3511
- return false;
3512
- throw retryError;
3513
- }
3514
- }
3620
+ return await read();
3621
+ } catch (recheckError) {
3622
+ if (recheckError.code === "ENOENT")
3623
+ throw new DisappearedLockRecordError(path, error);
3515
3624
  throw error;
3516
3625
  }
3517
3626
  }
3518
- async function backoff() {
3519
- await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 4)));
3627
+ }
3628
+
3629
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
3630
+ import { join as join3, resolve as resolve6 } from "node:path";
3631
+ function lockPathFor(target, name) {
3632
+ return `${target}.${name}.lock`;
3633
+ }
3634
+
3635
+ class LockContentionError extends Error {
3636
+ details;
3637
+ constructor(details) {
3638
+ super(`Timed out acquiring ${details.name} lock for ${details.target}`);
3639
+ this.name = "LockContentionError";
3640
+ this.details = details;
3520
3641
  }
3521
- async function readLockState(notifyReady = true) {
3522
- if (notifyReady && options.onStep)
3523
- await options.onStep("lock-read-ready");
3524
- let owner;
3642
+ }
3643
+
3644
+ class LockOwnershipError extends Error {
3645
+ details;
3646
+ constructor(details) {
3647
+ super(`Lost ${details.name} lock for ${details.target}`);
3648
+ this.name = "LockOwnershipError";
3649
+ this.details = details;
3650
+ }
3651
+ }
3652
+ function isChangingLockRecord(error, target, name) {
3653
+ const path = resolve6(lockPathFor(target, name));
3654
+ const paths = [path, join3(path, "owner.json")];
3655
+ return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path], "create") || isWindowsAccessDeniedCreate(error, [`${path}.evicting`], "directory-create"));
3656
+ }
3657
+ async function withLock(target, options, fn) {
3658
+ const started = performance.now();
3659
+ let changingRecordError;
3660
+ for (;; ) {
3661
+ options.signal?.throwIfAborted();
3662
+ let lock;
3525
3663
  try {
3526
- owner = await readOwner();
3664
+ lock = await acquireRefreshFileLock({
3665
+ path: target,
3666
+ name: options.name,
3667
+ ttlMs: options.ttlMs,
3668
+ renew: options.renew ?? false,
3669
+ ...options.onStep ? { onStep: options.onStep } : {},
3670
+ ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
3671
+ });
3672
+ changingRecordError = undefined;
3527
3673
  } catch (error) {
3528
- if (error instanceof DisappearedLockRecordError)
3529
- return { status: "missing" };
3530
- if (windowsPrivateFiles && error.code !== "ENOENT")
3674
+ if (!isChangingLockRecord(error, target, options.name))
3531
3675
  throw error;
3676
+ lock = null;
3677
+ changingRecordError ??= error;
3532
3678
  }
3533
- const expiresAt = Number(owner?.expiresAt);
3534
- if (Number.isFinite(expiresAt) && expiresAt > now())
3535
- return { status: "live" };
3536
- if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
3537
- return {
3538
- status: "stale",
3539
- identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
3540
- };
3541
- }
3542
- try {
3543
- const current = await stat2(lockPath);
3544
- const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
3545
- if (legacyExpiry > now())
3546
- return { status: "live" };
3547
- return {
3548
- status: "stale",
3549
- identity: {
3550
- kind: "stat",
3551
- dev: current.dev,
3552
- ino: current.ino,
3553
- mtimeMs: current.mtimeMs,
3554
- expiresAt: legacyExpiry
3555
- }
3556
- };
3557
- } catch (error) {
3558
- if (error.code === "ENOENT") {
3559
- if (options.onStep)
3560
- await options.onStep("lock-missing");
3561
- return { status: "missing" };
3679
+ if (lock) {
3680
+ try {
3681
+ options.signal?.throwIfAborted();
3682
+ return await fn(lock);
3683
+ } finally {
3684
+ await lock.release(options.signal);
3562
3685
  }
3563
- throw error;
3564
3686
  }
3565
- }
3566
- function sameStaleLock(observed, current) {
3567
- if (current.status !== "stale")
3568
- return false;
3569
- const identity = current.identity;
3570
- if (observed.kind === "owner" && identity.kind === "owner") {
3571
- return observed.ownerId === identity.ownerId && observed.expiresAt === identity.expiresAt;
3687
+ const remaining = options.timeoutMs - (performance.now() - started);
3688
+ if (remaining <= 0) {
3689
+ if (changingRecordError)
3690
+ throw changingRecordError;
3691
+ throw new LockContentionError({
3692
+ target,
3693
+ name: options.name,
3694
+ timeoutMs: options.timeoutMs
3695
+ });
3572
3696
  }
3573
- return observed.kind === "stat" && identity.kind === "stat" && observed.dev === identity.dev && observed.ino === identity.ino && observed.mtimeMs === identity.mtimeMs && observed.expiresAt === identity.expiresAt;
3697
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25, Math.ceil(remaining))));
3574
3698
  }
3575
- async function ownsEvictionMarker() {
3699
+ }
3700
+
3701
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
3702
+ var leaseCreationTestHooks;
3703
+ async function createExclusiveText(path, text) {
3704
+ const tempPath = `${path}.${randomUUID5()}.tmp`;
3705
+ let handle;
3706
+ try {
3707
+ handle = await open3(tempPath, "wx", 384);
3576
3708
  try {
3577
- const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
3578
- return owner?.ownerId === evictOwnerId;
3709
+ if (leaseCreationTestHooks?.beforeWrite)
3710
+ await leaseCreationTestHooks.beforeWrite(tempPath);
3711
+ await handle.writeFile(text, "utf8");
3712
+ } finally {
3713
+ await handle.close();
3714
+ }
3715
+ try {
3716
+ if (leaseCreationTestHooks?.beforeLink)
3717
+ await leaseCreationTestHooks.beforeLink(tempPath, path);
3718
+ await link(tempPath, path);
3579
3719
  } catch (error) {
3580
- if (windowsPrivateFiles && error.code !== "ENOENT")
3720
+ const code = error.code;
3721
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EOPNOTSUPP" && code !== "EXDEV")
3581
3722
  throw error;
3582
- return false;
3723
+ await writeExclusiveText(path, text);
3583
3724
  }
3725
+ } finally {
3726
+ if (handle)
3727
+ await rm2(tempPath, { force: true }).catch(() => {});
3584
3728
  }
3585
- async function removeLeaseObject(path) {
3586
- if (windowsPrivateFiles)
3587
- await privateOperation(path, "remove", () => rm2(path, { recursive: true, force: true }));
3588
- else
3589
- await rm2(path, { recursive: true, force: true }).catch(() => {});
3590
- }
3591
- function isRetryableRemoval(error, path) {
3592
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path)
3593
- return false;
3594
- return isWindowsSharingViolation(error) || error.win32Code === undefined && error.reason === undefined && (error.code === "EBUSY" || error.code === "EPERM");
3595
- }
3596
- async function removeOwnedLeaseObject(path, stillOwned, deadline = performance.now() + EVICT_TTL + 1000) {
3597
- let original;
3598
- let delayMs = 5;
3599
- while (await stillOwned()) {
3600
- try {
3601
- await removeLeaseObject(path);
3602
- return;
3603
- } catch (error) {
3604
- if (!isRetryableRemoval(error, path))
3605
- throw error;
3606
- original ??= error;
3607
- }
3608
- const remainingMs = deadline - performance.now();
3609
- if (remainingMs <= 0)
3610
- throw original;
3611
- await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
3612
- if (performance.now() >= deadline)
3613
- throw original;
3614
- delayMs = Math.min(delayMs * 2, 50);
3615
- }
3729
+ }
3730
+ async function writeExclusiveText(path, text) {
3731
+ const handle = await open3(path, "wx", 384);
3732
+ let createdStat;
3733
+ try {
3734
+ createdStat = await handle.stat();
3735
+ } catch {
3736
+ createdStat = undefined;
3616
3737
  }
3617
- async function releaseEvictionMarker(deadline) {
3618
- let ownedDirectory;
3619
- await removeOwnedLeaseObject(evictPath, async () => {
3620
- if (!windowsPrivateFiles)
3621
- return ownsEvictionMarker();
3622
- const current = await lstat3(evictPath).catch((error) => {
3623
- if (error.code !== "ENOENT")
3624
- throw error;
3738
+ try {
3739
+ if (leaseCreationTestHooks?.beforeWrite)
3740
+ await leaseCreationTestHooks.beforeWrite(path);
3741
+ await handle.writeFile(text, "utf8");
3742
+ } catch (error) {
3743
+ try {
3744
+ const current = await lstat3(path).catch(() => {
3625
3745
  return;
3626
3746
  });
3627
- if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
3628
- return false;
3629
- if (await ownsEvictionMarker()) {
3630
- ownedDirectory = current;
3631
- return true;
3632
- }
3633
- if (!ownedDirectory)
3634
- return false;
3635
- try {
3636
- await stat2(evictOwnerPath);
3637
- return false;
3638
- } catch (error) {
3639
- if (error.code !== "ENOENT")
3640
- throw error;
3641
- return true;
3747
+ if (createdStat && current && current.dev === createdStat.dev && current.ino === createdStat.ino) {
3748
+ await rm2(path, { force: true }).catch(() => {});
3642
3749
  }
3643
- }, deadline);
3750
+ } catch {}
3751
+ throw error;
3752
+ } finally {
3753
+ await handle.close();
3644
3754
  }
3645
- async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
3646
- if (!created)
3647
- return false;
3648
- let stillOurs = false;
3755
+ }
3756
+ var STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
3757
+ var STAGING_SWEEP_MIN_AGE_MS = 10 * 60000;
3758
+ var STAGING_SWEEP_MAX_CANDIDATES = 256;
3759
+ var STAGING_SWEEP_MAX_BYTES = 4096;
3760
+ var sweptLockPaths = new Set;
3761
+ var pendingStagingSweeps = new Set;
3762
+ var stagingSweepTestHooks;
3763
+ function isStagingName(name, lockName) {
3764
+ const prefix = `${lockName}.`;
3765
+ const suffix = ".tmp";
3766
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
3767
+ return false;
3768
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
3769
+ }
3770
+ function sameStagingFile(a, b) {
3771
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
3772
+ }
3773
+ async function readStagedOwner(path) {
3774
+ const before = await lstat3(path);
3775
+ if (!before.isFile() || before.isSymbolicLink())
3776
+ return;
3777
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
3778
+ return;
3779
+ const handle = await open3(path, "r");
3780
+ let text;
3781
+ try {
3782
+ if (!sameStagingFile(before, await handle.stat()))
3783
+ return;
3784
+ text = await handle.readFile("utf8");
3785
+ } finally {
3786
+ await handle.close();
3787
+ }
3788
+ let record;
3789
+ try {
3790
+ record = JSON.parse(text);
3791
+ } catch {
3792
+ return;
3793
+ }
3794
+ if (!record || typeof record !== "object" || Array.isArray(record))
3795
+ return;
3796
+ const keys = Object.keys(record).sort();
3797
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
3798
+ return;
3799
+ const { ownerId, expiresAt } = record;
3800
+ if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
3801
+ return;
3802
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
3803
+ return;
3804
+ return { identity: before, expiresAt };
3805
+ }
3806
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
3807
+ const directory = dirname5(lockPath);
3808
+ const lockName = basename2(lockPath);
3809
+ const hooks = stagingSweepTestHooks;
3810
+ const names = await (hooks?.readdir ?? readdir)(directory);
3811
+ const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
3812
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
3813
+ for (const name of candidates) {
3814
+ const path = join4(directory, name);
3649
3815
  try {
3650
- await removeOwnedLeaseObject(evictPath, async () => {
3651
- stillOurs = false;
3652
- const st = await lstat3(evictPath).catch(() => {
3653
- return;
3654
- });
3655
- if (!st || !sameMarkerDirectory(created, st))
3656
- return false;
3657
- stillOurs = true;
3658
- try {
3659
- await stat2(evictOwnerPath);
3660
- return false;
3661
- } catch (error) {
3662
- return error.code === "ENOENT";
3663
- }
3664
- }, deadline);
3816
+ if (now() - (await lstat3(path)).mtimeMs < marginMs)
3817
+ continue;
3818
+ const staged = await readStagedOwner(path);
3819
+ if (!staged || !(staged.expiresAt < now() - marginMs))
3820
+ continue;
3821
+ if (hooks?.beforeUnlink)
3822
+ await hooks.beforeUnlink(path);
3823
+ const current = await readStagedOwner(path);
3824
+ if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
3825
+ continue;
3826
+ await (hooks?.unlink ?? unlink2)(path);
3665
3827
  } catch {}
3666
- return stillOurs;
3667
3828
  }
3668
- async function tryAcquireEvictionMarker(deadline) {
3669
- if (windowsPrivateFiles)
3670
- await createPrivateDirectoryExclusive(evictPath);
3671
- else
3672
- await mkdir2(evictPath);
3673
- let created;
3674
- try {
3675
- const st = await lstat3(evictPath);
3676
- created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
3677
- } catch {
3678
- created = undefined;
3679
- }
3829
+ }
3830
+ function startStagingSweep(lockPath, ttlMs, now) {
3831
+ if (sweptLockPaths.has(lockPath))
3832
+ return;
3833
+ sweptLockPaths.add(lockPath);
3834
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {});
3835
+ pendingStagingSweeps.add(sweep);
3836
+ sweep.finally(() => pendingStagingSweeps.delete(sweep));
3837
+ }
3838
+ var setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
3839
+ var clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
3840
+ function isLostMarkerRaceError(error) {
3841
+ const code = error?.code;
3842
+ return code === "ENOENT" || !windowsPrivateFiles && (code === "EINVAL" || code === "ENOTDIR");
3843
+ }
3844
+ var evictionMarkerTestHooks;
3845
+ function sameMarkerDirectory(created, current) {
3846
+ if (created.dev !== current.dev || created.ino !== current.ino)
3847
+ return false;
3848
+ if (created.ino === 0 && created.birthtimeMs !== current.birthtimeMs)
3849
+ return false;
3850
+ return true;
3851
+ }
3852
+ var OWNERLESS_MARKER_GRACE_MS = 1000;
3853
+ function acquireRefreshFileLock(options) {
3854
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
3855
+ }
3856
+ async function acquireRefreshFileLockWithClock(options) {
3857
+ const lockPath = lockPathFor(options.path, options.name);
3858
+ const legacyOwnerPath = join4(lockPath, "owner.json");
3859
+ const ownerId = randomUUID5();
3860
+ const now = options.now ?? Date.now;
3861
+ let renewTimer = null;
3862
+ let released = false;
3863
+ let releaseConfirmed = false;
3864
+ let loss;
3865
+ let resolveLoss;
3866
+ const lostPromise = new Promise((resolve) => {
3867
+ resolveLoss = resolve;
3868
+ });
3869
+ function notifyTimerStep(event) {
3680
3870
  try {
3681
- await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
3682
- const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
3683
- if (injected !== undefined)
3684
- throw injected;
3685
- const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
3686
- `;
3687
- if (windowsPrivateFiles)
3688
- await createPrivateBytes(evictOwnerPath, bytes);
3689
- else
3690
- await writeExclusiveText(evictOwnerPath, bytes);
3691
- } catch (error) {
3692
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
3693
- if (isLostMarkerRaceError(error) && !stillOurs)
3694
- return false;
3695
- try {
3696
- await releaseEvictionMarker(deadline);
3697
- } catch {}
3698
- throw error;
3699
- }
3700
- if (options.onStep)
3701
- await options.onStep("eviction-marker-acquired");
3702
- return true;
3871
+ const result = options.onRenewalTimer?.(event);
3872
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
3873
+ Promise.resolve(result).catch(() => {});
3874
+ }
3875
+ } catch {}
3703
3876
  }
3704
- async function recoverStaleEvictionMarker(deadline) {
3705
- let evictStat;
3706
- try {
3707
- evictStat = await stat2(evictPath);
3708
- } catch (error) {
3709
- if (error.code === "ENOENT")
3710
- return "missing";
3711
- throw error;
3712
- }
3877
+ function cancelRenewalTimer() {
3878
+ if (!renewTimer)
3879
+ return;
3880
+ clearRefreshLockRenewalTimeout(renewTimer);
3881
+ renewTimer = null;
3882
+ notifyTimerStep("cancelled");
3883
+ }
3884
+ function recordLoss(reason, owner) {
3885
+ if (loss || released)
3886
+ return;
3887
+ loss = Object.freeze({
3888
+ reason,
3889
+ expectedOwnerId: ownerId,
3890
+ ...typeof owner?.ownerId === "string" ? { observedOwnerId: owner.ownerId } : {},
3891
+ ...typeof owner?.expiresAt === "number" ? { observedExpiresAt: owner.expiresAt } : {}
3892
+ });
3893
+ cancelRenewalTimer();
3894
+ resolveLoss(loss);
3895
+ }
3896
+ let terminalIOError;
3897
+ let renewalInFlight = null;
3898
+ const evictPath = `${lockPath}.evicting`;
3899
+ const evictOwnerPath = join4(evictPath, "owner.json");
3900
+ const evictOwnerId = randomUUID5();
3901
+ const EVICT_TTL = 5000;
3902
+ const MAX_STEAL_ATTEMPTS = 8;
3903
+ function isChangingLockCreate(error) {
3904
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
3905
+ }
3906
+ async function readOwner() {
3713
3907
  if (windowsPrivateFiles) {
3714
3908
  try {
3715
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
3909
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
3716
3910
  } catch (error) {
3717
- if (error.code === "ENOENT")
3718
- return "missing";
3719
- throw error;
3911
+ if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
3912
+ throw error;
3913
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3914
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
3720
3915
  }
3721
3916
  }
3722
- if (evictStat.mtimeMs + EVICT_TTL > now()) {
3723
- let hasOwner = true;
3724
- try {
3725
- await stat2(evictOwnerPath);
3726
- } catch (error) {
3727
- if (error.code === "ENOENT")
3728
- hasOwner = false;
3729
- else
3730
- return "fresh";
3731
- }
3732
- if (hasOwner)
3733
- return "fresh";
3734
- if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
3735
- return "fresh";
3736
- }
3737
- if (options.onStep)
3738
- await options.onStep("stale-marker-stat");
3739
- const claimedPath = `${evictPath}.${randomUUID5()}`;
3740
3917
  try {
3741
- await rename3(evictPath, claimedPath);
3918
+ return JSON.parse(await readFile2(lockPath, "utf8"));
3742
3919
  } catch (error) {
3743
- if (error.code === "ENOENT")
3744
- return "missing";
3745
- throw error;
3920
+ const code = error.code;
3921
+ if (code !== "EISDIR")
3922
+ throw error;
3923
+ return JSON.parse(await readFile2(legacyOwnerPath, "utf8"));
3746
3924
  }
3747
- if (options.onStep)
3748
- await options.onStep("stale-marker-claimed");
3749
- const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : undefined;
3750
- await removeOwnedLeaseObject(claimedPath, async () => {
3751
- if (!claimedIdentity)
3752
- return true;
3753
- const current = await lstat3(claimedPath).catch((error) => {
3754
- if (error.code !== "ENOENT")
3755
- throw error;
3756
- return;
3925
+ }
3926
+ async function writeOwner() {
3927
+ if (windowsPrivateFiles) {
3928
+ const owner = await readOwner();
3929
+ const remaining = Number(owner?.expiresAt) - now();
3930
+ await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3931
+ `, {
3932
+ deadline: performance.now() + Math.max(0, remaining),
3933
+ beforeRename: async () => {
3934
+ const current = await readOwner();
3935
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
3936
+ throw new LockOwnershipError({
3937
+ target: options.path,
3938
+ name: options.name
3939
+ });
3940
+ }
3941
+ }
3757
3942
  });
3758
- return !!current && sameMarkerDirectory(claimedIdentity, current);
3759
- }, deadline);
3760
- return "recovered";
3943
+ return;
3944
+ }
3945
+ const tempPath = `${lockPath}.${randomUUID5()}.tmp`;
3946
+ let handle;
3947
+ let created = false;
3948
+ try {
3949
+ handle = await open3(tempPath, "wx", 384);
3950
+ created = true;
3951
+ await handle.writeFile(`${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3952
+ `, "utf8");
3953
+ await handle.chmod(384);
3954
+ await handle.close();
3955
+ handle = undefined;
3956
+ const current = await readOwner();
3957
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
3958
+ throw new LockOwnershipError({
3959
+ target: options.path,
3960
+ name: options.name
3961
+ });
3962
+ }
3963
+ await rename3(tempPath, lockPath);
3964
+ created = false;
3965
+ } finally {
3966
+ await handle?.close().catch(() => {});
3967
+ if (created)
3968
+ await rm2(tempPath, { force: true }).catch(() => {});
3969
+ }
3761
3970
  }
3762
- async function withEvictionMarker(action, deadline) {
3971
+ async function createLease() {
3972
+ const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
3973
+ `;
3974
+ if (windowsPrivateFiles)
3975
+ await createPrivateBytes(lockPath, bytes);
3976
+ else
3977
+ await createExclusiveText(lockPath, bytes);
3978
+ }
3979
+ async function leaseContention(error) {
3980
+ const code = error.code;
3981
+ if (code !== "EEXIST" && code !== "EISDIR")
3982
+ return false;
3983
+ if (windowsPrivateFiles) {
3984
+ if (options.onStep)
3985
+ await options.onStep("lease-contention-read-ready");
3986
+ try {
3987
+ if (code === "EISDIR") {
3988
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
3989
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
3990
+ } else
3991
+ await readOwner();
3992
+ } catch (readError) {
3993
+ if (readError.code !== "ENOENT")
3994
+ throw readError;
3995
+ }
3996
+ }
3997
+ return true;
3998
+ }
3999
+ async function tryAcquire() {
4000
+ if (windowsPrivateFiles)
4001
+ await ensurePrivateDirectory(dirname5(lockPath));
3763
4002
  try {
3764
- if (!await tryAcquireEvictionMarker(deadline))
3765
- return false;
4003
+ await createLease();
4004
+ return true;
3766
4005
  } catch (error) {
3767
- if (error.code === "EEXIST") {
3768
- if (windowsPrivateFiles) {
3769
- try {
3770
- await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
3771
- await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
3772
- } catch (ownerError) {
3773
- if (ownerError.code !== "ENOENT")
3774
- throw ownerError;
3775
- }
3776
- }
4006
+ const code = error.code;
4007
+ if (await leaseContention(error))
3777
4008
  return false;
4009
+ if (code === "ENOENT") {
4010
+ if (windowsPrivateFiles)
4011
+ await ensurePrivateDirectory(dirname5(lockPath));
4012
+ else
4013
+ await mkdir2(dirname5(lockPath), { recursive: true });
4014
+ try {
4015
+ await createLease();
4016
+ return true;
4017
+ } catch (retryError) {
4018
+ if (await leaseContention(retryError))
4019
+ return false;
4020
+ throw retryError;
4021
+ }
3778
4022
  }
3779
4023
  throw error;
3780
4024
  }
3781
- let actionFailed = false;
3782
- let actionError;
4025
+ }
4026
+ async function backoff() {
4027
+ await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 4)));
4028
+ }
4029
+ async function readLockState(notifyReady = true) {
4030
+ if (notifyReady && options.onStep)
4031
+ await options.onStep("lock-read-ready");
4032
+ let owner;
3783
4033
  try {
3784
- await action();
4034
+ owner = await readOwner();
3785
4035
  } catch (error) {
3786
- actionFailed = true;
3787
- actionError = error;
4036
+ if (error instanceof DisappearedLockRecordError)
4037
+ return { status: "missing" };
4038
+ if (windowsPrivateFiles && error.code !== "ENOENT")
4039
+ throw error;
4040
+ }
4041
+ const expiresAt = Number(owner?.expiresAt);
4042
+ if (Number.isFinite(expiresAt) && expiresAt > now())
4043
+ return { status: "live" };
4044
+ if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
4045
+ return {
4046
+ status: "stale",
4047
+ identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
4048
+ };
3788
4049
  }
3789
4050
  try {
3790
- await releaseEvictionMarker(deadline);
4051
+ const current = await stat2(lockPath);
4052
+ const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
4053
+ if (legacyExpiry > now())
4054
+ return { status: "live" };
4055
+ return {
4056
+ status: "stale",
4057
+ identity: {
4058
+ kind: "stat",
4059
+ dev: current.dev,
4060
+ ino: current.ino,
4061
+ mtimeMs: current.mtimeMs,
4062
+ expiresAt: legacyExpiry
4063
+ }
4064
+ };
3791
4065
  } catch (error) {
3792
- if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
3793
- lockPath,
3794
- legacyOwnerPath,
3795
- evictOwnerPath
3796
- ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
3797
- throw actionError;
4066
+ if (error.code === "ENOENT") {
4067
+ if (options.onStep)
4068
+ await options.onStep("lock-missing");
4069
+ return { status: "missing" };
4070
+ }
3798
4071
  throw error;
3799
4072
  }
3800
- if (actionFailed)
3801
- throw actionError;
3802
- return true;
3803
4073
  }
3804
- async function relinquishLockAfterMarkerLoss() {
3805
- for (let attempt = 0;attempt < MAX_STEAL_ATTEMPTS; attempt++) {
3806
- if (options.onStep)
3807
- await options.onStep("relinquish-read");
3808
- let owner;
3809
- try {
3810
- owner = await readOwner();
3811
- } catch (error) {
3812
- if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
3813
- throw error;
3814
- return;
3815
- }
3816
- if (owner?.ownerId !== ownerId)
3817
- return;
4074
+ function sameStaleLock(observed, current) {
4075
+ if (current.status !== "stale")
4076
+ return false;
4077
+ const identity = current.identity;
4078
+ if (observed.kind === "owner" && identity.kind === "owner") {
4079
+ return observed.ownerId === identity.ownerId && observed.expiresAt === identity.expiresAt;
4080
+ }
4081
+ return observed.kind === "stat" && identity.kind === "stat" && observed.dev === identity.dev && observed.ino === identity.ino && observed.mtimeMs === identity.mtimeMs && observed.expiresAt === identity.expiresAt;
4082
+ }
4083
+ async function ownsEvictionMarker() {
4084
+ try {
4085
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
4086
+ return owner?.ownerId === evictOwnerId;
4087
+ } catch (error) {
4088
+ if (windowsPrivateFiles && error.code !== "ENOENT")
4089
+ throw error;
4090
+ return false;
4091
+ }
4092
+ }
4093
+ async function removeLeaseObject(path) {
4094
+ if (windowsPrivateFiles)
4095
+ await privateOperation(path, "remove", () => rm2(path, { recursive: true, force: true }));
4096
+ else
4097
+ await rm2(path, { recursive: true, force: true }).catch(() => {});
4098
+ }
4099
+ function isRetryableRemoval(error, path) {
4100
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path)
4101
+ return false;
4102
+ return isWindowsSharingViolation(error) || error.win32Code === undefined && error.reason === undefined && (error.code === "EBUSY" || error.code === "EPERM");
4103
+ }
4104
+ async function removeOwnedLeaseObject(path, stillOwned, deadline = performance.now() + EVICT_TTL + 1000) {
4105
+ let original;
4106
+ let delayMs = 5;
4107
+ while (await stillOwned()) {
3818
4108
  try {
3819
- await rm2(lockPath, { recursive: true, force: true });
4109
+ await removeLeaseObject(path);
3820
4110
  return;
3821
4111
  } catch (error) {
3822
- if (windowsPrivateFiles)
4112
+ if (!isRetryableRemoval(error, path))
3823
4113
  throw error;
3824
- await backoff();
4114
+ original ??= error;
3825
4115
  }
4116
+ const remainingMs = deadline - performance.now();
4117
+ if (remainingMs <= 0)
4118
+ throw original;
4119
+ await new Promise((resolve) => setTimeout(resolve, Math.min(delayMs, remainingMs)));
4120
+ if (performance.now() >= deadline)
4121
+ throw original;
4122
+ delayMs = Math.min(delayMs * 2, 50);
3826
4123
  }
3827
4124
  }
3828
- function scheduleRenewal() {
3829
- if (!options.renew || released || loss)
3830
- return;
3831
- const intervalMs = options.renewIntervalMs ?? Math.max(1000, Math.floor(options.ttlMs / 3));
3832
- renewTimer = setRefreshLockRenewalTimeout(() => {
3833
- renewTimer = null;
3834
- const renewal = (async () => {
3835
- let shouldReschedule = !released;
3836
- try {
3837
- const markerAcquired = await withEvictionMarker(async () => {
3838
- const owner = await readOwner();
4125
+ async function releaseEvictionMarker(deadline) {
4126
+ let ownedDirectory;
4127
+ await removeOwnedLeaseObject(evictPath, async () => {
4128
+ if (!windowsPrivateFiles)
4129
+ return ownsEvictionMarker();
4130
+ const current = await lstat3(evictPath).catch((error) => {
4131
+ if (error.code !== "ENOENT")
4132
+ throw error;
4133
+ return;
4134
+ });
4135
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
4136
+ return false;
4137
+ if (await ownsEvictionMarker()) {
4138
+ ownedDirectory = current;
4139
+ return true;
4140
+ }
4141
+ if (!ownedDirectory)
4142
+ return false;
4143
+ try {
4144
+ await stat2(evictOwnerPath);
4145
+ return false;
4146
+ } catch (error) {
4147
+ if (error.code !== "ENOENT")
4148
+ throw error;
4149
+ return true;
4150
+ }
4151
+ }, deadline);
4152
+ }
4153
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
4154
+ if (!created)
4155
+ return false;
4156
+ let stillOurs = false;
4157
+ try {
4158
+ await removeOwnedLeaseObject(evictPath, async () => {
4159
+ stillOurs = false;
4160
+ const st = await lstat3(evictPath).catch(() => {
4161
+ return;
4162
+ });
4163
+ if (!st || !sameMarkerDirectory(created, st))
4164
+ return false;
4165
+ stillOurs = true;
4166
+ try {
4167
+ await stat2(evictOwnerPath);
4168
+ return false;
4169
+ } catch (error) {
4170
+ return error.code === "ENOENT";
4171
+ }
4172
+ }, deadline);
4173
+ } catch {}
4174
+ return stillOurs;
4175
+ }
4176
+ async function tryAcquireEvictionMarker(deadline) {
4177
+ if (windowsPrivateFiles)
4178
+ await createPrivateDirectoryExclusive(evictPath);
4179
+ else
4180
+ await mkdir2(evictPath);
4181
+ let created;
4182
+ try {
4183
+ const st = await lstat3(evictPath);
4184
+ created = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
4185
+ } catch {
4186
+ created = undefined;
4187
+ }
4188
+ try {
4189
+ await evictionMarkerTestHooks?.beforeOwnerWrite?.(evictPath, evictOwnerPath);
4190
+ const injected = await evictionMarkerTestHooks?.failOwnerWrite?.(evictPath, evictOwnerPath);
4191
+ if (injected !== undefined)
4192
+ throw injected;
4193
+ const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
4194
+ `;
4195
+ if (windowsPrivateFiles)
4196
+ await createPrivateBytes(evictOwnerPath, bytes);
4197
+ else
4198
+ await writeExclusiveText(evictOwnerPath, bytes);
4199
+ } catch (error) {
4200
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
4201
+ if (isLostMarkerRaceError(error) && !stillOurs)
4202
+ return false;
4203
+ try {
4204
+ await releaseEvictionMarker(deadline);
4205
+ } catch {}
4206
+ throw error;
4207
+ }
4208
+ if (options.onStep)
4209
+ await options.onStep("eviction-marker-acquired");
4210
+ return true;
4211
+ }
4212
+ async function recoverStaleEvictionMarker(deadline) {
4213
+ let evictStat;
4214
+ try {
4215
+ evictStat = await stat2(evictPath);
4216
+ } catch (error) {
4217
+ if (error.code === "ENOENT")
4218
+ return "missing";
4219
+ throw error;
4220
+ }
4221
+ if (windowsPrivateFiles) {
4222
+ try {
4223
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
4224
+ } catch (error) {
4225
+ if (error.code === "ENOENT")
4226
+ return "missing";
4227
+ throw error;
4228
+ }
4229
+ }
4230
+ if (evictStat.mtimeMs + EVICT_TTL > now()) {
4231
+ let hasOwner = true;
4232
+ try {
4233
+ await stat2(evictOwnerPath);
4234
+ } catch (error) {
4235
+ if (error.code === "ENOENT")
4236
+ hasOwner = false;
4237
+ else
4238
+ return "fresh";
4239
+ }
4240
+ if (hasOwner)
4241
+ return "fresh";
4242
+ if (evictStat.mtimeMs + OWNERLESS_MARKER_GRACE_MS > now())
4243
+ return "fresh";
4244
+ }
4245
+ if (options.onStep)
4246
+ await options.onStep("stale-marker-stat");
4247
+ const claimedPath = `${evictPath}.${randomUUID5()}`;
4248
+ try {
4249
+ await rename3(evictPath, claimedPath);
4250
+ } catch (error) {
4251
+ if (error.code === "ENOENT")
4252
+ return "missing";
4253
+ throw error;
4254
+ }
4255
+ if (options.onStep)
4256
+ await options.onStep("stale-marker-claimed");
4257
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : undefined;
4258
+ await removeOwnedLeaseObject(claimedPath, async () => {
4259
+ if (!claimedIdentity)
4260
+ return true;
4261
+ const current = await lstat3(claimedPath).catch((error) => {
4262
+ if (error.code !== "ENOENT")
4263
+ throw error;
4264
+ return;
4265
+ });
4266
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
4267
+ }, deadline);
4268
+ return "recovered";
4269
+ }
4270
+ async function withEvictionMarker(action, deadline) {
4271
+ try {
4272
+ if (!await tryAcquireEvictionMarker(deadline))
4273
+ return false;
4274
+ } catch (error) {
4275
+ if (error.code === "EEXIST") {
4276
+ if (windowsPrivateFiles) {
4277
+ try {
4278
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
4279
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
4280
+ } catch (ownerError) {
4281
+ if (ownerError.code !== "ENOENT")
4282
+ throw ownerError;
4283
+ }
4284
+ }
4285
+ return false;
4286
+ }
4287
+ throw error;
4288
+ }
4289
+ let actionFailed = false;
4290
+ let actionError;
4291
+ try {
4292
+ await action();
4293
+ } catch (error) {
4294
+ actionFailed = true;
4295
+ actionError = error;
4296
+ }
4297
+ try {
4298
+ await releaseEvictionMarker(deadline);
4299
+ } catch (error) {
4300
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
4301
+ lockPath,
4302
+ legacyOwnerPath,
4303
+ evictOwnerPath
4304
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
4305
+ throw actionError;
4306
+ throw error;
4307
+ }
4308
+ if (actionFailed)
4309
+ throw actionError;
4310
+ return true;
4311
+ }
4312
+ async function relinquishLockAfterMarkerLoss() {
4313
+ for (let attempt = 0;attempt < MAX_STEAL_ATTEMPTS; attempt++) {
4314
+ if (options.onStep)
4315
+ await options.onStep("relinquish-read");
4316
+ let owner;
4317
+ try {
4318
+ owner = await readOwner();
4319
+ } catch (error) {
4320
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
4321
+ throw error;
4322
+ return;
4323
+ }
4324
+ if (owner?.ownerId !== ownerId)
4325
+ return;
4326
+ try {
4327
+ await rm2(lockPath, { recursive: true, force: true });
4328
+ return;
4329
+ } catch (error) {
4330
+ if (windowsPrivateFiles)
4331
+ throw error;
4332
+ await backoff();
4333
+ }
4334
+ }
4335
+ }
4336
+ function scheduleRenewal() {
4337
+ if (!options.renew || released || loss)
4338
+ return;
4339
+ const intervalMs = options.renewIntervalMs ?? Math.max(1000, Math.floor(options.ttlMs / 3));
4340
+ renewTimer = setRefreshLockRenewalTimeout(() => {
4341
+ renewTimer = null;
4342
+ const renewal = (async () => {
4343
+ let shouldReschedule = !released;
4344
+ try {
4345
+ const markerAcquired = await withEvictionMarker(async () => {
4346
+ const owner = await readOwner();
3839
4347
  const currentNow = now();
3840
4348
  if (released || loss) {
3841
4349
  shouldReschedule = false;
@@ -4015,6 +4523,7 @@ async function acquireRefreshFileLockWithClock(options) {
4015
4523
  return null;
4016
4524
  }
4017
4525
  scheduleRenewal();
4526
+ startStagingSweep(lockPath, options.ttlMs, now);
4018
4527
  return {
4019
4528
  ownerId,
4020
4529
  whenLost: () => lostPromise,
@@ -4078,17 +4587,15 @@ async function acquireRefreshFileLockWithClock(options) {
4078
4587
  removalConfirmed = true;
4079
4588
  }, deadline);
4080
4589
  changingRecordError = undefined;
4081
- if (markerAcquired) {
4082
- if (windowsPrivateFiles && !removalConfirmed)
4083
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
4084
- code: "EIO"
4085
- });
4086
- releaseConfirmed = removalConfirmed;
4590
+ if (markerAcquired && removalConfirmed) {
4591
+ releaseConfirmed = true;
4087
4592
  return;
4088
4593
  }
4089
- if (signal?.aborted)
4090
- return;
4091
- await recoverStaleEvictionMarker(deadline);
4594
+ if (!markerAcquired) {
4595
+ if (signal?.aborted)
4596
+ return;
4597
+ await recoverStaleEvictionMarker(deadline);
4598
+ }
4092
4599
  } catch (error) {
4093
4600
  const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
4094
4601
  lockPath,
@@ -4118,10 +4625,13 @@ async function acquireRefreshFileLockWithClock(options) {
4118
4625
  throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
4119
4626
  code: "ETIMEDOUT"
4120
4627
  });
4628
+ createLogger("fs").warn("File lock release deadline expired", {
4629
+ lockPath
4630
+ });
4121
4631
  }
4122
4632
  };
4123
4633
  }
4124
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/map.js
4634
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/map.js
4125
4635
  var ALL_SCOPE = "all";
4126
4636
  var DEFAULT_REQUIRED_LABELS = Object.freeze([
4127
4637
  "primary"
@@ -4221,7 +4731,7 @@ function isQuotaMap(value) {
4221
4731
  return optional(value, "budget", isCreditBudgetEntry) && optional(value, "counters", isQuotaCounters) && optional(value, "credits", isQuotaCredits);
4222
4732
  }
4223
4733
 
4224
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/merge.js
4734
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/merge.js
4225
4735
  class QuotaCodecError extends TypeError {
4226
4736
  constructor(message) {
4227
4737
  super(message);
@@ -4302,450 +4812,116 @@ function mergeCounters(stored, observed) {
4302
4812
  }
4303
4813
  }
4304
4814
  return counters.size === 0 ? undefined : Object.fromEntries(counters);
4305
- }
4306
- function mergeCredits(stored, observed) {
4307
- if (observed === undefined)
4308
- return stored;
4309
- if (stored !== undefined && observed.checkedAt < stored.checkedAt) {
4310
- return stored;
4311
- }
4312
- return { ...observed };
4313
- }
4314
- function mergeQuotaObservation(stored, observation) {
4315
- const decoded = stored === undefined ? undefined : decodeQuotaMap(stored);
4316
- if (stored !== undefined && decoded === undefined) {
4317
- throw new QuotaCodecError("stored quota map is malformed");
4318
- }
4319
- if (!isQuotaObservation(observation)) {
4320
- throw new QuotaCodecError("quota observation is malformed");
4321
- }
4322
- const base = decoded ?? { limits: [] };
4323
- const at = observation.checkedAt;
4324
- const entries = new Map;
4325
- for (const entry of base.limits) {
4326
- entries.set(limitKey(entry.scope, entry.label), entry);
4327
- }
4328
- const applies = (key) => {
4329
- const existing = entries.get(key);
4330
- return existing === undefined || at >= entryTime(existing);
4331
- };
4332
- const carried = new Set;
4333
- for (const reading of observation.readings ?? []) {
4334
- const scope = reading.scope ?? ALL_SCOPE;
4335
- const key = limitKey(scope, reading.label);
4336
- carried.add(key);
4337
- if (!applies(key))
4338
- continue;
4339
- entries.set(key, {
4340
- scope,
4341
- label: reading.label,
4342
- kind: "reading",
4343
- checkedAt: at,
4344
- usedPercent: reading.usedPercent,
4345
- ...reading.resetsAt === undefined ? {} : { resetsAt: reading.resetsAt },
4346
- ...reading.windowMinutes === undefined ? {} : { windowMinutes: reading.windowMinutes }
4347
- });
4348
- }
4349
- for (const pair of observation.coverage ?? []) {
4350
- const scope = pair.scope ?? ALL_SCOPE;
4351
- const key = limitKey(scope, pair.label);
4352
- if (carried.has(key) || !applies(key))
4353
- continue;
4354
- const existing = entries.get(key);
4355
- entries.set(key, existing === undefined || existing.kind === "absent" ? { scope, label: pair.label, kind: "absent", checkedAt: at } : { scope, label: pair.label, kind: "retired", retiredAt: at });
4356
- }
4357
- const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
4358
- const budget = mergeBudget(base.budget, observation.budget, at);
4359
- const counters = mergeCounters(base.counters, observation.counters);
4360
- const credits = mergeCredits(base.credits, observation.credits);
4361
- return {
4362
- ...unknownKeys,
4363
- limits: [...entries.values()].sort(compareEntries),
4364
- ...budget === undefined ? {} : { budget },
4365
- ...counters === undefined ? {} : { counters },
4366
- ...credits === undefined ? {} : { credits }
4367
- };
4368
- }
4369
-
4370
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/codec.js
4371
- var quotaCodec = Object.freeze({
4372
- validate: isQuotaMap,
4373
- decode: decodeQuotaMap,
4374
- merge: mergeQuotaObservation
4375
- });
4376
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/format.js
4377
- var QUOTA_STALE_AFTER_MS = 15 * 60000;
4378
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/errors.js
4379
- class ClaustrumConsumerError extends Error {
4380
- kind;
4381
- constructor(kind, message) {
4382
- super(message);
4383
- this.name = "ClaustrumConsumerError";
4384
- this.kind = kind;
4385
- }
4386
- }
4387
-
4388
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
4389
- function matches(entry, credentialId, accountIdentity) {
4390
- if (entry.accountIdentity !== undefined && accountIdentity !== undefined)
4391
- return entry.accountIdentity === accountIdentity;
4392
- return entry.credentialId === credentialId;
4393
- }
4394
- function isDeclined(entries, credentialId, accountIdentity) {
4395
- return entries.some((entry) => matches(entry, credentialId, accountIdentity));
4396
- }
4397
- function declineAccount(entries, credentialId, accountIdentity) {
4398
- const entry = {
4399
- credentialId,
4400
- ...accountIdentity !== undefined && { accountIdentity }
4401
- };
4402
- return [
4403
- ...entries.filter((existing) => existing.credentialId !== credentialId || existing.accountIdentity !== accountIdentity),
4404
- entry
4405
- ];
4406
- }
4407
- function acceptAccount(entries, credentialIds, accountIdentity) {
4408
- return entries.filter((entry) => !credentialIds.some((id) => matches(entry, id, accountIdentity)));
4409
- }
4410
-
4411
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4412
- import { resolve as resolve7 } from "node:path";
4413
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/engine.js
4414
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
4415
- import { open as open3 } from "node:fs/promises";
4416
- import { dirname as dirname5, resolve as resolve6 } from "node:path";
4417
-
4418
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/redact.js
4419
- var SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
4420
- var TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
4421
- var MASK = "***REDACTED***";
4422
- var MAX_ERROR_DEPTH = 8;
4423
- function isError(value) {
4424
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
4425
- }
4426
- function createRedactor(options = {}) {
4427
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
4428
- function isSecretKey(key) {
4429
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
4430
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
4431
- }
4432
- function errorEntries(error) {
4433
- const fields = error;
4434
- const entries = [
4435
- ["name", error.name],
4436
- ["message", error.message],
4437
- ["stack", error.stack]
4438
- ];
4439
- for (const key of ["code", "status", "cause"])
4440
- if (fields[key] !== undefined)
4441
- entries.push([key, fields[key]]);
4442
- const listed = new Set(entries.map(([key]) => key));
4443
- for (const entry of Object.entries(error))
4444
- if (!listed.has(entry[0]))
4445
- entries.push(entry);
4446
- return entries;
4447
- }
4448
- function walk(value, keys, seen, errorDepth = 0) {
4449
- if (typeof value === "string") {
4450
- return patterns.reduce((text, pattern) => text.replace(pattern, MASK), value);
4451
- }
4452
- if (!value || typeof value !== "object")
4453
- return value;
4454
- if (seen.has(value))
4455
- return "[Circular]";
4456
- seen.add(value);
4457
- try {
4458
- if (Array.isArray(value))
4459
- return value.map((item) => walk(item, keys, seen, errorDepth));
4460
- const error = isError(value);
4461
- if (error && errorDepth >= MAX_ERROR_DEPTH)
4462
- return "[Truncated]";
4463
- const childDepth = error ? errorDepth + 1 : errorDepth;
4464
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
4465
- key,
4466
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
4467
- ]));
4468
- } finally {
4469
- seen.delete(value);
4470
- }
4471
- }
4472
- return {
4473
- redact: (value) => walk(value, true, new WeakSet),
4474
- redactStrings: (value) => walk(value, false, new WeakSet)
4475
- };
4476
- }
4477
- var defaultRedactor = createRedactor();
4478
- var redact = defaultRedactor.redact;
4479
- var redactStrings = defaultRedactor.redactStrings;
4480
-
4481
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/logger/engine.js
4482
- var ORDER = {
4483
- error: 0,
4484
- warn: 1,
4485
- info: 2,
4486
- debug: 3,
4487
- trace: 4
4488
- };
4489
- var MAX_BYTES = 5 * 1024 * 1024;
4490
- var ROTATE_KEEP = 3;
4491
- function chmodPrivate(path) {
4492
- try {
4493
- chmodSync(path, 384);
4494
- } catch {}
4495
- }
4496
- function rotateIfNeeded(f) {
4497
- try {
4498
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
4499
- return;
4500
- for (let i = ROTATE_KEEP - 1;i >= 1; i--) {
4501
- if (existsSync(`${f}.${i}`)) {
4502
- const rotated = `${f}.${i + 1}`;
4503
- renameSync(`${f}.${i}`, rotated);
4504
- chmodPrivate(rotated);
4505
- }
4506
- }
4507
- const rotated = `${f}.1`;
4508
- renameSync(f, rotated);
4509
- chmodPrivate(rotated);
4510
- } catch {}
4511
- }
4512
- async function closeWindowsFile(sink) {
4513
- const { file, handle } = sink;
4514
- sink.file = undefined;
4515
- sink.handle = undefined;
4516
- if (file && handle)
4517
- await privateOperation(file, "log-close", () => handle.close());
4518
- }
4519
- async function openWindowsFile(sink, file) {
4520
- await ensurePrivateDirectory(dirname5(file));
4521
- try {
4522
- await verifyPrivate(file, "file", true);
4523
- } catch (error) {
4524
- if (error.code !== "ENOENT")
4525
- throw error;
4526
- try {
4527
- await createPrivateBytes(file, "");
4528
- } catch (creationError) {
4529
- if (creationError.code !== "EEXIST")
4530
- throw creationError;
4531
- await verifyPrivate(file, "file", true);
4532
- }
4533
- }
4534
- sink.handle = await privateOperation(file, "log-open", () => open3(file, "a"));
4535
- sink.file = file;
4536
- return sink.handle;
4537
- }
4538
- async function flushWindowsFile(sink, file, text) {
4539
- file = resolve6(file);
4540
- try {
4541
- if (sink.file !== file)
4542
- await closeWindowsFile(sink);
4543
- let handle = sink.handle ?? await openWindowsFile(sink, file);
4544
- const info = await privateOperation(file, "log-stat", () => handle.stat());
4545
- if (info.size >= MAX_BYTES) {
4546
- await closeWindowsFile(sink);
4547
- for (let i = ROTATE_KEEP - 1;i >= 0; i--) {
4548
- const source = i === 0 ? file : `${file}.${i}`;
4549
- const target = `${file}.${i + 1}`;
4550
- try {
4551
- await verifyPrivate(source, "file", true);
4552
- } catch (error) {
4553
- if (error.code === "ENOENT")
4554
- continue;
4555
- throw error;
4556
- }
4557
- try {
4558
- await verifyPrivate(target, "file", true);
4559
- } catch (error) {
4560
- if (error.code !== "ENOENT")
4561
- throw error;
4562
- }
4563
- await replaceWindowsFile(source, target);
4564
- await verifyPrivate(target, "file");
4565
- }
4566
- handle = await openWindowsFile(sink, file);
4567
- }
4568
- await privateOperation(file, "log-append", () => handle.appendFile(text, "utf8"));
4569
- } catch (error) {
4570
- await closeWindowsFile(sink).catch(() => {});
4571
- throw error;
4572
- }
4573
- }
4574
- function safeSerialize(data) {
4575
- try {
4576
- return ` ${JSON.stringify(data)}`;
4577
- } catch {
4578
- return " [unserializable]";
4579
- }
4580
- }
4581
- function createEngine(options) {
4582
- let logFileSource;
4583
- let initLevelSource;
4584
- let runtimeLevel;
4585
- let redactor = createRedactor();
4586
- let captureSink;
4587
- let buffer = [];
4588
- let timer;
4589
- let orderedSink = Promise.resolve();
4590
- let sinkError;
4591
- const windowsFile = {};
4592
- function queueWindows(operation) {
4593
- const next = orderedSink.then(operation);
4594
- orderedSink = next.catch((error) => {
4595
- sinkError = error;
4596
- });
4597
- return next;
4598
- }
4599
- function configure(next) {
4600
- if (windowsPrivateFiles && next.file !== logFileSource)
4601
- queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {});
4602
- logFileSource = next.file;
4603
- initLevelSource = next.level;
4604
- redactor = createRedactor(next);
4605
- captureSink = next.captureSink;
4606
- }
4607
- function setLogLevel(l) {
4608
- if (l === undefined || l in ORDER)
4609
- runtimeLevel = l;
4610
- }
4611
- function logFilePath() {
4612
- if (logFileSource === undefined)
4613
- return;
4614
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
4615
- return resolved || undefined;
4815
+ }
4816
+ function mergeCredits(stored, observed) {
4817
+ if (observed === undefined)
4818
+ return stored;
4819
+ if (stored !== undefined && observed.checkedAt < stored.checkedAt) {
4820
+ return stored;
4616
4821
  }
4617
- function configuredLevel() {
4618
- if (runtimeLevel)
4619
- return runtimeLevel;
4620
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
4621
- if (floor && floor in ORDER)
4622
- return floor;
4623
- return "info";
4822
+ return { ...observed };
4823
+ }
4824
+ function mergeQuotaObservation(stored, observation) {
4825
+ const decoded = stored === undefined ? undefined : decodeQuotaMap(stored);
4826
+ if (stored !== undefined && decoded === undefined) {
4827
+ throw new QuotaCodecError("stored quota map is malformed");
4624
4828
  }
4625
- function flushLogs(close = true) {
4626
- if (timer) {
4627
- clearTimeout(timer);
4628
- timer = undefined;
4629
- }
4630
- if (!buffer.length) {
4631
- if (windowsPrivateFiles)
4632
- return queueWindows(async () => {
4633
- if (close)
4634
- await closeWindowsFile(windowsFile);
4635
- if (sinkError)
4636
- throw sinkError;
4637
- });
4638
- return;
4639
- }
4640
- let file;
4641
- try {
4642
- file = logFilePath();
4643
- } catch {
4644
- buffer = [];
4645
- if (windowsPrivateFiles && close)
4646
- return queueWindows(() => closeWindowsFile(windowsFile));
4647
- return;
4648
- }
4649
- const text = buffer.join("");
4650
- buffer = [];
4651
- if (!file) {
4652
- if (windowsPrivateFiles && close)
4653
- return queueWindows(() => closeWindowsFile(windowsFile));
4654
- return;
4655
- }
4656
- if (windowsPrivateFiles) {
4657
- return queueWindows(async () => {
4658
- try {
4659
- await flushWindowsFile(windowsFile, file, text);
4660
- } finally {
4661
- if (close)
4662
- await closeWindowsFile(windowsFile);
4663
- }
4664
- });
4665
- }
4666
- try {
4667
- rotateIfNeeded(file);
4668
- if (existsSync(file))
4669
- chmodPrivate(file);
4670
- appendFileSync(file, text, { encoding: "utf8", mode: 384 });
4671
- } catch {}
4829
+ if (!isQuotaObservation(observation)) {
4830
+ throw new QuotaCodecError("quota observation is malformed");
4672
4831
  }
4673
- function schedule() {
4674
- if (!timer)
4675
- timer = setTimeout(() => {
4676
- timer = undefined;
4677
- const flushed = flushLogs(false);
4678
- if (flushed instanceof Promise)
4679
- flushed.catch(() => {});
4680
- }, 500);
4832
+ const base = decoded ?? { limits: [] };
4833
+ const at = observation.checkedAt;
4834
+ const entries = new Map;
4835
+ for (const entry of base.limits) {
4836
+ entries.set(limitKey(entry.scope, entry.label), entry);
4681
4837
  }
4682
- function emit(channel, level, message, data) {
4683
- if (logFileSource === undefined && captureSink === undefined)
4684
- return;
4685
- try {
4686
- if (ORDER[level] > ORDER[configuredLevel()])
4687
- return;
4688
- const scrubbedMessage = redactor.redactStrings(message);
4689
- let scrubbedData;
4690
- try {
4691
- scrubbedData = redactor.redact(data);
4692
- } catch {
4693
- scrubbedData = "[unserializable]";
4694
- }
4695
- const line = `[${new Date().toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === undefined ? "" : safeSerialize(scrubbedData)) + `
4696
- `;
4697
- try {
4698
- captureSink?.({
4699
- channel,
4700
- level,
4701
- message: scrubbedMessage,
4702
- data: scrubbedData
4703
- });
4704
- } catch {}
4705
- if (logFileSource === undefined)
4706
- return;
4707
- buffer.push(line);
4708
- if (buffer.length >= 50) {
4709
- const flushed = flushLogs(false);
4710
- if (flushed instanceof Promise)
4711
- flushed.catch(() => {});
4712
- } else
4713
- schedule();
4714
- } catch {}
4838
+ const applies = (key) => {
4839
+ const existing = entries.get(key);
4840
+ return existing === undefined || at >= entryTime(existing);
4841
+ };
4842
+ const carried = new Set;
4843
+ for (const reading of observation.readings ?? []) {
4844
+ const scope = reading.scope ?? ALL_SCOPE;
4845
+ const key = limitKey(scope, reading.label);
4846
+ carried.add(key);
4847
+ if (!applies(key))
4848
+ continue;
4849
+ entries.set(key, {
4850
+ scope,
4851
+ label: reading.label,
4852
+ kind: "reading",
4853
+ checkedAt: at,
4854
+ usedPercent: reading.usedPercent,
4855
+ ...reading.resetsAt === undefined ? {} : { resetsAt: reading.resetsAt },
4856
+ ...reading.windowMinutes === undefined ? {} : { windowMinutes: reading.windowMinutes }
4857
+ });
4715
4858
  }
4716
- function createLogger(channel) {
4717
- return {
4718
- error: (m, d) => emit(channel, "error", m, d),
4719
- warn: (m, d) => emit(channel, "warn", m, d),
4720
- info: (m, d) => emit(channel, "info", m, d),
4721
- debug: (m, d) => emit(channel, "debug", m, d),
4722
- trace: (m, d) => emit(channel, "trace", m, d)
4723
- };
4859
+ for (const pair of observation.coverage ?? []) {
4860
+ const scope = pair.scope ?? ALL_SCOPE;
4861
+ const key = limitKey(scope, pair.label);
4862
+ if (carried.has(key) || !applies(key))
4863
+ continue;
4864
+ const existing = entries.get(key);
4865
+ entries.set(key, existing === undefined || existing.kind === "absent" ? { scope, label: pair.label, kind: "absent", checkedAt: at } : { scope, label: pair.label, kind: "retired", retiredAt: at });
4724
4866
  }
4725
- function reset() {
4726
- if (windowsPrivateFiles)
4727
- queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {});
4728
- sinkError = undefined;
4729
- buffer = [];
4730
- if (timer) {
4731
- clearTimeout(timer);
4732
- timer = undefined;
4733
- }
4734
- logFileSource = undefined;
4735
- initLevelSource = undefined;
4736
- runtimeLevel = undefined;
4737
- redactor = createRedactor();
4738
- captureSink = undefined;
4867
+ const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
4868
+ const budget = mergeBudget(base.budget, observation.budget, at);
4869
+ const counters = mergeCounters(base.counters, observation.counters);
4870
+ const credits = mergeCredits(base.credits, observation.credits);
4871
+ return {
4872
+ ...unknownKeys,
4873
+ limits: [...entries.values()].sort(compareEntries),
4874
+ ...budget === undefined ? {} : { budget },
4875
+ ...counters === undefined ? {} : { counters },
4876
+ ...credits === undefined ? {} : { credits }
4877
+ };
4878
+ }
4879
+
4880
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/codec.js
4881
+ var quotaCodec = Object.freeze({
4882
+ validate: isQuotaMap,
4883
+ decode: decodeQuotaMap,
4884
+ merge: mergeQuotaObservation
4885
+ });
4886
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/format.js
4887
+ var QUOTA_STALE_AFTER_MS = 15 * 60000;
4888
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/errors.js
4889
+ class ClaustrumConsumerError extends Error {
4890
+ kind;
4891
+ constructor(kind, message) {
4892
+ super(message);
4893
+ this.name = "ClaustrumConsumerError";
4894
+ this.kind = kind;
4739
4895
  }
4740
- if (options)
4741
- configure(options);
4742
- return { configure, createLogger, setLogLevel, flushLogs, reset };
4743
4896
  }
4744
- var defaultEngine = createEngine();
4745
- function createLogger(channel) {
4746
- return defaultEngine.createLogger(channel);
4897
+
4898
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
4899
+ function matches(entry, credentialId, accountIdentity) {
4900
+ if (entry.accountIdentity !== undefined && accountIdentity !== undefined)
4901
+ return entry.accountIdentity === accountIdentity;
4902
+ return entry.credentialId === credentialId;
4903
+ }
4904
+ function isDeclined(entries, credentialId, accountIdentity) {
4905
+ return entries.some((entry) => matches(entry, credentialId, accountIdentity));
4906
+ }
4907
+ function declineAccount(entries, credentialId, accountIdentity) {
4908
+ const entry = {
4909
+ credentialId,
4910
+ ...accountIdentity !== undefined && { accountIdentity }
4911
+ };
4912
+ return [
4913
+ ...entries.filter((existing) => existing.credentialId !== credentialId || existing.accountIdentity !== accountIdentity),
4914
+ entry
4915
+ ];
4747
4916
  }
4748
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
4917
+ function acceptAccount(entries, credentialIds, accountIdentity) {
4918
+ return entries.filter((entry) => !credentialIds.some((id) => matches(entry, id, accountIdentity)));
4919
+ }
4920
+
4921
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4922
+ import { resolve as resolve7 } from "node:path";
4923
+
4924
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
4749
4925
  var QUOTA_COMMIT_INTERVAL_MS = 30000;
4750
4926
  var quotaCommitTimer = {
4751
4927
  now: () => performance.now(),
@@ -4758,7 +4934,7 @@ var quotaCommitTimer = {
4758
4934
  }
4759
4935
  };
4760
4936
 
4761
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/quota/pending.js
4937
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/quota/pending.js
4762
4938
  function quotaFields(publication, witness = "") {
4763
4939
  const result = new Map;
4764
4940
  const { observation } = publication;
@@ -4806,7 +4982,7 @@ function quotaFields(publication, witness = "") {
4806
4982
  return result;
4807
4983
  }
4808
4984
 
4809
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4985
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
4810
4986
  var writers = new Map;
4811
4987
  var logger = createLogger("claustrum");
4812
4988
  var COALESCE_MS = 100;
@@ -4991,7 +5167,7 @@ async function drainVaultQuota(path, timeoutMs = 1000) {
4991
5167
  }
4992
5168
  }
4993
5169
 
4994
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
5170
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
4995
5171
  function vaultRosterSeed(roster) {
4996
5172
  return {
4997
5173
  declined: roster.declined.map((entry) => ({ ...entry })),
@@ -5537,7 +5713,7 @@ async function refreshVaultRoster(options) {
5537
5713
  }
5538
5714
  }
5539
5715
 
5540
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
5716
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/limits/vault-adapter.js
5541
5717
  function bindingsOf(namespace, roster) {
5542
5718
  return (roster?.rows ?? []).map((row) => ({
5543
5719
  account: {
@@ -5632,7 +5808,7 @@ async function createVaultLimitsAdapter(options) {
5632
5808
  await read();
5633
5809
  return adapter;
5634
5810
  }
5635
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/redaction/index.js
5811
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/redaction/index.js
5636
5812
  import { types } from "node:util";
5637
5813
  var escapedErrorField = /"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i;
5638
5814
  var escapedErrorType = /"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;
@@ -6487,7 +6663,69 @@ function limitRefusal(decision, host, now) {
6487
6663
  throw new Error("claustrum-auth: unsupported limit refusal");
6488
6664
  return localLimitRefusal(new Response(wire.body, { status: wire.status, headers: wire.headers }), wire.hostRetry);
6489
6665
  }
6490
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/routing/sticky.js
6666
+
6667
+ // ../core/src/routing.ts
6668
+ var routingDeclinedText = "Thalamus routing declined this request, so it was not sent.";
6669
+ var routingNoAnswerText = "Thalamus routing did not answer, so this API key request was not sent.";
6670
+ function routingRefusalText(code) {
6671
+ if (code === "routing-declined")
6672
+ return routingDeclinedText;
6673
+ if (code === "routing-no-answer")
6674
+ return routingNoAnswerText;
6675
+ return;
6676
+ }
6677
+ function hasVaultRoutingAccessor() {
6678
+ try {
6679
+ return typeof Reflect.get(globalThis, Symbol.for("cortexkit.routing")) === "function";
6680
+ } catch {
6681
+ return false;
6682
+ }
6683
+ }
6684
+ async function selectRoutedKey(consumer, provider, modelId, sessionId, excluded = new Set, nextRoute) {
6685
+ if (!hasVaultRoutingAccessor())
6686
+ return;
6687
+ const routes = consumer.routingRows();
6688
+ const roster = consumer.snapshot?.()?.rows ?? [];
6689
+ const next = nextRoute ?? routes.find((row) => !excluded.has(row.id))?.id;
6690
+ if (roster.find((row) => row.routeId === next)?.credentialType === "oauth")
6691
+ return;
6692
+ if (!sessionId)
6693
+ throw new ClaustrumAuthError("routing-no-answer");
6694
+ const enabled = new Set(routes.map((row) => row.id));
6695
+ const candidates = roster.filter((row) => enabled.has(row.routeId) && !excluded.has(row.routeId) && row.credentialType === "api_key").map((row) => ({
6696
+ routeId: row.routeId,
6697
+ credentialId: row.credentialId,
6698
+ accountId: row.accountIdentity ?? row.credentialId
6699
+ }));
6700
+ const answer = await askRouting({
6701
+ sessionId,
6702
+ provider,
6703
+ modelId,
6704
+ candidates,
6705
+ refusals: true
6706
+ });
6707
+ if (!answer)
6708
+ throw new ClaustrumAuthError("routing-no-answer");
6709
+ if ("refused" in answer)
6710
+ throw new ClaustrumAuthError("routing-declined");
6711
+ return answer.candidate;
6712
+ }
6713
+ async function reportRoutedBalance(key, sessionId, service, status, body) {
6714
+ if (!key || !sessionId || status !== 402)
6715
+ return;
6716
+ const text = await body().catch(() => "");
6717
+ if (!isBalanceFailure(service, text))
6718
+ return;
6719
+ const providerCode = service === "openrouter" ? "openrouter_credits" : "http_402";
6720
+ reportRouting({
6721
+ sessionId,
6722
+ accountId: key.accountId,
6723
+ credentialId: key.credentialId,
6724
+ outcome: "credential_refused",
6725
+ providerCode
6726
+ });
6727
+ }
6728
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/routing/sticky.js
6491
6729
  var QUOTA_STALENESS_MS = 15 * 60000;
6492
6730
  var MIN_RESET_HOURS = 1 / 60;
6493
6731
  // ../core/src/serving.ts
@@ -6559,6 +6797,7 @@ function createFetch(options) {
6559
6797
  cache: request.cache
6560
6798
  };
6561
6799
  const tried = new Set;
6800
+ let routedAttempt = false;
6562
6801
  const rejected = new Set;
6563
6802
  const secrets = [];
6564
6803
  let redirectBilling;
@@ -6619,10 +6858,26 @@ function createFetch(options) {
6619
6858
  try {
6620
6859
  for (;; ) {
6621
6860
  signal.throwIfAborted();
6861
+ if (routedAttempt && pending && !pending.parsed)
6862
+ return await redactResponse(pending.response, secrets);
6622
6863
  const rows = await candidates();
6864
+ const ownDecision = pending ? decide("after-limit", rows, pending.response.status, pending.account, pending.parsed) : decide("pre-send", rows);
6865
+ if (ownDecision.action === "pass" && pending)
6866
+ return await redactResponse(pending.response, secrets);
6867
+ const nextRoute = ownDecision.action === "reroute" ? ownDecision.account.accountId : rows.find((row) => row.admitted && row.placementEligible)?.account.accountId;
6868
+ const routed = await selectRoutedKey(options.consumer, options.routing?.provider ?? options.entry.service, options.routing?.modelId ?? "", options.routing?.sessionId, new Set([...tried, ...rejected]), nextRoute);
6869
+ routedAttempt = routed !== undefined;
6870
+ const routedId = routed?.routeId;
6623
6871
  if (!pending && !rows.some((row) => row.admitted))
6624
6872
  throw new ClaustrumAuthError("no-vault-account");
6625
- const initial = pending ? decide("after-limit", rows, pending.response.status, pending.account, pending.parsed) : decide("pre-send", rows);
6873
+ const initial = routed ? {
6874
+ action: "reroute",
6875
+ account: rows.find((row) => row.account.accountId === routedId)?.account ?? {
6876
+ namespace: "claustrum-auth:routing",
6877
+ accountId: routed.routeId,
6878
+ incarnation: "routing"
6879
+ }
6880
+ } : ownDecision;
6626
6881
  if (initial.action === "pass" && pending)
6627
6882
  return await redactResponse(pending.response, secrets);
6628
6883
  if (initial.action === "refuse") {
@@ -6632,11 +6887,11 @@ function createFetch(options) {
6632
6887
  if (initial.action !== "reroute")
6633
6888
  throw new Error("claustrum-auth: unsupported limit action");
6634
6889
  const route = initial.account.accountId;
6635
- if (limits && !await limits.beforeDispatch(route)) {
6890
+ if (!routed && limits && !await limits.beforeDispatch(route)) {
6636
6891
  rejected.add(route);
6637
6892
  continue;
6638
6893
  }
6639
- if (limits) {
6894
+ if (!routed && limits) {
6640
6895
  if (!(await candidates()).find((row) => row.account.accountId === route)?.ready)
6641
6896
  continue;
6642
6897
  }
@@ -6653,7 +6908,9 @@ function createFetch(options) {
6653
6908
  for (;; ) {
6654
6909
  signal.throwIfAborted();
6655
6910
  checkOrigin(target, options.entry);
6656
- response = await options.consumer.send(route, async (receipt, dispatchSignal) => {
6911
+ const dispatch = async (receipt, dispatchSignal) => {
6912
+ if (routed && receipt.credentialId !== routed.credentialId)
6913
+ throw new ClaustrumAuthError("routing-no-answer");
6657
6914
  secrets.push(receipt.accessToken);
6658
6915
  const draft = placeReceipt(target, headers, options.entry, receipt);
6659
6916
  const dispatchHeaders = new Headers(draft.headers);
@@ -6685,7 +6942,11 @@ function createFetch(options) {
6685
6942
  failedBilling?.end(false, false);
6686
6943
  throw error;
6687
6944
  }
6688
- }, { site: "claustrum-auth", signal });
6945
+ };
6946
+ response = await options.consumer.send(route, dispatch, {
6947
+ site: "claustrum-auth",
6948
+ signal
6949
+ });
6689
6950
  signal.throwIfAborted();
6690
6951
  const location = response.headers.get("location");
6691
6952
  if (![301, 302, 303, 307, 308].includes(response.status) || !location)
@@ -6713,8 +6974,12 @@ function createFetch(options) {
6713
6974
  redirectBilling = undefined;
6714
6975
  response = observeBillingResponse(billing, response);
6715
6976
  }
6977
+ const account = observation?.binding.account ?? {
6978
+ ...initial.account,
6979
+ accountId: route
6980
+ };
6716
6981
  const parsed = await limitFromReply({
6717
- account: observation?.binding.account ?? initial.account,
6982
+ account,
6718
6983
  service: options.entry.service,
6719
6984
  status: response.status,
6720
6985
  headers: response.headers,
@@ -6722,6 +6987,7 @@ function createFetch(options) {
6722
6987
  now: now()
6723
6988
  });
6724
6989
  const balance402 = parsed?.kind === "payment-balance";
6990
+ await reportRoutedBalance(routed, options.routing?.sessionId, options.entry.service, response.status, () => response.clone().text());
6725
6991
  if (response.ok || response.status === 402 && !balance402) {
6726
6992
  if (limits && observation) {
6727
6993
  if (hasBalanceRule(options.entry.service) && observation.paymentProbe)
@@ -6745,7 +7011,7 @@ function createFetch(options) {
6745
7011
  }
6746
7012
  pending = {
6747
7013
  response,
6748
- account: observation?.binding.account ?? initial.account,
7014
+ account,
6749
7015
  parsed
6750
7016
  };
6751
7017
  }
@@ -6757,10 +7023,10 @@ function createFetch(options) {
6757
7023
  }
6758
7024
  };
6759
7025
  }
6760
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7026
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
6761
7027
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
6762
7028
 
6763
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/availability.js
7029
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/availability.js
6764
7030
  import { ClaustrumCredentialError } from "@cortexkit/claustrum-client";
6765
7031
  import { SocketClosedError, SocketTimeoutError, SubcCallError } from "@cortexkit/subc-client";
6766
7032
  var VAULT_FAILURE_CLASSES = Object.freeze({
@@ -6854,12 +7120,12 @@ function classifyVaultFailure(error) {
6854
7120
  return VAULT_FAILURE_CLASSES[code];
6855
7121
  }
6856
7122
 
6857
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
7123
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
6858
7124
  import { resolve as resolve9 } from "node:path";
6859
7125
  import { storeIdentity } from "@cortexkit/claustrum-client";
6860
7126
  import { SubcClient } from "@cortexkit/subc-client";
6861
7127
 
6862
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/watch.js
7128
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/watch.js
6863
7129
  var SAFETY_POLL_MS = 5 * 60000;
6864
7130
  var WATCH_RETRY_MS = 5 * 60000;
6865
7131
  var RESUBSCRIBE_BACKOFF_MS = 1000;
@@ -7055,7 +7321,7 @@ class ScopedRosterWatch {
7055
7321
  }
7056
7322
  }
7057
7323
 
7058
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
7324
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
7059
7325
  function insulaUsageTransport(options) {
7060
7326
  const identity = options.identity ?? storeIdentity(options.projectRoot ?? process.cwd(), options.storagePath ?? process.cwd());
7061
7327
  return {
@@ -7411,10 +7677,10 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
7411
7677
  };
7412
7678
  }
7413
7679
 
7414
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7680
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7415
7681
  import { ClaustrumCredentialError as ClaustrumCredentialError6 } from "@cortexkit/claustrum-client";
7416
7682
 
7417
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/util/any-signal.js
7683
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/util/any-signal.js
7418
7684
  function combineAbortSignals(signals) {
7419
7685
  const controller = new AbortController;
7420
7686
  const listeners = [];
@@ -7451,17 +7717,17 @@ function combineAbortSignals(signals) {
7451
7717
  return { signal: controller.signal, dispose };
7452
7718
  }
7453
7719
 
7454
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
7720
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
7455
7721
  import { channel } from "node:diagnostics_channel";
7456
7722
  import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
7457
7723
 
7458
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7724
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7459
7725
  import { constants as fsConstants } from "node:fs";
7460
- import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat4, unlink as unlink2 } from "node:fs/promises";
7461
- import { basename as basename2, dirname as dirname6, extname, isAbsolute, join as join5, resolve as resolve10 } from "node:path";
7726
+ import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat4, unlink as unlink3 } from "node:fs/promises";
7727
+ import { basename as basename3, dirname as dirname6, extname, isAbsolute, join as join5, resolve as resolve10 } from "node:path";
7462
7728
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
7463
7729
 
7464
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/host.js
7730
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/host.js
7465
7731
  import { ClaustrumCredentialError as ClaustrumCredentialError2 } from "@cortexkit/claustrum-client";
7466
7732
  var VAULT_HOST_STATUS = "Served by Thalamus";
7467
7733
  var hostClients = new WeakSet;
@@ -7555,7 +7821,7 @@ function connectVaultHost(pluginId) {
7555
7821
  throw new ClaustrumUnreachableError("host-accessor-missing");
7556
7822
  }
7557
7823
 
7558
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7824
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
7559
7825
  var ENROLLMENT_SCHEMA = 1;
7560
7826
  var ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
7561
7827
  var TOKEN_RE = /^[0-9a-f]{64}$/;
@@ -7572,9 +7838,28 @@ var TERMINAL_ENROLLMENT_CODES = new Set([
7572
7838
  var RETRYABLE_ENROLLMENT_CODES = new Set([
7573
7839
  "pending_queue_full"
7574
7840
  ]);
7841
+ function validEnrollmentRequestedGrants(grants) {
7842
+ return Array.isArray(grants) && grants.length >= 1 && grants.length <= 4 && Array.from(grants).every((grant) => {
7843
+ if (!isRecord4(grant) || Object.keys(grant).length !== 2 || grant.operation !== "read" && grant.operation !== "list" || !isRecord4(grant.selector))
7844
+ return false;
7845
+ const keys = Object.keys(grant.selector);
7846
+ const key = keys[0];
7847
+ return keys.length === 1 && (key === "category" || key === "exact") && typeof grant.selector[key] === "string" && grant.selector[key].trim().length > 0;
7848
+ });
7849
+ }
7850
+ function grantProposal(state) {
7851
+ return {
7852
+ ...state.requestedGrants !== undefined && {
7853
+ requestedGrants: state.requestedGrants
7854
+ },
7855
+ ...state.requestedGrantsStatus !== undefined && {
7856
+ requestedGrantsStatus: state.requestedGrantsStatus
7857
+ }
7858
+ };
7859
+ }
7575
7860
  function getClaustrumEnrollmentPaths(tokenPath) {
7576
7861
  const extension = extname(tokenPath) || ".json";
7577
- const stem = basename2(tokenPath, extname(tokenPath));
7862
+ const stem = basename3(tokenPath, extname(tokenPath));
7578
7863
  return {
7579
7864
  statePath: join5(dirname6(tokenPath), `${stem}-state${extension}`),
7580
7865
  tokenPath
@@ -7604,6 +7889,7 @@ function decodeEnrollmentState(value) {
7604
7889
  throw invalidState();
7605
7890
  }
7606
7891
  if (value.phase === "pending") {
7892
+ const grants = decodeGrantProposal(value);
7607
7893
  if (!TOKEN_RE.test(String(value.requestSecret ?? "")) || value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length === 0) || !validTimestamp(value.createdAt) || !validTimestamp(value.updatedAt)) {
7608
7894
  throw invalidState();
7609
7895
  }
@@ -7616,10 +7902,12 @@ function decodeEnrollmentState(value) {
7616
7902
  requestId: value.requestId
7617
7903
  },
7618
7904
  createdAt: value.createdAt,
7619
- updatedAt: value.updatedAt
7905
+ updatedAt: value.updatedAt,
7906
+ ...grants
7620
7907
  };
7621
7908
  }
7622
7909
  if (value.phase === "approved") {
7910
+ const grants = decodeGrantProposal(value);
7623
7911
  if (value.approvedName !== undefined && (typeof value.approvedName !== "string" || value.approvedName.length === 0) || !validGeneration(value.tokenGeneration) || !validTimestamp(value.updatedAt)) {
7624
7912
  throw invalidState();
7625
7913
  }
@@ -7631,7 +7919,8 @@ function decodeEnrollmentState(value) {
7631
7919
  approvedName: value.approvedName
7632
7920
  },
7633
7921
  tokenGeneration: value.tokenGeneration,
7634
- updatedAt: value.updatedAt
7922
+ updatedAt: value.updatedAt,
7923
+ ...grants
7635
7924
  };
7636
7925
  }
7637
7926
  if (value.phase === "denied" || value.phase === "blocked") {
@@ -7650,6 +7939,11 @@ function decodeEnrollmentState(value) {
7650
7939
  }
7651
7940
  throw invalidState();
7652
7941
  }
7942
+ function decodeGrantProposal(value) {
7943
+ if (value.requestedGrants !== undefined && !validEnrollmentRequestedGrants(value.requestedGrants) || value.requestedGrantsStatus !== undefined && (value.requestedGrants === undefined || value.requestedGrantsStatus !== "sent" && value.requestedGrantsStatus !== "dropped"))
7944
+ return {};
7945
+ return grantProposal(value);
7946
+ }
7653
7947
  function decodeTokenFile(value) {
7654
7948
  if (!isRecord4(value) || !TOKEN_RE.test(String(value.token ?? "")) || !validGeneration(value.token_generation)) {
7655
7949
  throw new ClaustrumConsumerError("invalid-token", "invalid Claustrum enrollment token file");
@@ -7762,7 +8056,8 @@ async function readEnrollmentStatus(paths, proposedName) {
7762
8056
  ...state?.phase === "approved" && state.approvedName !== undefined && {
7763
8057
  approvedName: state.approvedName
7764
8058
  },
7765
- tokenGeneration: token.token_generation
8059
+ tokenGeneration: token.token_generation,
8060
+ ...state && (state.phase === "approved" || state.phase === "pending") && grantProposal(state)
7766
8061
  }
7767
8062
  };
7768
8063
  }
@@ -7821,7 +8116,8 @@ function statusFromState(state) {
7821
8116
  return {
7822
8117
  state: "pending",
7823
8118
  proposedName: state.proposedName,
7824
- ...state.requestId !== undefined && { requestId: state.requestId }
8119
+ ...state.requestId !== undefined && { requestId: state.requestId },
8120
+ ...grantProposal(state)
7825
8121
  };
7826
8122
  }
7827
8123
  if (state.phase === "approved") {
@@ -7831,7 +8127,8 @@ function statusFromState(state) {
7831
8127
  ...state.approvedName !== undefined && {
7832
8128
  approvedName: state.approvedName
7833
8129
  },
7834
- tokenGeneration: state.tokenGeneration
8130
+ tokenGeneration: state.tokenGeneration,
8131
+ ...grantProposal(state)
7835
8132
  };
7836
8133
  }
7837
8134
  if (state.phase === "denied")
@@ -7843,10 +8140,10 @@ function statusFromState(state) {
7843
8140
  };
7844
8141
  }
7845
8142
 
7846
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
8143
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
7847
8144
  var CUSTODY_PLACEHOLDER_PREFIX = "claustrum-tombstone:v1:";
7848
8145
 
7849
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/shutdown.js
8146
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/shutdown.js
7850
8147
  function shutdownWarning(logger, shutdown) {
7851
8148
  let warned = false;
7852
8149
  return (pendingOperations) => {
@@ -7884,7 +8181,7 @@ async function drainShutdown(pending, onTimeout) {
7884
8181
  }
7885
8182
  }
7886
8183
 
7887
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/usage.js
8184
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/usage.js
7888
8185
  import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
7889
8186
  function plain(value) {
7890
8187
  return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
@@ -8012,7 +8309,7 @@ class ScopedUsageReporter {
8012
8309
  }
8013
8310
  }
8014
8311
 
8015
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8312
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8016
8313
  function isScopedCredentialRotation(served, current) {
8017
8314
  return current !== undefined && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
8018
8315
  }
@@ -8718,7 +9015,7 @@ class ClaustrumScopedCustody {
8718
9015
  }
8719
9016
  }
8720
9017
 
8721
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.js
9018
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.js
8722
9019
  var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
8723
9020
  function unreachableConnect() {
8724
9021
  return new ClaustrumUnreachableError;
@@ -9429,10 +9726,10 @@ class ClaustrumConsumer {
9429
9726
  await this.#disposing;
9430
9727
  }
9431
9728
  }
9432
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
9729
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
9433
9730
  import { createHash as createHash3 } from "node:crypto";
9434
9731
  import { channel as channel2 } from "node:diagnostics_channel";
9435
- import { readdir, stat as stat5 } from "node:fs/promises";
9732
+ import { readdir as readdir2, stat as stat5 } from "node:fs/promises";
9436
9733
  import { dirname as dirname7, join as join6, resolve as resolve11 } from "node:path";
9437
9734
  var sharedRosters = new Map;
9438
9735
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -10080,7 +10377,7 @@ class ClaustrumDiscoveryHub {
10080
10377
  const name = `${entry.provider}.json`;
10081
10378
  const candidates = [join6(this.#generationDirectory, name)];
10082
10379
  try {
10083
- for (const key of await readdir(this.#generationDirectory))
10380
+ for (const key of await readdir2(this.#generationDirectory))
10084
10381
  if (key !== this.#key && FINGERPRINT.test(key))
10085
10382
  candidates.push(join6(this.#generationDirectory, key, name));
10086
10383
  } catch {}
@@ -10277,7 +10574,7 @@ class ClaustrumDiscoveryHub {
10277
10574
  }
10278
10575
  }
10279
10576
 
10280
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
10577
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/claustrum/index.js
10281
10578
  var SCOPED_CONNECT_TIMEOUT_MS = 1e4;
10282
10579
  async function connectClaustrumScopedClient(options) {
10283
10580
  const { connectTimeoutMs, ...client } = options;
@@ -10305,12 +10602,12 @@ async function connectClaustrumScopedClient(options) {
10305
10602
  }
10306
10603
  // ../core/src/menu.ts
10307
10604
  import { Readable, Writable } from "node:stream";
10308
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/hooks.js
10605
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/hooks.js
10309
10606
  import { AsyncLocalStorage } from "node:async_hooks";
10310
10607
  var insideHook = new AsyncLocalStorage;
10311
10608
  var insideCodec = new AsyncLocalStorage;
10312
10609
 
10313
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
10610
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
10314
10611
  var POOL_LOCK_DEFAULTS = Object.freeze({
10315
10612
  ttlMs: 1e4,
10316
10613
  timeoutMs: 15000,
@@ -10318,15 +10615,15 @@ var POOL_LOCK_DEFAULTS = Object.freeze({
10318
10615
  renew: true
10319
10616
  });
10320
10617
 
10321
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/schema.js
10618
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/schema.js
10322
10619
  var POOL_KEY = "commonAuthPool";
10323
10620
  var REFRESH_STAMP_TOLERANCE_MS = 5 * 60000;
10324
10621
  var UNSAFE_IDS = new Set(["__proto__", "constructor", "prototype"]);
10325
10622
 
10326
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/provider-state.js
10623
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/provider-state.js
10327
10624
  var DECLINE_TRANSITION = Symbol.for("@cortexkit/common-auth/store/decline-transition");
10328
10625
 
10329
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/settings.js
10626
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/settings.js
10330
10627
  var POOL_OWNED_KEYS = Object.freeze([
10331
10628
  "version",
10332
10629
  "accounts",
@@ -10334,9 +10631,9 @@ var POOL_OWNED_KEYS = Object.freeze([
10334
10631
  ]);
10335
10632
  var settingsCache = new FileReadCache;
10336
10633
 
10337
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/store/pool.js
10634
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/store/pool.js
10338
10635
  var processMemory = new Map;
10339
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/ansi.js
10636
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/auth-menu/ansi.js
10340
10637
  var ANSI = {
10341
10638
  hide: "\x1B[?25l",
10342
10639
  show: "\x1B[?25h",
@@ -10418,7 +10715,7 @@ function truncateAnsi(input, maxVisibleChars) {
10418
10715
  return output.includes("\x1B[") ? `${output}${ANSI.reset}${suffix}` : output + suffix;
10419
10716
  }
10420
10717
 
10421
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/terminal.js
10718
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/auth-menu/terminal.js
10422
10719
  function processTerminal() {
10423
10720
  return {
10424
10721
  input: process.stdin,
@@ -10434,7 +10731,7 @@ function printLine(terminal, line = "") {
10434
10731
  `);
10435
10732
  }
10436
10733
 
10437
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/select.js
10734
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/auth-menu/select.js
10438
10735
  var ESCAPE_TIMEOUT_MS = 50;
10439
10736
  function colorCode(color) {
10440
10737
  if (color === "red")
@@ -10572,7 +10869,7 @@ async function select(terminal, items, options) {
10572
10869
  });
10573
10870
  }
10574
10871
 
10575
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/confirm.js
10872
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/auth-menu/confirm.js
10576
10873
  async function confirm(terminal, message, defaultYes = false) {
10577
10874
  if (!isInteractive(terminal))
10578
10875
  return false;
@@ -10586,7 +10883,7 @@ async function confirm(terminal, message, defaultYes = false) {
10586
10883
  return await select(terminal, items, { message }) ?? false;
10587
10884
  }
10588
10885
 
10589
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/auth-menu/menu.js
10886
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/auth-menu/menu.js
10590
10887
  function menuContext(terminal) {
10591
10888
  const interactive = isInteractive(terminal);
10592
10889
  return {
@@ -11176,14 +11473,14 @@ async function startupStep(step, action) {
11176
11473
  import path2 from "node:path";
11177
11474
  import { resolveClaustrumConnectionPath } from "@cortexkit/claustrum-client";
11178
11475
 
11179
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11476
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11180
11477
  import { createHash as createHash4 } from "node:crypto";
11181
11478
  import { constants } from "node:fs";
11182
- import { lstat as lstat4, mkdir as mkdir5, open as open5, unlink as unlink3 } from "node:fs/promises";
11479
+ import { lstat as lstat4, mkdir as mkdir5, open as open5, unlink as unlink4 } from "node:fs/promises";
11183
11480
  import { dirname as dirname8, resolve as resolve12 } from "node:path";
11184
11481
  import { setTimeout as sleep } from "node:timers/promises";
11185
11482
 
11186
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
11483
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
11187
11484
  import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
11188
11485
  import { mkdir as mkdir4, rmdir, stat as stat6, utimes } from "node:fs/promises";
11189
11486
  var STALE = 30000;
@@ -11375,7 +11672,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11375
11672
  };
11376
11673
  }
11377
11674
 
11378
- // ../../node_modules/.bun/@cortexkit+common-auth@0.43.0+7766d853e58521fa/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11675
+ // ../../node_modules/.bun/@cortexkit+common-auth@0.47.0+d48131f39628582b/node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
11379
11676
  class PiSlotError extends Error {
11380
11677
  code;
11381
11678
  constructor(code) {
@@ -11658,7 +11955,7 @@ function createPiSlot(options, onStep, hooks) {
11658
11955
  }
11659
11956
  async function deleteStash(assertLock) {
11660
11957
  assertLock();
11661
- await unlink3(stashPath);
11958
+ await unlink4(stashPath);
11662
11959
  await syncDir(dirname8(stashPath));
11663
11960
  onStep?.("stash-deleted");
11664
11961
  }
@@ -11773,6 +12070,9 @@ class FlagStore {
11773
12070
  var refused = "Request refused locally by the claustrum-auth plugin:";
11774
12071
  var nothingSent = "Nothing was sent.";
11775
12072
  function refusalText(code, provider, entry) {
12073
+ const routing = routingRefusalText(code);
12074
+ if (routing)
12075
+ return routing;
11776
12076
  switch (code) {
11777
12077
  case "placement-refused":
11778
12078
  return `${refused} this model's request carries the ${provider} vault placeholder outside the Authorization header, and vault keys are only sent as Authorization: Bearer. ${nothingSent}`;
@@ -12007,11 +12307,17 @@ class PiRuntime {
12007
12307
  stream(served, model, context, options) {
12008
12308
  if (options?.apiKey !== served.placeholder)
12009
12309
  return streamSimple(model, context, options);
12310
+ const sessionId = options.sessionId ?? this.#ctx.sessionManager?.getSessionId();
12311
+ const routing = {
12312
+ sessionId,
12313
+ provider: model.provider,
12314
+ modelId: model.id
12315
+ };
12010
12316
  const inner = options.fetch ?? globalThis.fetch;
12011
12317
  if (!hasBillingAccessor())
12012
12318
  return streamSimple(model, context, {
12013
12319
  ...options,
12014
- fetch: this.ownedFetch(served, inner)
12320
+ fetch: this.ownedFetch(served, inner, undefined, routing)
12015
12321
  });
12016
12322
  let current;
12017
12323
  let attempt = 0;
@@ -12019,16 +12325,16 @@ class PiRuntime {
12019
12325
  ...options,
12020
12326
  fetch: this.ownedFetch(served, inner, (receipt) => {
12021
12327
  current?.end();
12022
- if (!hasBillingAccessor())
12328
+ if (!sessionId || !hasBillingAccessor())
12023
12329
  return;
12024
- current = new BillingAttempt(served.entry, model.provider, options.sessionId ?? this.#ctx.sessionManager.getSessionId(), "primary", model.id, receipt, ++attempt, true);
12330
+ current = new BillingAttempt(served.entry, model.provider, sessionId, "primary", model.id, receipt, ++attempt, true);
12025
12331
  return current;
12026
- })
12332
+ }, routing)
12027
12333
  });
12028
12334
  stream.result().then((message) => current?.piEnd(message.responseId, message.stopReason), () => current?.end());
12029
12335
  return stream;
12030
12336
  }
12031
- ownedFetch(served, inner, billing) {
12337
+ ownedFetch(served, inner, billing, routing) {
12032
12338
  const serve = createFetch({
12033
12339
  entry: served.entry,
12034
12340
  placeholder: served.placeholder,
@@ -12037,7 +12343,8 @@ class PiRuntime {
12037
12343
  fetch: inner,
12038
12344
  rateLimitMarks: served.marks,
12039
12345
  limits: () => this.#core.limits(served.provider),
12040
- billing
12346
+ billing,
12347
+ routing
12041
12348
  });
12042
12349
  return async (input, init) => {
12043
12350
  try {