@cortexkit/anthropic-auth-core 2.14.1 → 2.15.1

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.
@@ -453,6 +453,17 @@ export declare function quotaRefusalTiming(input: {
453
453
  retryAfterSeconds: number | undefined;
454
454
  limitName?: string;
455
455
  };
456
+ /**
457
+ * The retry delay a quota refusal advertises: the time until `resetAt` (five
458
+ * minutes when it is unknown), capped by the longest same-account wait and the
459
+ * host's retry cap. The "0" wait setting advertises no retry at all.
460
+ */
461
+ export declare function quotaRefusalRetryAfterSeconds(input: {
462
+ resetAt: number | undefined;
463
+ storage?: AccountSettingsReaderInput | null;
464
+ sessionTtlMs?: number;
465
+ now?: number;
466
+ }): number | undefined;
456
467
  /** Compatibility accessor for callers that need only the capped retry delay. */
457
468
  export declare function killswitchRetryAfterSeconds(mainQuota: OAuthQuotaSnapshot | undefined, fallbackAccounts: Array<QuotaResetEvidence>, now: number, scopedModelId?: string, options?: {
458
469
  storage?: AccountStorage | null;
package/dist/cch.d.ts CHANGED
@@ -30,6 +30,8 @@ export declare class ClaudeCodeFirstUserTextTracker {
30
30
  constructor(limit?: number);
31
31
  resolve(sessionId: string, messages: Message[], pin?: boolean): string;
32
32
  has(sessionId: string): boolean;
33
+ /** Read a head's billing-text pin without changing its lifetime or LRU order. */
34
+ peek(sessionId: string): string | undefined;
33
35
  clear(): void;
34
36
  }
35
37
  /**
package/dist/index.d.ts CHANGED
@@ -115,6 +115,7 @@ export * from './session-cache-activity.ts';
115
115
  export * from './session-cache-policy.ts';
116
116
  export * from './settings-definition.ts';
117
117
  export * from './settings-mode.ts';
118
+ export * from './settings-mode-status.ts';
118
119
  export * from './settings-move-fence.ts';
119
120
  export * from './settings-move-map.ts';
120
121
  export * from './settings-move-run.ts';
package/dist/index.js CHANGED
@@ -13093,15 +13093,26 @@ function quotaRefusalTiming(input) {
13093
13093
  }
13094
13094
  const earliest = resetTimes.sort((a, b) => a.resetAt - b.resetAt)[0];
13095
13095
  const resetAt = earliest?.resetAt;
13096
- const wait = getMaxSameAccountWait(input.storage ?? null);
13097
- const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
13098
- const capMs = clampHostRetryMs(wait === "max" ? ttlMs : Number(wait) * 60000);
13099
13096
  return {
13100
13097
  resetAt,
13101
13098
  ...earliest ? { limitName: earliest.limitName } : {},
13102
- retryAfterSeconds: wait === "0" ? undefined : Math.max(1, Math.ceil(Math.min(resetAt === undefined ? 300000 : resetAt - now, capMs) / 1000))
13099
+ retryAfterSeconds: quotaRefusalRetryAfterSeconds({
13100
+ resetAt,
13101
+ storage: input.storage,
13102
+ sessionTtlMs: input.sessionTtlMs,
13103
+ now
13104
+ })
13103
13105
  };
13104
13106
  }
13107
+ function quotaRefusalRetryAfterSeconds(input) {
13108
+ const now = input.now ?? Date.now();
13109
+ const wait = getMaxSameAccountWait(input.storage ?? null);
13110
+ if (wait === "0")
13111
+ return;
13112
+ const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
13113
+ const capMs = clampHostRetryMs(wait === "max" ? ttlMs : Number(wait) * 60000);
13114
+ return Math.max(1, Math.ceil(Math.min(input.resetAt === undefined ? 300000 : input.resetAt - now, capMs) / 1000));
13115
+ }
13105
13116
  function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId, options) {
13106
13117
  return quotaRefusalTiming({
13107
13118
  ...options,
@@ -16712,6 +16723,9 @@ class ClaudeCodeFirstUserTextTracker {
16712
16723
  has(sessionId) {
16713
16724
  return this.#values.has(sessionId);
16714
16725
  }
16726
+ peek(sessionId) {
16727
+ return this.#values.get(sessionId);
16728
+ }
16715
16729
  clear() {
16716
16730
  this.#values.clear();
16717
16731
  }
@@ -29685,16 +29699,13 @@ function decideStickyQuotaFailure(input) {
29685
29699
  const scope = input.unconfirmedRetry;
29686
29700
  return scope && !scope.counter.retain(scope.sessionId, scope.turnId, scope.accountId) ? { action: "migrate", reason: "unconfirmed-retry-limit" } : { action: "retain", reason };
29687
29701
  };
29688
- let reading2 = knownQuota(input.quota);
29689
- const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, now) : undefined;
29690
- if (reading2 && input.responseHeaders) {
29691
- reading2 = { ...reading2 };
29692
- for (const key of ["five_hour", "seven_day", "scoped"]) {
29693
- if (quotaFieldSource(reading2, key) === "headers")
29694
- delete reading2[key];
29695
- }
29696
- }
29697
- const quota2 = reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
29702
+ const quota2 = stickyQuotaEvidence({
29703
+ quota: input.quota,
29704
+ responseHeaders: input.responseHeaders,
29705
+ modelId: input.modelId,
29706
+ now,
29707
+ storedHeaderReadings: true
29708
+ });
29698
29709
  if (!quota2)
29699
29710
  return retain("unknown");
29700
29711
  let blocking;
@@ -29723,6 +29734,60 @@ function decideStickyQuotaFailure(input) {
29723
29734
  }
29724
29735
  return { action: "migrate", reason: blocking.reason };
29725
29736
  }
29737
+ function stickyQuotaEvidence(input) {
29738
+ let reading2 = knownQuota(input.quota);
29739
+ const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, input.now) : undefined;
29740
+ if (reading2 && (input.responseHeaders || !input.storedHeaderReadings)) {
29741
+ reading2 = { ...reading2 };
29742
+ for (const key of ["five_hour", "seven_day", "scoped"]) {
29743
+ if (quotaFieldSource(reading2, key) === "headers")
29744
+ delete reading2[key];
29745
+ }
29746
+ }
29747
+ return reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
29748
+ }
29749
+ function stickyQuotaExhaustionInForce(input) {
29750
+ const now = input.now ?? Date.now();
29751
+ const quota2 = stickyQuotaEvidence({
29752
+ quota: input.quota,
29753
+ responseHeaders: input.responseHeaders,
29754
+ modelId: input.modelId,
29755
+ now,
29756
+ storedHeaderReadings: false
29757
+ });
29758
+ if (!quota2)
29759
+ return;
29760
+ const scoped = getScopedQuotaWindowForModel(quota2, input.modelId);
29761
+ let blocking;
29762
+ for (const [reason, limitName, window2] of [
29763
+ ["model-scoped", `${scoped?.modelName ?? "Model"} weekly`, scoped],
29764
+ ["seven-day", "weekly", quota2.seven_day],
29765
+ ["five-hour", "5-hour", quota2.five_hour]
29766
+ ]) {
29767
+ if (!window2 || !Number.isFinite(window2.remainingPercent) || window2.remainingPercent > 0)
29768
+ continue;
29769
+ const resetAt = window2.resetsAt ? Date.parse(window2.resetsAt) : NaN;
29770
+ if (!Number.isFinite(resetAt) || resetAt <= now)
29771
+ continue;
29772
+ if (!blocking || resetAt > blocking.resetAt)
29773
+ blocking = { resetAt, reason, limitName };
29774
+ }
29775
+ return blocking;
29776
+ }
29777
+ function createExhaustedNoRouteResponse(input) {
29778
+ const now = input.now ?? Date.now();
29779
+ const earliest = [...input.exhausted].sort((a, b) => a.resetAt - b.resetAt)[0];
29780
+ return createQuotaRefusalResponse("Claude reports every account that could take this request as out of quota.", {
29781
+ resetAt: earliest?.resetAt,
29782
+ ...earliest ? { limitName: earliest.limitName } : {},
29783
+ retryAfterSeconds: quotaRefusalRetryAfterSeconds({
29784
+ resetAt: earliest?.resetAt,
29785
+ storage: input.storage,
29786
+ sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId),
29787
+ now
29788
+ })
29789
+ }, now);
29790
+ }
29726
29791
  function stickyRetainRetryHeaders(upstream, now = Date.now()) {
29727
29792
  const headers = new Headers(upstream);
29728
29793
  let seconds = 60;
@@ -38938,6 +39003,70 @@ function isSettingsImportPending(service) {
38938
39003
  return service ? pendingImports.has(service) : false;
38939
39004
  }
38940
39005
 
39006
+ // src/settings-mode-status.ts
39007
+ function settingsMoveBlockerIdentity(blocker) {
39008
+ switch (blocker.kind) {
39009
+ case "registration":
39010
+ return { kind: blocker.kind };
39011
+ case "floor":
39012
+ return { kind: blocker.kind, release: blocker.release };
39013
+ case "settings-holder":
39014
+ return {
39015
+ kind: blocker.kind,
39016
+ path: blocker.holderFile,
39017
+ pid: blocker.pid,
39018
+ release: blocker.release
39019
+ };
39020
+ case "holder-file":
39021
+ return { kind: blocker.kind, path: blocker.holderFile };
39022
+ case "pre-n-artifact":
39023
+ return { kind: blocker.kind, path: blocker.artifact, pid: blocker.pid };
39024
+ case "artifact-scan":
39025
+ return { kind: blocker.kind, path: blocker.path };
39026
+ }
39027
+ }
39028
+ var blockerWords = {
39029
+ registration: "this process to register as a settings holder",
39030
+ floor: "a valid minimum plugin release",
39031
+ "holder-file": "a settings holder registry that could not be read",
39032
+ "settings-holder": "an older or unrecognized settings holder",
39033
+ "pre-n-artifact": "an older plugin process that may still be running",
39034
+ "artifact-scan": "an old plugin file that could not be read (the log names it)"
39035
+ };
39036
+ var outcomeWords = {
39037
+ "fence-closed": "a safe settings-holder check",
39038
+ "separate-install": "this separate install, which keeps its own settings",
39039
+ "source-unavailable": "the old settings stores to become readable and ready",
39040
+ "import-refused": "this host's protection settings to be safely imported",
39041
+ "import-unknown": "this host's old protection settings to become readable",
39042
+ "import-pending": "the shared file to become usable so this host's protection settings can be checked",
39043
+ "authority-refused": "account enrollment or credential migration to allow settings access",
39044
+ "startup-failed": "settings startup to succeed",
39045
+ busy: "another settings operation to finish; restart to try the move again",
39046
+ failed: "the settings move to succeed; restart to try again",
39047
+ "aborted-target-appeared": "a settings file published by another process to be checked",
39048
+ "done-already": "the existing settings file to be checked",
39049
+ "marker-present": "the previously moved settings file to be checked",
39050
+ moved: "the moved settings file to be opened"
39051
+ };
39052
+ var sourceWords = {
39053
+ "custody-unreadable": "account enrollment to become readable",
39054
+ "seeding-failed": "the vault settings to be initialized",
39055
+ "paths-unreadable": "the old settings store paths to become readable",
39056
+ "vault-unseeded": "the vault settings to be ready"
39057
+ };
39058
+ function formatSettingsModeStatus(options) {
39059
+ const target = options.file ? `\`${options.file}\`` : "the shared settings file";
39060
+ if (options.mode === "user-file")
39061
+ return `Settings: shared file ${target}`;
39062
+ if (options.mode === "separate")
39063
+ return "Settings: using the old settings; this separate install keeps its own settings and does not move them to the shared file";
39064
+ const diagnostic = options.diagnostic;
39065
+ const kinds = [...new Set(diagnostic?.blockers?.map(({ kind }) => kind))];
39066
+ const reason = kinds.length ? kinds.map((kind) => blockerWords[kind]).join("; ") : diagnostic?.outcome === "source-unavailable" && diagnostic.sourceReason ? sourceWords[diagnostic.sourceReason] : diagnostic ? outcomeWords[diagnostic.outcome] : "the settings move to complete at a later start";
39067
+ return `Settings: using the old settings; the move to ${target} waits for: ${reason}`;
39068
+ }
39069
+
38941
39070
  // src/settings-record.ts
38942
39071
  function settingsFileSets(generation, key, host2, model2) {
38943
39072
  const levels = generation.fileLevels[key];
@@ -39074,6 +39203,7 @@ function resolveSettingsRecord(stored, generation, host2, model2) {
39074
39203
  // src/native-runtime-settings.ts
39075
39204
  function createNativeRuntimeSettings(options) {
39076
39205
  const env = options.env ?? process.env;
39206
+ let diagnostic = options.settingsDiagnostic;
39077
39207
  let adoption = getSettingsAdoptionCheck(options.settingsService);
39078
39208
  const startedPending = isSettingsImportPending(options.settingsService);
39079
39209
  let service = options.settingsService?.retain();
@@ -39281,6 +39411,16 @@ function createNativeRuntimeSettings(options) {
39281
39411
  return {
39282
39412
  resolve: resolve22,
39283
39413
  status,
39414
+ modeStatus(file) {
39415
+ return formatSettingsModeStatus({
39416
+ mode: mode() === "separate" ? "separate" : userAuthority || mode() === "user-file" ? "user-file" : "legacy",
39417
+ file: service?.file ?? fallback?.file ?? file,
39418
+ diagnostic
39419
+ });
39420
+ },
39421
+ setDiagnostic(next) {
39422
+ diagnostic = next;
39423
+ },
39284
39424
  gateway,
39285
39425
  applyEffects,
39286
39426
  file: () => generation()?.file,
@@ -42028,6 +42168,8 @@ function acquireNativeAccountRuntime(options) {
42028
42168
  const { use, close } = sharedAccounts.acquire(key, () => createNativeAccountRuntime(options));
42029
42169
  const vault = leaseNativeVaultRuntime(() => use().vault, close);
42030
42170
  const quotaObservations = use().quotaObservations;
42171
+ if (options.settingsDiagnostic)
42172
+ use().setSettingsDiagnostic?.(options.settingsDiagnostic);
42031
42173
  const onLockEvent = use().onLockEvent;
42032
42174
  const relocationGuard = use().relocationGuard;
42033
42175
  const drainRoutingPublications = use().drainRoutingPublications;
@@ -42047,6 +42189,7 @@ function acquireNativeAccountRuntime(options) {
42047
42189
  read: (model2) => use().read(model2),
42048
42190
  resolveSettings: (stored, model2) => use().resolveSettings?.(stored, model2) ?? stored,
42049
42191
  getSettingsStatus: () => use().getSettingsStatus?.(),
42192
+ getSettingsModeStatus: () => use().getSettingsModeStatus?.() ?? "",
42050
42193
  getClaudeGateway: () => use().getClaudeGateway?.(),
42051
42194
  applySettingsEffects: () => use().applySettingsEffects?.(),
42052
42195
  prepareSettingsAction: () => use().prepareSettingsAction?.() ?? Promise.resolve(),
@@ -42576,6 +42719,8 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42576
42719
  return runtimeSettings.file() ?? (await selectedStorage()).paths.config;
42577
42720
  },
42578
42721
  getSettingsStatus: runtimeSettings.status,
42722
+ getSettingsModeStatus: () => runtimeSettings.modeStatus(options.settingsFile ?? getSettingsFilePath({ env })),
42723
+ setSettingsDiagnostic: runtimeSettings.setDiagnostic,
42579
42724
  getClaudeGateway: runtimeSettings.gateway,
42580
42725
  resolveSettings: runtimeSettings.resolve,
42581
42726
  applySettingsEffects: runtimeSettings.applyEffects,
@@ -49730,34 +49875,55 @@ function stamped(value) {
49730
49875
  const writer = value.writer;
49731
49876
  return typeof writer === "object" && writer !== null && writer.protocol === 1;
49732
49877
  }
49733
- async function readArtifact(path2, blockers) {
49878
+ function publisherPid(kind, name) {
49879
+ const match = kind === "rpc" ? /^port-(\d+)\.json$/.exec(name) : /^(\d+)-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/.exec(name);
49880
+ const pid = Number(match?.[1]);
49881
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
49882
+ }
49883
+ async function readArtifact(path2, blockers, malformedIsStale) {
49734
49884
  let text6;
49735
49885
  let mtimeMs;
49886
+ let regular;
49736
49887
  try {
49737
49888
  const file = await open15(path2, "r");
49738
49889
  try {
49739
49890
  text6 = await file.readFile("utf8");
49740
- mtimeMs = (await file.stat()).mtimeMs;
49891
+ const stat16 = await file.stat();
49892
+ mtimeMs = stat16.mtimeMs;
49893
+ regular = stat16.isFile();
49741
49894
  } finally {
49742
49895
  await file.close();
49743
49896
  }
49744
49897
  } catch (error) {
49745
49898
  if (errorCode5(error) === "ENOENT")
49746
49899
  return;
49747
- blockers.push({ kind: "artifact-scan", path: path2, reason: reasonOf(error) });
49900
+ if (!malformedIsStale())
49901
+ blockers.push({ kind: "artifact-scan", path: path2, reason: reasonOf(error) });
49748
49902
  return;
49749
49903
  }
49750
49904
  try {
49751
49905
  const value = JSON.parse(text6);
49752
49906
  const startedAt = typeof value === "object" && value !== null ? "startedAt" in value ? value.startedAt : ("registeredAt" in value) ? value.registeredAt : mtimeMs : mtimeMs;
49753
- return { value, startedAt };
49907
+ return { value, startedAt, regular };
49754
49908
  } catch {
49755
- blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49909
+ if (!malformedIsStale(regular ? mtimeMs : undefined))
49910
+ blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49756
49911
  return;
49757
49912
  }
49758
49913
  }
49759
49914
  async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidAlive, clock = {}, acceptsRelease) {
49760
49915
  const exempt = (value) => stamped(value) && (!acceptsRelease || acceptsRelease(value.writer.release));
49916
+ const malformedIsStale = (pid, startedAt) => {
49917
+ if (pid === undefined)
49918
+ return false;
49919
+ if (recordPredatesBoot(startedAt, clock))
49920
+ return true;
49921
+ try {
49922
+ return !pidAlive2(pid);
49923
+ } catch {
49924
+ return false;
49925
+ }
49926
+ };
49761
49927
  const blockers = [];
49762
49928
  const portDirs = [...locations.rpcDirs];
49763
49929
  for (const root of locations.rpcRoots)
@@ -49768,13 +49934,16 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
49768
49934
  if (!/^port-\d+\.json$/.test(name))
49769
49935
  continue;
49770
49936
  const path2 = join33(dir, name);
49771
- const record17 = await readArtifact(path2, blockers);
49937
+ const filenamePid = publisherPid("rpc", name);
49938
+ const isStale = (startedAt2) => malformedIsStale(filenamePid, startedAt2);
49939
+ const record17 = await readArtifact(path2, blockers, isStale);
49772
49940
  if (record17 === undefined || exempt(record17.value))
49773
49941
  continue;
49774
49942
  const { value, startedAt } = record17;
49775
- const pid = value.pid;
49943
+ const pid = value?.pid;
49776
49944
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
49777
- blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49945
+ if (!isStale(record17.regular ? startedAt : undefined))
49946
+ blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49778
49947
  continue;
49779
49948
  }
49780
49949
  if (!recordPredatesBoot(startedAt, clock) && pidAlive2(pid))
@@ -49787,7 +49956,8 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
49787
49956
  if (!match)
49788
49957
  continue;
49789
49958
  const path2 = join33(dir, name);
49790
- const record17 = await readArtifact(path2, blockers);
49959
+ const filenamePid = publisherPid("cachekeep", name);
49960
+ const record17 = await readArtifact(path2, blockers, (startedAt) => malformedIsStale(filenamePid, startedAt));
49791
49961
  if (record17 === undefined || exempt(record17.value))
49792
49962
  continue;
49793
49963
  const pid = Number(match[1]);
@@ -50253,6 +50423,7 @@ async function prepareSettingsMoveSources(options) {
50253
50423
  }
50254
50424
 
50255
50425
  // src/settings-move-run.ts
50426
+ var loggedClosedFence = false;
50256
50427
  async function importSettingsHostStore(options, service, warn, retry) {
50257
50428
  const { host: host2, paths: paths2 } = options;
50258
50429
  const authority = { ...options, ...options.authority };
@@ -50305,6 +50476,17 @@ async function importSettingsHostStore(options, service, warn, retry) {
50305
50476
  async function runSettingsMoveAtStartup(options) {
50306
50477
  const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
50307
50478
  const authority = { ...options, ...options.authority };
50479
+ let blockers = [];
50480
+ const noteClosedFence = () => {
50481
+ if (loggedClosedFence)
50482
+ return;
50483
+ loggedClosedFence = true;
50484
+ const message = `Settings move waits for a closed fence; keeping legacy settings. Blockers: ${JSON.stringify(blockers)}`;
50485
+ if (options.log?.info)
50486
+ options.log.info(message);
50487
+ else
50488
+ logger2.info("settings", message);
50489
+ };
50308
50490
  const logged3 = new Set;
50309
50491
  const warn = (message) => {
50310
50492
  const key = `${paths2.target}\x00${message}`;
@@ -50321,6 +50503,7 @@ async function runSettingsMoveAtStartup(options) {
50321
50503
  mode: mode2,
50322
50504
  mayOpenService: mode2 !== "separate" && outcome2 !== "import-refused",
50323
50505
  outcome: outcome2,
50506
+ ...blockers.length ? { blockers } : {},
50324
50507
  ...move2 ? { move: move2 } : {}
50325
50508
  });
50326
50509
  const startOnFile = async (outcome2, move2) => {
@@ -50388,16 +50571,30 @@ async function runSettingsMoveAtStartup(options) {
50388
50571
  const stores = [paths2.own.account];
50389
50572
  if (paths2.sourceRule === "default")
50390
50573
  stores.push(paths2.defaults.opencode.account, paths2.defaults.pi.account);
50391
- const fence = async () => (await checkSettingsMoveFence({ ...options, ...options.fence, stores })).open;
50574
+ const fence = async () => {
50575
+ const checked = await checkSettingsMoveFence({
50576
+ ...options,
50577
+ ...options.fence,
50578
+ stores
50579
+ });
50580
+ blockers = checked.blockers.map(settingsMoveBlockerIdentity);
50581
+ if (!checked.open)
50582
+ noteClosedFence();
50583
+ return checked.open;
50584
+ };
50392
50585
  if (!await fence())
50393
50586
  return result("legacy", "fence-closed");
50394
50587
  const prepared = await (options.dependencies?.prepareSources ?? prepareSettingsMoveSources)({ ...options, paths: paths2 });
50395
50588
  if (prepared.status !== "ready") {
50396
50589
  if (prepared.status === "unavailable")
50397
50590
  warn(`Settings move unavailable for ${prepared.host}: ${prepared.reason}; keeping legacy settings until the next start.`);
50398
- return result("legacy", "source-unavailable");
50591
+ return {
50592
+ ...result("legacy", "source-unavailable"),
50593
+ ...prepared.status === "unavailable" ? { sourceReason: prepared.reason } : {}
50594
+ };
50399
50595
  }
50400
50596
  let holderFiles;
50597
+ let holderFile;
50401
50598
  try {
50402
50599
  holderFiles = await settingsMoveHolderFiles({
50403
50600
  ...options,
@@ -50406,6 +50603,7 @@ async function runSettingsMoveAtStartup(options) {
50406
50603
  });
50407
50604
  const context = resolvePathOptions(options);
50408
50605
  for (const file of holderFiles) {
50606
+ holderFile = file;
50409
50607
  const folder = context.paths.dirname(file);
50410
50608
  if (options.authority?.fs?.mkdir)
50411
50609
  await options.authority.fs.mkdir(folder);
@@ -50416,6 +50614,10 @@ async function runSettingsMoveAtStartup(options) {
50416
50614
  });
50417
50615
  }
50418
50616
  } catch {
50617
+ blockers = [
50618
+ { kind: "holder-file", ...holderFile ? { path: holderFile } : {} }
50619
+ ];
50620
+ noteClosedFence();
50419
50621
  return result("legacy", "fence-closed");
50420
50622
  }
50421
50623
  const [first, ...rest] = prepared.sources;
@@ -50487,6 +50689,9 @@ async function startSettings(options) {
50487
50689
  };
50488
50690
  const move = options.start?.move ?? runSettingsMoveAtStartup;
50489
50691
  const open16 = options.start?.open ?? openSettingsService;
50692
+ const diagnostic = {
50693
+ outcome: refused2 ? "authority-refused" : "startup-failed"
50694
+ };
50490
50695
  let adopted = false;
50491
50696
  const serviceOptions = (file2) => ({
50492
50697
  file: file2,
@@ -50512,6 +50717,10 @@ async function startSettings(options) {
50512
50717
  };
50513
50718
  const adopt = async (service) => {
50514
50719
  const outcome2 = await importSettingsHostStore({ ...options, paths: await resolvePaths() }, service, warnOnce, "at its next settings check");
50720
+ if (outcome2 !== "adopt" && outcome2 !== "pending") {
50721
+ diagnostic.outcome = outcome2 === "refused" ? "import-refused" : outcome2 === "unknown" ? "import-unknown" : "import-pending";
50722
+ delete diagnostic.blockers;
50723
+ }
50515
50724
  if (outcome2 === "pending")
50516
50725
  return "pending";
50517
50726
  if (outcome2 !== "adopt")
@@ -50532,16 +50741,19 @@ async function startSettings(options) {
50532
50741
  const started = await move(options);
50533
50742
  file = started.paths.target;
50534
50743
  paths2 = started.paths;
50744
+ diagnostic.outcome = started.outcome;
50745
+ diagnostic.blockers = started.blockers;
50746
+ diagnostic.sourceReason = started.sourceReason;
50535
50747
  moved = started.mode === "user-file";
50536
50748
  adopted = moved && !started.importPending;
50537
50749
  if (!started.mayOpenService)
50538
- return { mode: started.mode, file };
50750
+ return { mode: started.mode, file, diagnostic };
50539
50751
  const service = track(await open16(serviceOptions(file)));
50540
50752
  if (!service)
50541
- return { mode: started.mode, file };
50753
+ return { mode: started.mode, file, diagnostic };
50542
50754
  if (started.importPending)
50543
50755
  markSettingsImportPending(service);
50544
- return { mode: started.mode, file, service };
50756
+ return { mode: started.mode, file, service, diagnostic };
50545
50757
  } catch {
50546
50758
  if (!warned3) {
50547
50759
  warned3 = true;
@@ -50593,7 +50805,7 @@ async function startSettings(options) {
50593
50805
  };
50594
50806
  if (refused2) {
50595
50807
  if (options.paths?.separate)
50596
- return { mode: "separate", file: options.paths.target };
50808
+ return { mode: "separate", file: options.paths.target, diagnostic };
50597
50809
  try {
50598
50810
  file = options.paths?.target ?? getSettingsFilePath(options);
50599
50811
  } catch {}
@@ -50613,7 +50825,7 @@ async function startSettings(options) {
50613
50825
  return;
50614
50826
  return openService();
50615
50827
  }, { retryDelaysMs: PREFLIGHT_RETRY_DELAYS_MS, separate: () => separate });
50616
- return { mode: "legacy", file, reopen: reopenAfterPreflight };
50828
+ return { mode: "legacy", file, reopen: reopenAfterPreflight, diagnostic };
50617
50829
  }
50618
50830
  let mode = "user-file";
50619
50831
  let unknown = false;
@@ -50631,13 +50843,14 @@ async function startSettings(options) {
50631
50843
  }
50632
50844
  }
50633
50845
  if (mode === "legacy")
50634
- return { mode, file, reopen: reopenLegacy };
50846
+ return { mode, file, reopen: reopenLegacy, diagnostic };
50635
50847
  if (mode !== "user-file")
50636
- return { mode, file };
50848
+ return { mode, file, diagnostic };
50637
50849
  const recovered = await recoverSettingsProtection(file, options.host, options.protection, file ? options.host : undefined);
50638
50850
  return {
50639
50851
  mode,
50640
50852
  file,
50853
+ diagnostic,
50641
50854
  fallback: {
50642
50855
  get file() {
50643
50856
  return file;
@@ -52821,6 +53034,7 @@ export {
52821
53034
  stickyRetryAfterWithJitter,
52822
53035
  stickyRetainRetryHeaders,
52823
53036
  stickyQuotaSnapshotIsFresh,
53037
+ stickyQuotaExhaustionInForce,
52824
53038
  stateSubfolderName,
52825
53039
  stateRefusalPublicMessage,
52826
53040
  stateRefusalCause,
@@ -52843,6 +53057,7 @@ export {
52843
53057
  settingsRecreationForWriter,
52844
53058
  settingsRecreationFloors,
52845
53059
  settingsMoveHolderFiles,
53060
+ settingsMoveBlockerIdentity,
52846
53061
  settingsImportRecordPath,
52847
53062
  settingsFileUnusableText,
52848
53063
  settingsFileSets,
@@ -52951,6 +53166,7 @@ export {
52951
53166
  quotaSnapshotHasStandardWindows,
52952
53167
  quotaSnapshotCheckedAt,
52953
53168
  quotaRefusalTiming,
53169
+ quotaRefusalRetryAfterSeconds,
52954
53170
  quotaRefusalDetails,
52955
53171
  quotaFieldSource,
52956
53172
  quotaExhaustionFromHeaders,
@@ -53174,6 +53390,7 @@ export {
53174
53390
  generateRelayToken,
53175
53391
  generatePKCE,
53176
53392
  gatewaySettingsFile,
53393
+ formatSettingsModeStatus,
53177
53394
  formatRefreshBackoffMessage,
53178
53395
  formatQuotaMoney,
53179
53396
  formatQuotaBackoffMessage,
@@ -53258,6 +53475,7 @@ export {
53258
53475
  createNativeLocalCredentialService,
53259
53476
  createNativeCustody,
53260
53477
  createNativeAccountRuntime,
53478
+ createExhaustedNoRouteResponse,
53261
53479
  createEmptyStorage,
53262
53480
  createDumpResponseObserver,
53263
53481
  createClaudeModelFetch,
@@ -57,8 +57,9 @@ export declare function defaultPreNArtifactLocations(env?: NodeJS.ProcessEnv, ho
57
57
  /**
58
58
  * The fence's check for older versions: an RPC port file or CacheKeep record without the
59
59
  * `writer` stamp, whose pid is alive, belongs to a version that registers
60
- * nothing and blocks. Every entry is read; a folder or file that can't be
61
- * read or parsed blocks too. A record from before this boot is stale even
60
+ * nothing and blocks. Unreadable or malformed publisher-owned files need a
61
+ * proven dead filename pid, or a readable regular file's pre-boot mtime.
62
+ * Other scan failures block. A record from before this boot is stale even
62
63
  * if its pid has been reused; missing or untrustworthy times keep blocking.
63
64
  */
64
65
  export declare function preNArtifactBlockers(locations: PreNArtifactLocations, pidAlive?: (pid: number) => boolean, clock?: Pick<HolderLiveness, 'now' | 'uptime'>,
@@ -16,6 +16,7 @@ import { type NativePoolPaths } from './pool-paths.ts';
16
16
  import type { QuotaRequestDispatch } from './quota-manager.ts';
17
17
  import { type RelayConfig } from './relay.ts';
18
18
  import { type RelocationGuard } from './relocation-guard.ts';
19
+ import type { SettingsMoveDiagnostic } from './settings-mode-status.ts';
19
20
  export type { NativeAccountMetadataPatch, NativeAccountSnapshot, NativeAccountView, } from './native-account-view.ts';
20
21
  export interface NativeAccountRuntimeOptions extends NativeRuntimeSettingsOptions {
21
22
  paths: NativePoolPaths;
@@ -94,6 +95,9 @@ export interface NativeAccountRuntime {
94
95
  resolveSettings?(stored: AccountStorage, model?: string): AccountStorage;
95
96
  /** No-model settings and every explicit model override, for /claude status. */
96
97
  getSettingsStatus?(): NativeRuntimeSettingsStatus | undefined;
98
+ getSettingsModeStatus?(): string;
99
+ /** Update the memory-only startup diagnostic when another host instance joins. */
100
+ setSettingsDiagnostic?(diagnostic: SettingsMoveDiagnostic): void;
97
101
  /**
98
102
  * The user's gateway for Claude OAuth model requests, from memory. Hosts
99
103
  * use it only for model requests, never for sign-in, refresh or usage.
@@ -2,6 +2,7 @@ import type { AccountStorage } from './accounts.ts';
2
2
  import { type ClaudeGateway, type ClaudeGatewayStatus } from './gateway.ts';
3
3
  import { type SettingsKey } from './settings-definition.ts';
4
4
  import { type SettingsMode, type SettingsModeOptions } from './settings-mode.ts';
5
+ import { type SettingsMoveDiagnostic } from './settings-mode-status.ts';
5
6
  import type { SettingsHost } from './settings-paths.ts';
6
7
  import { type SettingsFileStatus, type SettingsService, type SettingsUpdate, type SettingsValues } from './settings-service.ts';
7
8
  import type { SettingsProtectionFallback, SettingsReopen } from './settings-start.ts';
@@ -9,6 +10,7 @@ export interface NativeRuntimeSettingsOptions {
9
10
  settingsService?: SettingsService;
10
11
  /** Return the cached settings mode; this callback must not read the filesystem. */
11
12
  settingsMode?: () => SettingsMode;
13
+ settingsDiagnostic?: SettingsMoveDiagnostic;
12
14
  settingsAuthority?: {
13
15
  options?: SettingsModeOptions;
14
16
  /** Schedule a background authority check and return its cancellation function. */
@@ -56,6 +58,8 @@ export declare function createNativeRuntimeSettings(options: NativeRuntimeSettin
56
58
  (stored: Record<string, unknown>, model?: string): Record<string, unknown>;
57
59
  };
58
60
  status: () => NativeRuntimeSettingsStatus | undefined;
61
+ modeStatus(file: string): string;
62
+ setDiagnostic(next: SettingsMoveDiagnostic): void;
59
63
  gateway: () => ClaudeGateway | undefined;
60
64
  applyEffects: () => void;
61
65
  file: () => string | undefined;
@@ -0,0 +1,25 @@
1
+ import type { SettingsMode } from './settings-mode.ts';
2
+ import type { SettingsMoveFenceBlocker } from './settings-move-fence.ts';
3
+ import type { SettingsMoveStartupResult } from './settings-move-run.ts';
4
+ import type { SettingsMoveSourcesResult } from './settings-move-sources.ts';
5
+ /** Only blocker identities are exposed; reasons can contain filesystem errors. */
6
+ export interface SettingsMoveBlockerIdentity {
7
+ kind: SettingsMoveFenceBlocker['kind'];
8
+ path?: string;
9
+ pid?: number | null;
10
+ release?: string | null;
11
+ }
12
+ export interface SettingsMoveDiagnostic {
13
+ outcome: SettingsMoveStartupResult['outcome'] | 'authority-refused' | 'startup-failed';
14
+ blockers?: readonly SettingsMoveBlockerIdentity[];
15
+ sourceReason?: Extract<SettingsMoveSourcesResult, {
16
+ status: 'unavailable';
17
+ }>['reason'];
18
+ }
19
+ export declare function settingsMoveBlockerIdentity(blocker: SettingsMoveFenceBlocker): SettingsMoveBlockerIdentity;
20
+ /** Shared by every host, using only the runtime's cached settings mode and move result. */
21
+ export declare function formatSettingsModeStatus(options: {
22
+ mode: SettingsMode;
23
+ file: string;
24
+ diagnostic?: SettingsMoveDiagnostic;
25
+ }): string;
@@ -1,10 +1,14 @@
1
1
  import { type MoveOutcome, type MoveResult, moveSettingsOnce } from "./internal-types/settings/index.js";
2
2
  import { type SettingsMode, type SettingsModeOptions } from './settings-mode.ts';
3
+ import { type SettingsMoveBlockerIdentity, type SettingsMoveDiagnostic } from './settings-mode-status.ts';
3
4
  import { type SettingsMoveFenceOptions } from './settings-move-fence.ts';
4
5
  import { prepareSettingsMoveSources, type SettingsMoveSourcesOptions } from './settings-move-sources.ts';
5
6
  import { type SettingsPaths } from './settings-paths.ts';
6
7
  import { type SettingsService } from './settings-service.ts';
7
8
  export interface SettingsMoveStartupOptions extends SettingsMoveSourcesOptions {
9
+ log?: SettingsMoveSourcesOptions['log'] & {
10
+ info?: (message: string) => void;
11
+ };
8
12
  fence: Pick<SettingsMoveFenceOptions, 'registration' | 'floor' | 'self' | 'liveness' | 'artifacts' | 'readHolders'>;
9
13
  authority?: Pick<SettingsModeOptions, 'fs' | 'ownership' | 'now'>;
10
14
  dependencies?: {
@@ -33,6 +37,8 @@ export interface SettingsMoveStartupResult {
33
37
  */
34
38
  | 'import-pending';
35
39
  move?: MoveResult;
40
+ blockers?: SettingsMoveBlockerIdentity[];
41
+ sourceReason?: SettingsMoveDiagnostic['sourceReason'];
36
42
  /**
37
43
  * In user-file mode: the file is missing and this host's legacy store was
38
44
  * never imported. The host uses the file (its protection comes from this
@@ -1,4 +1,5 @@
1
1
  import { type SettingsMode } from './settings-mode.ts';
2
+ import type { SettingsMoveDiagnostic } from './settings-mode-status.ts';
2
3
  import { runSettingsMoveAtStartup, type SettingsMoveStartupOptions } from './settings-move-run.ts';
3
4
  import { type SettingsProtectionRecovery, type SettingsProtectionValues, type SettingsService, type SettingsServiceOptions } from './settings-service.ts';
4
5
  export interface StartSettingsOptions extends SettingsMoveStartupOptions {
@@ -47,6 +48,7 @@ export interface SettingsProtectionFallback {
47
48
  }
48
49
  export interface StartedSettings {
49
50
  mode: SettingsMode;
51
+ diagnostic?: SettingsMoveDiagnostic;
50
52
  /**
51
53
  * The settings file; empty only when no path could be resolved, which the
52
54
  * shared-runtime key treats as "no settings file".
@@ -118,6 +118,40 @@ export declare function decideStickyQuotaFailure(input: {
118
118
  accountId: string;
119
119
  };
120
120
  }): StickyQuotaFailureDecision;
121
+ export type StickyQuotaExhaustion = {
122
+ /** When the last exhausted window blocking the request resets. */
123
+ readonly resetAt: number;
124
+ readonly reason: 'five-hour' | 'seven-day' | 'model-scoped';
125
+ /** The window's name as quota refusals show it, such as "weekly". */
126
+ readonly limitName: string;
127
+ };
128
+ /**
129
+ * Confirmed exhaustion that still blocks a request for `modelId`: an exhausted
130
+ * 5-hour, weekly or model-scoped window whose reset is known and still ahead.
131
+ * It reads the same evidence as `decideStickyQuotaFailure`, except that stored
132
+ * header readings never count, because their percentages are display-rounded:
133
+ * only raw refused-request headers or a polled reading confirm exhaustion.
134
+ * Returns the latest such reset, since the account can serve the request again
135
+ * only after every one of those windows resets. Windows whose reset is unknown
136
+ * or already past are not counted.
137
+ */
138
+ export declare function stickyQuotaExhaustionInForce(input: {
139
+ quota: OAuthQuotaSnapshot | QuotaState | undefined;
140
+ responseHeaders?: Headers;
141
+ modelId?: string;
142
+ now?: number;
143
+ }): StickyQuotaExhaustion | undefined;
144
+ /**
145
+ * The quota refusal for a request that no account can take because every
146
+ * account that could is confirmed exhausted (see `stickyQuotaExhaustionInForce`).
147
+ * It names the window that resets first across those accounts.
148
+ */
149
+ export declare function createExhaustedNoRouteResponse(input: {
150
+ exhausted: readonly StickyQuotaExhaustion[];
151
+ storage?: AccountStorage | null;
152
+ sessionId?: string | null;
153
+ now?: number;
154
+ }): Response;
121
155
  /** Bound an unconfirmed 429's host retry while preserving any shorter upstream wait. */
122
156
  export declare function stickyRetainRetryHeaders(upstream: Headers, now?: number): Headers;
123
157
  export declare function getStickyRoutingStatePath(accountStoragePath: string): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.14.1",
3
+ "version": "2.15.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",