@cortexkit/anthropic-auth-core 2.15.2 → 2.16.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.
@@ -183,6 +183,7 @@ export type AccountStorage = {
183
183
  routing?: {
184
184
  mode?: RoutingMode;
185
185
  maxSameAccountWait?: import('./routing.ts').MaxSameAccountWait;
186
+ waitForReset?: boolean;
186
187
  };
187
188
  fallbackOn?: number[];
188
189
  refresh?: {
@@ -447,11 +448,15 @@ export declare function quotaRefusalTiming(input: {
447
448
  scopedModelId?: string;
448
449
  modelId?: string;
449
450
  sessionTtlMs?: number;
451
+ /** The caller found no other route and this host supports reset-sized waits. */
452
+ waitForReset?: boolean;
453
+ sessionId?: string | null;
450
454
  now?: number;
451
455
  }): {
452
456
  resetAt: number | undefined;
453
457
  retryAfterSeconds: number | undefined;
454
458
  limitName?: string;
459
+ resetWaitMs?: number;
455
460
  };
456
461
  /**
457
462
  * The retry delay a quota refusal advertises: the time until `resetAt` (five
@@ -1,5 +1,7 @@
1
- /** Hosts recheck availability periodically instead of sleeping until a distant quota reset. */
1
+ /** Ordinary host retries recheck availability periodically. */
2
2
  export declare const MAX_HOST_RETRY_MS: number;
3
+ export declare function markResetWaitResponse(response: Response, delayMs: number): Response;
4
+ export declare function resetWaitDelayMs(response: Response): number | undefined;
3
5
  export declare function clampHostRetryMs(delayMs: number): number;
4
6
  /** Keep quota reset headers intact: they are evidence, not instructions to the host. */
5
7
  export declare function hostRetryHeaders(upstream: Headers, now?: number): Headers;
package/dist/index.js CHANGED
@@ -721,6 +721,9 @@ function loadBackend() {
721
721
  });
722
722
  return backend;
723
723
  }
724
+ function isSharingIoError(detail) {
725
+ return detail?.reason === "io-error" && (detail.win32Code === 32 || detail.win32Code === 303);
726
+ }
724
727
 
725
728
  class PrivateFileError extends Error {
726
729
  path;
@@ -736,7 +739,7 @@ class PrivateFileError extends Error {
736
739
  orphanPath;
737
740
  constructor(path, stage, cause) {
738
741
  const detail = cause;
739
- super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
742
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : isSharingIoError(detail) ? `Private file busy at ${stage}: ${path}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).` : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
740
743
  this.path = path;
741
744
  this.stage = stage;
742
745
  this.name = "PrivateFileError";
@@ -746,7 +749,7 @@ class PrivateFileError extends Error {
746
749
  }
747
750
  }
748
751
  function isWindowsSharingViolation(error) {
749
- return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
752
+ return windowsPrivateFiles && error instanceof PrivateFileError && isSharingIoError(error);
750
753
  }
751
754
  async function privateOperation(path, stage, operation) {
752
755
  try {
@@ -10545,6 +10548,14 @@ async function exchange(input, verifier, redirectUri, expectedState) {
10545
10548
 
10546
10549
  // src/host-retry.ts
10547
10550
  var MAX_HOST_RETRY_MS = 15 * 60000;
10551
+ var resetWaits = new WeakMap;
10552
+ function markResetWaitResponse(response, delayMs) {
10553
+ resetWaits.set(response, delayMs);
10554
+ return response;
10555
+ }
10556
+ function resetWaitDelayMs(response) {
10557
+ return resetWaits.get(response);
10558
+ }
10548
10559
  function clampHostRetryMs(delayMs) {
10549
10560
  return Math.max(0, Math.min(MAX_HOST_RETRY_MS, Number.isNaN(delayMs) ? 0 : delayMs));
10550
10561
  }
@@ -10567,6 +10578,8 @@ function hostRetryHeaders(upstream, now = Date.now()) {
10567
10578
  return headers;
10568
10579
  }
10569
10580
  function hostRetryResponse(response, now = Date.now()) {
10581
+ if (resetWaits.has(response))
10582
+ return response;
10570
10583
  const headers = hostRetryHeaders(response.headers, now);
10571
10584
  if (["retry-after", "retry-after-ms"].every((name) => headers.get(name) === response.headers.get(name)))
10572
10585
  return response;
@@ -12241,6 +12254,9 @@ var ROUTING_MODES = [
12241
12254
  var DEFAULT_ROUTING_MODE = "main-first";
12242
12255
  var MAX_SAME_ACCOUNT_WAITS = ["0", "15", "max"];
12243
12256
  var DEFAULT_MAX_SAME_ACCOUNT_WAIT = "15";
12257
+ function getWaitForReset(storage) {
12258
+ return storage?.routing?.waitForReset === true;
12259
+ }
12244
12260
  function getMaxSameAccountWait(storage) {
12245
12261
  const value = storage?.routing?.maxSameAccountWait;
12246
12262
  return MAX_SAME_ACCOUNT_WAITS.includes(value) ? value : DEFAULT_MAX_SAME_ACCOUNT_WAIT;
@@ -13095,8 +13111,10 @@ function quotaRefusalTiming(input) {
13095
13111
  }
13096
13112
  const earliest = resetTimes.sort((a, b) => a.resetAt - b.resetAt)[0];
13097
13113
  const resetAt = earliest?.resetAt;
13114
+ const resetWaitMs = input.waitForReset && getWaitForReset(storage) && resetAt !== undefined && input.readings.length > 0 && resetTimes.length === input.readings.length ? (Math.ceil((resetAt - now) / 1000) + createHash4("sha256").update(input.sessionId ?? "").digest().readUInt32BE(0) % 21) * 1000 : undefined;
13098
13115
  return {
13099
13116
  resetAt,
13117
+ ...resetWaitMs === undefined ? {} : { resetWaitMs },
13100
13118
  ...earliest ? { limitName: earliest.limitName } : {},
13101
13119
  retryAfterSeconds: quotaRefusalRetryAfterSeconds({
13102
13120
  resetAt,
@@ -21984,7 +22002,7 @@ async function callFailureHook(operation, hook, rowId, error, logger3) {
21984
22002
  }
21985
22003
 
21986
22004
  // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
21987
- import { setTimeout as snapshotDelay } from "node:timers/promises";
22005
+ import { setTimeout as delay4 } from "node:timers/promises";
21988
22006
 
21989
22007
  // ../../node_modules/@cortexkit/common-auth/dist/store/reserved.js
21990
22008
  function assertNotReserved(operation, id, reservation) {
@@ -22664,13 +22682,19 @@ function loadRows(config, state, codec, options = {}) {
22664
22682
  }
22665
22683
 
22666
22684
  // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
22685
+ var sharingRetryDelays = [5, 10, 20, 40, 80, 160, 320, 400];
22667
22686
  async function readText(path2) {
22668
- try {
22669
- return await readPrivateText(path2, windowsPrivateFiles);
22670
- } catch (error) {
22671
- if (error.code === "ENOENT")
22672
- return;
22673
- throw error;
22687
+ for (let attempt = 0;; attempt++) {
22688
+ try {
22689
+ return await readPrivateText(path2, windowsPrivateFiles);
22690
+ } catch (error) {
22691
+ if (error.code === "ENOENT")
22692
+ return;
22693
+ const wait = sharingRetryDelays[attempt];
22694
+ if (wait === undefined || !isWindowsSharingViolation(error))
22695
+ throw error;
22696
+ await delay4(wait);
22697
+ }
22674
22698
  }
22675
22699
  }
22676
22700
  function parseFile(text) {
@@ -22687,12 +22711,21 @@ async function readPoolConfig(path2) {
22687
22711
  }
22688
22712
  async function readPool(ctx) {
22689
22713
  for (let attempt = 0;attempt < 3; attempt++) {
22690
- const configText = await readText(ctx.configPath);
22691
- const stateText = await readText(ctx.statePath);
22692
- const checkedConfigText = await readText(ctx.configPath);
22714
+ let configText;
22715
+ let stateText;
22716
+ let checkedConfigText;
22717
+ try {
22718
+ configText = await readText(ctx.configPath);
22719
+ stateText = await readText(ctx.statePath);
22720
+ checkedConfigText = await readText(ctx.configPath);
22721
+ } catch (error) {
22722
+ if (isWindowsSharingViolation(error))
22723
+ break;
22724
+ throw error;
22725
+ }
22693
22726
  if (configText !== checkedConfigText) {
22694
22727
  if (attempt < 2)
22695
- await snapshotDelay(2 + Math.floor(Math.random() * 4));
22728
+ await delay4(2 + Math.floor(Math.random() * 4));
22696
22729
  continue;
22697
22730
  }
22698
22731
  const config = classifyConfig(parseFile(configText));
@@ -24653,11 +24686,11 @@ class PoolQuotaWriter {
24653
24686
  overlay(rows) {
24654
24687
  return rows.map((row) => this.overlayRow(row));
24655
24688
  }
24656
- schedule(delay4) {
24689
+ schedule(delay5) {
24657
24690
  if (this.running || this.timer || !this.pending.size || this.stopped)
24658
24691
  return;
24659
24692
  const remaining = this.closed ? 0 : (this.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - this.clock.now();
24660
- this.timer = this.clock.schedule(Math.max(delay4, remaining), () => {
24693
+ this.timer = this.clock.schedule(Math.max(delay5, remaining), () => {
24661
24694
  this.timer = undefined;
24662
24695
  return this.flush();
24663
24696
  });
@@ -24755,8 +24788,8 @@ class PoolQuotaWriter {
24755
24788
  this.running = undefined;
24756
24789
  for (const wake of this.wake)
24757
24790
  wake();
24758
- const delay4 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24759
- this.schedule(delay4);
24791
+ const delay5 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24792
+ this.schedule(delay5);
24760
24793
  }
24761
24794
  })();
24762
24795
  return this.running;
@@ -25968,11 +26001,11 @@ async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry
25968
26001
  throw error;
25969
26002
  original = error;
25970
26003
  }
25971
- for (const delay4 of [10, 20, 40, 80, 100]) {
26004
+ for (const delay5 of [10, 20, 40, 80, 100]) {
25972
26005
  const remaining = 500 - (now() - start);
25973
26006
  if (remaining <= 0)
25974
26007
  break;
25975
- await sleep(Math.min(delay4, remaining));
26008
+ await sleep(Math.min(delay5, remaining));
25976
26009
  if (now() - start >= 500)
25977
26010
  break;
25978
26011
  if (await beforeRetry?.() === "skip")
@@ -29394,9 +29427,10 @@ function retryMinutes(seconds) {
29394
29427
  return minutes === 1 ? "1 minute" : `${minutes} minutes`;
29395
29428
  }
29396
29429
  function createQuotaRefusalResponse(reason, timing, now = Date.now(), options = {}) {
29430
+ const resetWaitMs = options.retry !== "manual" ? timing.resetWaitMs : undefined;
29397
29431
  timing = {
29398
29432
  ...timing,
29399
- retryAfterSeconds: timing.retryAfterSeconds === undefined ? undefined : clampHostRetryMs(timing.retryAfterSeconds * 1000) / 1000
29433
+ retryAfterSeconds: resetWaitMs !== undefined ? resetWaitMs / 1000 : timing.retryAfterSeconds === undefined ? undefined : clampHostRetryMs(timing.retryAfterSeconds * 1000) / 1000
29400
29434
  };
29401
29435
  const reset = timing.resetAt === undefined ? "Reset time is unknown." : `Reset at ${new Intl.DateTimeFormat("en-US", {
29402
29436
  month: "long",
@@ -29418,7 +29452,7 @@ function createQuotaRefusalResponse(reason, timing, now = Date.now(), options =
29418
29452
  const duration = remaining >= 3600000 ? `${Math.ceil(remaining / 3600000)} h` : `${Math.ceil(remaining / 60000)} min`;
29419
29453
  const room = timing.limitName ? `No Claude account has room for this request (${timing.limitName} limit or your quota floor). ` : "";
29420
29454
  const manualAction = resetTime ? `The earliest reset is ${resetTime} UTC (in ${duration}). Send the message again after ${resetTime} UTC.` : "Reset time is unknown. Check account availability before sending the message again.";
29421
- const message = options.retry === "manual" || seconds === undefined ? `${room}This turn has stopped. ${manualAction} ${reason}` : timing.limitName && resetTime ? `${room}The earliest reset is ${resetTime} UTC (in ${duration}). Retrying every ${retryMinutes(seconds)}. ${reason}` : `${reason}${retry} ${reset}`;
29455
+ const message = options.retry === "manual" || seconds === undefined ? `${room}This turn has stopped. ${manualAction} ${reason}` : resetWaitMs !== undefined && resetTime ? `${room}The earliest reset is ${resetTime} UTC (in ${duration}). Waiting until the reset before retrying. ${reason}` : timing.limitName && resetTime ? `${room}The earliest reset is ${resetTime} UTC (in ${duration}). Retrying every ${retryMinutes(seconds)}. ${reason}` : `${reason}${retry} ${reset}`;
29422
29456
  const response = new Response(JSON.stringify({
29423
29457
  type: "error",
29424
29458
  error: {
@@ -29433,7 +29467,7 @@ function createQuotaRefusalResponse(reason, timing, now = Date.now(), options =
29433
29467
  }
29434
29468
  });
29435
29469
  details.set(response, { reason, timing });
29436
- return response;
29470
+ return resetWaitMs === undefined ? response : markResetWaitResponse(response, resetWaitMs);
29437
29471
  }
29438
29472
 
29439
29473
  // src/sticky-routing.ts
@@ -29510,7 +29544,9 @@ function createStickyNoRouteResponse(input) {
29510
29544
  storage: input.storage,
29511
29545
  modelId,
29512
29546
  now,
29513
- sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId)
29547
+ sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId),
29548
+ waitForReset: input.waitForReset,
29549
+ sessionId: input.sessionId
29514
29550
  });
29515
29551
  const limitNames = input.vaultPolicyLimits?.map((limit) => limit === "model-scoped" ? `${modelName ?? "Model"} scoped limit` : limit === "killswitch" ? "killswitch limit" : "quota floor");
29516
29552
  const reason = limitNames ? `No vault account currently satisfies quota policy: ${limitNames.join(", ")}. Open /claude → Killswitch / Quota to change these limits.` : scopedBlocked && modelName ? `${modelName} weekly limit reached, no routable OAuth accounts.` : "No OAuth account currently satisfies sticky-balanced quota policy.";
@@ -32240,8 +32276,8 @@ class CacheKeepStore {
32240
32276
  this.pending.set(entry2.id, entry2);
32241
32277
  if (this.timers.has(entry2.id))
32242
32278
  return;
32243
- const delay4 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
32244
- const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay4);
32279
+ const delay5 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
32280
+ const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay5);
32245
32281
  timer.unref?.();
32246
32282
  this.timers.set(entry2.id, timer);
32247
32283
  }
@@ -34675,6 +34711,8 @@ function projectNativeAccountViews(input) {
34675
34711
  ...settings,
34676
34712
  accounts: fallbacks
34677
34713
  };
34714
+ if (input.settings.routing?.waitForReset === true)
34715
+ policyStorage.routing = { ...policyStorage.routing, waitForReset: true };
34678
34716
  if (policyStorage.relay)
34679
34717
  policyStorage.relay = {
34680
34718
  ...policyStorage.relay,
@@ -35071,13 +35109,14 @@ var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the
35071
35109
  var transientAccountErrors = new WeakSet;
35072
35110
 
35073
35111
  class NativeTransientAccountError extends Error {
35074
- constructor() {
35112
+ constructor(operation) {
35075
35113
  super(TRANSIENT_ACCOUNT_MESSAGE);
35076
35114
  const fixed = {
35077
35115
  name: "NativeTransientAccountError",
35078
35116
  message: TRANSIENT_ACCOUNT_MESSAGE,
35079
35117
  code: "ECONNRESET",
35080
- syscall: "native-account-update"
35118
+ syscall: "native-account-update",
35119
+ ...operation === "pool-read" && { poolRead: true }
35081
35120
  };
35082
35121
  for (const [key, value] of Object.entries(fixed))
35083
35122
  Object.defineProperty(this, key, {
@@ -35092,6 +35131,21 @@ class NativeTransientAccountError extends Error {
35092
35131
  function isNativeTransientAccountError(value) {
35093
35132
  return typeof value === "object" && value !== null && transientAccountErrors.has(value);
35094
35133
  }
35134
+ async function readNativePool(read) {
35135
+ const result = await readNativePoolSettings(read);
35136
+ if (result.status === "error" && result.kind === "snapshot-contended" && result.retryable)
35137
+ throw new NativeTransientAccountError("pool-read");
35138
+ return result;
35139
+ }
35140
+ async function readNativePoolSettings(read) {
35141
+ try {
35142
+ return await read;
35143
+ } catch (error) {
35144
+ if (error instanceof PrivateFileError && error.stage === "read" && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303))
35145
+ throw new NativeTransientAccountError("pool-read");
35146
+ throw error;
35147
+ }
35148
+ }
35095
35149
  var NATIVE_POOL_WRITE_JOIN_BUDGET_MS = 2000;
35096
35150
  async function joinNativePoolWrite(paths, signals, check, onLockEvent) {
35097
35151
  const observer = nativeLockObserver(onLockEvent);
@@ -35303,7 +35357,7 @@ function createNativeRefreshCoordinator(options) {
35303
35357
  const bootstrap = options.resolveIdentity ?? resolveClaudeCodeAccountIdentity;
35304
35358
  const onLockEvent = nativeLockObserver(options.onLockEvent);
35305
35359
  async function rowFor(binding2) {
35306
- const read = await store.read();
35360
+ const read = await readNativePool(store.read());
35307
35361
  return read.status === "ready" ? read.rows.find((row) => row.id === binding2.rowId) : undefined;
35308
35362
  }
35309
35363
  async function readPolicy(subject) {
@@ -37212,6 +37266,7 @@ var settingsDefinition = defineSettings({
37212
37266
  value: oneOf(["off", "15m", "cache"]),
37213
37267
  default: "15m"
37214
37268
  },
37269
+ wait_for_reset: { ...host, value: boolean(), default: false },
37215
37270
  fallback_on: { ...host, value: list(integer()), default: [401, 403, 429] },
37216
37271
  refresh_enabled: { ...host, value: boolean(), default: true },
37217
37272
  refresh_interval_minutes: { ...host, value: nonnegative, default: 10 },
@@ -37294,6 +37349,7 @@ var settingsDefinition = defineSettings({
37294
37349
  }
37295
37350
  });
37296
37351
  var SETTINGS_FILE_ONLY_KEYS = [
37352
+ "wait_for_reset",
37297
37353
  "gateway_url",
37298
37354
  "gateway_headers"
37299
37355
  ];
@@ -37301,6 +37357,7 @@ var SETTINGS_PI_DIFFERING_FIELDS = [];
37301
37357
  var SETTINGS_DEFAULT_READERS = {
37302
37358
  routing_mode: "packages/core/src/routing.ts:getRoutingMode",
37303
37359
  max_same_account_wait: "packages/core/src/routing.ts:getMaxSameAccountWait",
37360
+ wait_for_reset: "packages/core/src/routing.ts:getWaitForReset",
37304
37361
  fallback_on: "packages/core/src/accounts.ts:shouldFallbackStatus",
37305
37362
  refresh_enabled: "packages/opencode/src/index.ts:mainRefreshEnabled",
37306
37363
  refresh_interval_minutes: "packages/core/src/accounts.ts:getRefreshIntervalMs",
@@ -39217,7 +39274,8 @@ function resolveSettingsRecord(stored, generation, host2, model2) {
39217
39274
  routing: {
39218
39275
  ...section2(stored, "routing"),
39219
39276
  mode: values.routing_mode,
39220
- maxSameAccountWait: legacyWait(values.max_same_account_wait)
39277
+ maxSameAccountWait: legacyWait(values.max_same_account_wait),
39278
+ waitForReset: values.wait_for_reset
39221
39279
  },
39222
39280
  fallbackOn: values.fallback_on,
39223
39281
  refresh: {
@@ -41476,7 +41534,7 @@ function createNativeVaultRuntime(options) {
41476
41534
  });
41477
41535
  }
41478
41536
  async function rowFor(roster, routeId) {
41479
- const settings = await store.readSettings();
41537
+ const settings = await readNativePoolSettings(store.readSettings());
41480
41538
  if (settings.status !== "ready")
41481
41539
  throw new NativeCustodyError("invalid-state");
41482
41540
  const pin = nativeVaultPrimaryPin(settings.settings);
@@ -42411,7 +42469,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42411
42469
  };
42412
42470
  }
42413
42471
  async function poolRow(id2) {
42414
- const read = await store.read();
42472
+ const read = await readNativePool(store.read());
42415
42473
  if (read.status !== "ready")
42416
42474
  throw new NativeRuntimeError("publication-refused");
42417
42475
  return read.rows.find((row) => row.id === id2);
@@ -42419,7 +42477,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42419
42477
  async function physicalId(id2) {
42420
42478
  if (id2 !== "main")
42421
42479
  return id2;
42422
- const settings = await store.readSettings();
42480
+ const settings = await readNativePoolSettings(store.readSettings());
42423
42481
  if (settings.status !== "ready" || typeof settings.settings.mainAccountId !== "string")
42424
42482
  throw new NativeCustodyError("route-unavailable");
42425
42483
  return settings.settings.mainAccountId;
@@ -42585,8 +42643,8 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42585
42643
  const selectedPaths = mode === "claustrum" ? vaultPaths : paths2;
42586
42644
  const selectedStore = mode === "claustrum" ? vaultStore : store;
42587
42645
  const [read, settings, metadata2] = await Promise.all([
42588
- selectedStore.read(),
42589
- selectedStore.readSettings(),
42646
+ readNativePool(selectedStore.read()),
42647
+ readNativePoolSettings(selectedStore.readSettings()),
42590
42648
  readNativeRuntime(selectedPaths.runtime, selectedPaths.storageId)
42591
42649
  ]);
42592
42650
  if (read.status !== "ready" || settings.status !== "ready")
@@ -42686,7 +42744,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42686
42744
  for (let attempt = 0;attempt < 4; attempt++) {
42687
42745
  if (attempt)
42688
42746
  await new Promise((resolve23) => setTimeout(resolve23, 10));
42689
- const settings = await readSettings();
42747
+ const settings = await readNativePoolSettings(readSettings());
42690
42748
  if (settings.status !== "ready")
42691
42749
  throw new NativeRuntimeError("publication-refused");
42692
42750
  if (location !== "default") {
@@ -45466,7 +45524,7 @@ var actions = Object.freeze([
45466
45524
  group: "Accounts",
45467
45525
  label: "Disconnect from the vault",
45468
45526
  destructive: true,
45469
- confirm: "Disconnect this host from the vault and return to local accounts? The vault keeps this host's enrollment approved until an operator revokes it there.",
45527
+ confirm: "Disconnect this host from the vault and return to local accounts? Pi's previous saved Claude sign-in is not restored; sign in again after disconnecting. The vault keeps this host's enrollment approved until an operator revokes it there.",
45470
45528
  interactive: true,
45471
45529
  headlessRefusal: "interactive-required",
45472
45530
  parameters: []
@@ -46107,12 +46165,7 @@ function plan(actions2, rawRequest, rawContext) {
46107
46165
  options
46108
46166
  };
46109
46167
  }
46110
- var DISCONNECT_RESULTS = new Set([
46111
- "disconnected",
46112
- "idle",
46113
- "busy",
46114
- "conflict"
46115
- ]);
46168
+ var DISCONNECT_RESULTS = new Set(["disconnected", "idle", "busy"]);
46116
46169
  function readOutcome(action, outcome) {
46117
46170
  const fields3 = readPlain(outcome, ["ok", "text"]);
46118
46171
  const ok = fields3 instanceof Map ? fields3.get("ok") : undefined;
@@ -46144,11 +46197,7 @@ function disconnectFailureCode(error) {
46144
46197
  case "unsafe-path":
46145
46198
  return "disconnect-unsafe-file";
46146
46199
  case "invalid-auth":
46147
- case "invalid-stash":
46148
- case "missing-stash":
46149
46200
  return "disconnect-pi-recovery";
46150
- case "conflict":
46151
- return "disconnect-conflict";
46152
46201
  case "lock-timeout":
46153
46202
  case "lock-compromised":
46154
46203
  return "disconnect-busy";
@@ -47022,18 +47071,12 @@ var DISCONNECT_OUTCOMES = {
47022
47071
  ok: false,
47023
47072
  code: "busy",
47024
47073
  text: "Vault disconnect could not finish because another process is changing this host's enrollment. Try again."
47025
- },
47026
- conflict: {
47027
- ok: false,
47028
- code: "conflict",
47029
- text: "Disconnect stopped: this host already has a different stored sign-in, so it and the sign-in saved when the host joined the vault were both kept, and the vault connection remains. Resolve the two sign-ins with offline setup."
47030
47074
  }
47031
47075
  };
47032
47076
  var DISCONNECT_FAILURES = {
47033
47077
  "disconnect-unsafe-file": "Check file ownership, private permissions, and safe storage. Then try Disconnect again. Do not delete enrollment files by hand.",
47034
47078
  "disconnect-wrong-consumer": "The enrollment belongs to another host or plugin. Check this host’s enrollment path. Then try Disconnect again. Do not delete another host’s enrollment.",
47035
- "disconnect-pi-recovery": "Repair the Pi sign-in and its private recovery copy with offline setup. Keep both files. Then try Disconnect again.",
47036
- "disconnect-conflict": "Resolve the stored Pi sign-in and its private recovery copy with offline setup. Keep both sign-ins. Then try Disconnect again.",
47079
+ "disconnect-pi-recovery": "Repair Pi’s auth file with offline setup. Then try Disconnect again. No saved sign-in will be restored.",
47037
47080
  "disconnect-busy": "Stop other setup or disconnect attempts. Then try Disconnect again.",
47038
47081
  "disconnect-io": "Check file access and free disk space. Then try Disconnect again.",
47039
47082
  "execution-failed": "Check this host’s vault connection and file access. Then try Disconnect again.",
@@ -47055,6 +47098,11 @@ ${result.instructions.join(`
47055
47098
  `)}`
47056
47099
  };
47057
47100
  case "disconnect":
47101
+ if (host2 === "pi" && (result.result === "disconnected" || result.result === "idle"))
47102
+ return {
47103
+ ok: true,
47104
+ text: "Pi is disconnected from the vault. Its previous saved Claude sign-in is not restored. Sign in again in Pi to use local authentication."
47105
+ };
47058
47106
  return DISCONNECT_OUTCOMES[result.result];
47059
47107
  case "failed":
47060
47108
  if (result.action === "vault-disconnect")
@@ -47357,7 +47405,6 @@ function placeholderSecret(integrationID) {
47357
47405
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
47358
47406
  }
47359
47407
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
47360
- import { createHash as createHash26 } from "node:crypto";
47361
47408
  import { constants as constants5 } from "node:fs";
47362
47409
  import { lstat as lstat21, mkdir as mkdir17, open as open14, unlink as unlink11 } from "node:fs/promises";
47363
47410
  import { dirname as dirname24, resolve as resolve23 } from "node:path";
@@ -47468,12 +47515,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
47468
47515
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
47469
47516
  compromise();
47470
47517
  }
47471
- function schedule2(delay4 = UPDATE) {
47518
+ function schedule2(delay5 = UPDATE) {
47472
47519
  if (released)
47473
47520
  return;
47474
47521
  timer = setTimeout(() => {
47475
47522
  update();
47476
- }, delay4);
47523
+ }, delay5);
47477
47524
  timer.unref();
47478
47525
  }
47479
47526
  function retry(error) {
@@ -47627,28 +47674,17 @@ function rootSpans(text6) {
47627
47674
  function object4(value) {
47628
47675
  return typeof value === "object" && value !== null && !Array.isArray(value);
47629
47676
  }
47630
- function canonical2(value) {
47631
- if (Array.isArray(value))
47632
- return `[${value.map(canonical2).join(",")}]`;
47633
- if (object4(value)) {
47634
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical2(value[key])}`).join(",")}}`;
47635
- }
47636
- return JSON.stringify(value);
47637
- }
47638
- function digest2(value) {
47639
- return createHash26("sha256").update(canonical2(value)).digest("hex");
47640
- }
47641
47677
  function code(error) {
47642
47678
  return object4(error) ? error.code : undefined;
47643
47679
  }
47644
- async function safeRead(path2, privateFile = false, afterReadCheck) {
47680
+ async function safeRead(path2, afterReadCheck) {
47645
47681
  if (windowsPrivateFiles) {
47646
47682
  try {
47647
47683
  await afterReadCheck?.(path2);
47648
47684
  const bytes = await readPrivateBuffer(path2, true);
47649
47685
  const text6 = bytes.toString("utf8");
47650
47686
  if (!bytes.equals(Buffer.from(text6)))
47651
- throw new PiSlotError(privateFile ? "invalid-stash" : "invalid-auth");
47687
+ throw new PiSlotError("invalid-auth");
47652
47688
  return text6;
47653
47689
  } catch (error) {
47654
47690
  if (code(error) === "ENOENT")
@@ -47660,7 +47696,7 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
47660
47696
  try {
47661
47697
  file = await open14(path2, constants5.O_RDONLY | constants5.O_NOFOLLOW);
47662
47698
  const stat14 = await file.stat();
47663
- if (!stat14.isFile() || privateFile && (stat14.mode & 511) !== 384) {
47699
+ if (!stat14.isFile()) {
47664
47700
  throw new PiSlotError("unsafe-path");
47665
47701
  }
47666
47702
  await afterReadCheck?.(path2);
@@ -47671,7 +47707,7 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
47671
47707
  const bytes = await file.readFile();
47672
47708
  const text6 = bytes.toString("utf8");
47673
47709
  if (!bytes.equals(Buffer.from(text6))) {
47674
- throw new PiSlotError(privateFile ? "invalid-stash" : "invalid-auth");
47710
+ throw new PiSlotError("invalid-auth");
47675
47711
  }
47676
47712
  return text6;
47677
47713
  } catch (error) {
@@ -47706,10 +47742,6 @@ function parseAuth(text6, provider) {
47706
47742
  throw new PiSlotError("invalid-auth");
47707
47743
  }
47708
47744
  }
47709
- function entryText(auth) {
47710
- const value = auth.property?.value;
47711
- return value ? auth.text.slice(value.offset, value.offset + value.length) : null;
47712
- }
47713
47745
  function replaceEntry(auth, provider, next) {
47714
47746
  const { text: text6, root, property } = auth;
47715
47747
  const properties = root.children ?? [];
@@ -47768,24 +47800,8 @@ function createPiSlot(options, onStep, hooks) {
47768
47800
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
47769
47801
  throw new PiSlotError("invalid-options");
47770
47802
  }
47771
- const authIdentity = digest2(authPath);
47772
- const placeholderIdentity = digest2(placeholderKey);
47773
47803
  const placeholder = { type: "api_key", key: placeholderKey };
47774
- const isPlaceholder = (entry2) => digest2(entry2) === digest2(placeholder);
47775
- async function loadStash() {
47776
- const text6 = await safeRead(stashPath, true, hooks?.afterReadCheck);
47777
- if (text6 === undefined)
47778
- return;
47779
- try {
47780
- const stash = JSON.parse(text6);
47781
- if (stash.version !== 1 || stash.provider !== provider || stash.authIdentity !== authIdentity || stash.placeholderIdentity !== placeholderIdentity || stash.entry !== null && !object4(stash.entry) || stash.sha256 !== digest2(stash.entry) || (stash.entry === null ? stash.entryJson !== null : typeof stash.entryJson !== "string" || digest2(JSON.parse(stash.entryJson)) !== stash.sha256)) {
47782
- throw new Error;
47783
- }
47784
- return stash;
47785
- } catch {
47786
- throw new PiSlotError("invalid-stash");
47787
- }
47788
- }
47804
+ const isPlaceholder = (entry2) => entry2 !== null && Object.keys(entry2).length === 2 && entry2.type === placeholder.type && entry2.key === placeholder.key;
47789
47805
  async function locked(fn) {
47790
47806
  let release2;
47791
47807
  let assertFresh;
@@ -47832,11 +47848,25 @@ function createPiSlot(options, onStep, hooks) {
47832
47848
  }
47833
47849
  }
47834
47850
  async function load() {
47835
- const auth = parseAuth(await safeRead(authPath, false, hooks?.afterReadCheck) ?? "{}", provider);
47836
- const stash = await loadStash();
47837
- return { auth, stash };
47851
+ return parseAuth(await safeRead(authPath, hooks?.afterReadCheck) ?? "{}", provider);
47838
47852
  }
47839
47853
  async function deleteStash(assertLock) {
47854
+ try {
47855
+ const file = await lstat21(stashPath);
47856
+ if (!file.isFile())
47857
+ throw new PiSlotError("unsafe-path");
47858
+ } catch (error) {
47859
+ if (code(error) === "ENOENT")
47860
+ return;
47861
+ throw error;
47862
+ }
47863
+ if (windowsPrivateFiles)
47864
+ await verifySafeDirectory(dirname24(stashPath));
47865
+ else {
47866
+ const dir = await lstat21(dirname24(stashPath));
47867
+ if (!dir.isDirectory() || (dir.mode & 511) !== 448)
47868
+ throw new PiSlotError("unsafe-path");
47869
+ }
47840
47870
  assertLock();
47841
47871
  await unlink11(stashPath);
47842
47872
  await syncDir(dirname24(stashPath));
@@ -47844,58 +47874,27 @@ function createPiSlot(options, onStep, hooks) {
47844
47874
  }
47845
47875
  return {
47846
47876
  inspect: () => locked(async () => {
47847
- const { auth, stash } = await load();
47848
- const slot = isPlaceholder(auth.entry) ? "placeholder" : auth.entry === null ? "empty" : !stash || digest2(auth.entry) === stash.sha256 ? "original" : "foreign";
47849
- return { slot, stash: stash ? "valid" : "missing" };
47877
+ const auth = await load();
47878
+ const slot = isPlaceholder(auth.entry) ? "placeholder" : auth.entry === null ? "empty" : "original";
47879
+ return { slot };
47850
47880
  }),
47851
47881
  enterVault: () => locked(async (assertLock) => {
47852
- const { auth, stash } = await load();
47853
- if (isPlaceholder(auth.entry)) {
47854
- if (!stash)
47855
- throw new PiSlotError("missing-stash");
47856
- return;
47857
- }
47858
- if (stash && digest2(auth.entry) !== stash.sha256)
47859
- throw new PiSlotError("conflict");
47860
- if (!stash) {
47861
- if (windowsPrivateFiles)
47862
- await ensurePrivateDirectory(dirname24(stashPath));
47863
- else {
47864
- await mkdir17(dirname24(stashPath), { recursive: true, mode: 448 });
47865
- const dir = await lstat21(dirname24(stashPath));
47866
- if (!dir.isDirectory() || (dir.mode & 511) !== 448)
47867
- throw new PiSlotError("unsafe-path");
47868
- }
47869
- const saved = {
47870
- version: 1,
47871
- provider,
47872
- authIdentity,
47873
- placeholderIdentity,
47874
- entry: auth.entry,
47875
- entryJson: entryText(auth),
47876
- sha256: digest2(auth.entry)
47877
- };
47878
- await atomicWrite(stashPath, JSON.stringify(saved), assertLock, hooks?.beforeRename);
47879
- onStep?.("stash-written");
47882
+ const auth = await load();
47883
+ if (!isPlaceholder(auth.entry)) {
47884
+ await atomicWrite(authPath, replaceEntry(auth, provider, JSON.stringify(placeholder)), assertLock, hooks?.beforeRename);
47885
+ onStep?.("auth-written");
47880
47886
  }
47881
- await atomicWrite(authPath, replaceEntry(auth, provider, JSON.stringify(placeholder)), assertLock, hooks?.beforeRename);
47882
- onStep?.("auth-written");
47887
+ await deleteStash(assertLock);
47883
47888
  }),
47884
47889
  exitVault: () => locked(async (assertLock) => {
47885
- const { auth, stash } = await load();
47886
- if (!stash) {
47887
- if (isPlaceholder(auth.entry))
47888
- throw new PiSlotError("missing-stash");
47889
- return "nothing-to-do";
47890
- }
47891
- if (isPlaceholder(auth.entry)) {
47892
- await atomicWrite(authPath, replaceEntry(auth, provider, stash.entryJson), assertLock, hooks?.beforeRename);
47890
+ const auth = await load();
47891
+ const cleared = isPlaceholder(auth.entry);
47892
+ if (cleared) {
47893
+ await atomicWrite(authPath, replaceEntry(auth, provider, null), assertLock, hooks?.beforeRename);
47893
47894
  onStep?.("auth-written");
47894
- } else if (digest2(auth.entry) !== stash.sha256) {
47895
- return "conflict";
47896
47895
  }
47897
47896
  await deleteStash(assertLock);
47898
- return "restored";
47897
+ return cleared ? "cleared" : "nothing-to-do";
47899
47898
  })
47900
47899
  };
47901
47900
  }
@@ -47914,8 +47913,8 @@ function openNativePiAuthSlot(options) {
47914
47913
  async function disconnectNativeVaultForHost(options) {
47915
47914
  if (isVaultHosted())
47916
47915
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
47917
- if (options.host === "pi" && await options.slot.exitVault() === "conflict")
47918
- return "conflict";
47916
+ if (options.host === "pi")
47917
+ await options.slot.exitVault();
47919
47918
  const paths2 = getHostClaustrumEnrollmentPaths(options.host, options.env);
47920
47919
  const result = await disconnectClaustrumEnrollment(paths2, `anthropic-auth-${options.host}`);
47921
47920
  if (result === "disconnected" || result === "idle")
@@ -47957,7 +47956,8 @@ function createNativeVaultNoRouteResponse(input) {
47957
47956
  routeAccountIds: active2.filter((account) => account.quota).map((account) => account.id),
47958
47957
  storage: snapshot.policyStorage,
47959
47958
  sessionId: input.sessionId,
47960
- vaultPolicyLimits: [...limits]
47959
+ vaultPolicyLimits: [...limits],
47960
+ waitForReset: input.waitForReset && active2.every((account) => account.quota)
47961
47961
  });
47962
47962
  }
47963
47963
 
@@ -48070,7 +48070,7 @@ function requestMethod(input) {
48070
48070
  return input instanceof Request ? input.method : "GET";
48071
48071
  }
48072
48072
  // src/prime.ts
48073
- import { createHash as createHash27 } from "node:crypto";
48073
+ import { createHash as createHash26 } from "node:crypto";
48074
48074
  import * as fs4 from "node:fs";
48075
48075
  import { mkdir as mkdir18, readdir as readdir7, rm as rm10, stat as stat14, writeFile as writeFile6 } from "node:fs/promises";
48076
48076
  import { tmpdir as tmpdir8 } from "node:os";
@@ -48279,7 +48279,7 @@ function primeStorageFingerprint(storagePath) {
48279
48279
  throw error;
48280
48280
  canonicalPath3 = absolutePath;
48281
48281
  }
48282
- return createHash27("sha256").update(canonicalPath3).digest("hex").slice(0, 12);
48282
+ return createHash26("sha256").update(canonicalPath3).digest("hex").slice(0, 12);
48283
48283
  }
48284
48284
  function primeMarkerNamespaceDir(markerDir, storagePath) {
48285
48285
  return join30(markerDir, primeStorageFingerprint(storagePath));
@@ -48602,8 +48602,8 @@ class PrimeManager {
48602
48602
  return [markerPath];
48603
48603
  const verifiedPath = this.verifiedMarkerPath(accountIdentity, resetsAtEpochMs);
48604
48604
  if (resetsAtEpochMs === undefined) {
48605
- const digest3 = createHash27("sha256").update(accountIdentity).digest("hex");
48606
- if ((await this.readMarkerNames(this.verifiedMarkerDir())).some((name) => name.startsWith(`${digest3}-`)))
48605
+ const digest2 = createHash26("sha256").update(accountIdentity).digest("hex");
48606
+ if ((await this.readMarkerNames(this.verifiedMarkerDir())).some((name) => name.startsWith(`${digest2}-`)))
48607
48607
  return null;
48608
48608
  }
48609
48609
  if (!await this.tryClaimPath(this.verifiedMarkerDir(), verifiedPath))
@@ -48614,8 +48614,8 @@ class PrimeManager {
48614
48614
  return join30(this.options.markerDir ?? defaultMarkerDir(), "accounts");
48615
48615
  }
48616
48616
  verifiedMarkerPath(accountIdentity, resetsAtEpochMs) {
48617
- const digest3 = createHash27("sha256").update(accountIdentity).digest("hex");
48618
- return join30(this.verifiedMarkerDir(), `${digest3}-${resetsAtEpochMs ?? "bootstrap"}`);
48617
+ const digest2 = createHash26("sha256").update(accountIdentity).digest("hex");
48618
+ return join30(this.verifiedMarkerDir(), `${digest2}-${resetsAtEpochMs ?? "bootstrap"}`);
48619
48619
  }
48620
48620
  async readMarkerNames(dir) {
48621
48621
  try {
@@ -51390,12 +51390,12 @@ function expectRecord(sub, want) {
51390
51390
  }
51391
51391
  function expectDigest(path2, sha256) {
51392
51392
  return async () => {
51393
- const digest3 = await digestFile(path2);
51393
+ const digest2 = await digestFile(path2);
51394
51394
  if (sha256 === null)
51395
- return digest3.status === "absent" ? undefined : "it exists";
51396
- if (digest3.status === "file" && digest3.sha256 === sha256)
51395
+ return digest2.status === "absent" ? undefined : "it exists";
51396
+ if (digest2.status === "file" && digest2.sha256 === sha256)
51397
51397
  return;
51398
- return digest3.status === "absent" ? "it is missing" : "its bytes changed";
51398
+ return digest2.status === "absent" ? "it is missing" : "its bytes changed";
51399
51399
  };
51400
51400
  }
51401
51401
  function expectTombstone(path2, attempt) {
@@ -51465,8 +51465,8 @@ async function rollbackPreparing(record17, dataset, ctx) {
51465
51465
  await removeOwnStaging(relocatingPath(file.to, attempt));
51466
51466
  if (file.sha256 === null)
51467
51467
  continue;
51468
- const digest3 = await digestFile(file.to);
51469
- if (digest3.status !== "file" || digest3.sha256 !== file.sha256)
51468
+ const digest2 = await digestFile(file.to);
51469
+ if (digest2.status !== "file" || digest2.sha256 !== file.sha256)
51470
51470
  continue;
51471
51471
  if (!await exists5(file.from))
51472
51472
  continue;
@@ -51531,14 +51531,14 @@ async function cleanupOldCopies(record17, dataset, ctx) {
51531
51531
  const path2 = role === "journal" ? movingJournalPath(file.from, record17.attempt) : file.from;
51532
51532
  await ctx.stack.assertAll();
51533
51533
  const credential2 = CREDENTIAL_AUTHORITY_ROLES.includes(role);
51534
- let digest3;
51534
+ let digest2;
51535
51535
  try {
51536
- digest3 = await digestFile(path2);
51536
+ digest2 = await digestFile(path2);
51537
51537
  } catch (error) {
51538
51538
  if (!credential2)
51539
51539
  throw error;
51540
51540
  }
51541
- if (digest3?.status === "absent") {} else if (digest3 !== undefined && file.sha256 !== null && digest3.sha256 === file.sha256) {
51541
+ if (digest2?.status === "absent") {} else if (digest2 !== undefined && file.sha256 !== null && digest2.sha256 === file.sha256) {
51542
51542
  await owned2(ctx, { kind: "unlink", path: path2 }, expectDigest(path2, file.sha256));
51543
51543
  } else if (credential2) {
51544
51544
  conflict.push({ old: path2, new: file.to });
@@ -51835,9 +51835,9 @@ async function finishRestoreRetirement(record17, dataset, ctx) {
51835
51835
  const kept = [...record17.restore?.kept ?? []];
51836
51836
  for (const file of restore.files) {
51837
51837
  try {
51838
- const digest3 = await digestFile(file.to);
51839
- if (digest3.status === "file") {
51840
- if (digest3.sha256 === file.sha256)
51838
+ const digest2 = await digestFile(file.to);
51839
+ if (digest2.status === "file") {
51840
+ if (digest2.sha256 === file.sha256)
51841
51841
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
51842
51842
  else
51843
51843
  throw new Error("its bytes changed after they were restored");
@@ -52054,19 +52054,19 @@ async function startRestore(record17, dataset, ctx, options) {
52054
52054
  const attempt = randomUUID28();
52055
52055
  const files = [];
52056
52056
  for (const slot of dataset.slots) {
52057
- let digest3;
52057
+ let digest2;
52058
52058
  try {
52059
- digest3 = await digestFile(slot.to);
52059
+ digest2 = await digestFile(slot.to);
52060
52060
  } catch (error) {
52061
52061
  throw refused2(`${slot.to} is not a regular file, so anthropic-auth won't restore it; move it aside, then run ${RESTORE_LEGACY_COMMAND} again.`, [slot.to], error);
52062
52062
  }
52063
- if (digest3.status !== "file")
52063
+ if (digest2.status !== "file")
52064
52064
  continue;
52065
52065
  files.push({
52066
52066
  role: slot.role,
52067
52067
  from: slot.from,
52068
52068
  to: slot.to,
52069
- sha256: digest3.sha256,
52069
+ sha256: digest2.sha256,
52070
52070
  staging: restoreStagingPath(slot.from, attempt)
52071
52071
  });
52072
52072
  }
@@ -53172,6 +53172,7 @@ export {
53172
53172
  resolveClaudeModelCapabilities,
53173
53173
  resolveClaudeCodeIdentity,
53174
53174
  resolveClaudeCodeAccountIdentity,
53175
+ resetWaitDelayMs,
53175
53176
  resetVaultHostAuthorityForTests,
53176
53177
  resetStateLayoutDecisionsForTests,
53177
53178
  resetProcessStateLayoutsForTests,
@@ -53327,6 +53328,7 @@ export {
53327
53328
  mergeHeaderQuotaForPersistence,
53328
53329
  mergeAnthropicBetas,
53329
53330
  markSettingsImportPending,
53331
+ markResetWaitResponse,
53330
53332
  mapSettingsMoveSources,
53331
53333
  malformedSettingsText,
53332
53334
  lookupGatewaySettingsFile,
@@ -53412,6 +53414,7 @@ export {
53412
53414
  hasPrivateSettingsConfigHome,
53413
53415
  hasNoLocalCredential,
53414
53416
  guardAnthropicStreamResponse,
53417
+ getWaitForReset,
53415
53418
  getThinkingPrefixMismatchBehavior,
53416
53419
  getStickyRoutingStatePath,
53417
53420
  getSettingsStorePaths,
@@ -1,3 +1,3 @@
1
- /** Move a Pi provider slot aside without changing provider or model identifiers. */
1
+ /** Replace a Pi provider login with a vault placeholder without changing provider or model identifiers. */
2
2
  export type { PiSlot, PiSlotErrorCode, PiSlotInspection, PiSlotOptions, } from './slot.js';
3
3
  export { openPiSlot, PiSlotError } from './slot.js';
@@ -1,4 +1,4 @@
1
- export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | 'invalid-stash' | 'unsafe-path' | 'missing-stash' | 'conflict' | 'lock-timeout' | 'lock-compromised' | 'io';
1
+ export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | 'unsafe-path' | 'lock-timeout' | 'lock-compromised' | 'io';
2
2
  /** Errors deliberately contain neither paths nor credentials nor underlying error messages. */
3
3
  export declare class PiSlotError extends Error {
4
4
  readonly code: PiSlotErrorCode;
@@ -10,10 +10,8 @@ export interface PiSlotOptions {
10
10
  authPath: string;
11
11
  provider: string;
12
12
  /**
13
- * Where the provider's original Pi login is kept while the vault serves.
14
- * Put it in a private directory, and give each provider its own file: one
15
- * stash holds one provider's original login, and a second provider writing
16
- * to it would overwrite the first one's backup.
13
+ * Where older versions kept the original Pi login; deleted when found.
14
+ * Keep the same path across upgrades so legacy credentials can be removed.
17
15
  */
18
16
  stashPath: string;
19
17
  /**
@@ -26,13 +24,12 @@ export interface PiSlotOptions {
26
24
  lockTimeoutMs?: number;
27
25
  }
28
26
  export interface PiSlotInspection {
29
- slot: 'original' | 'placeholder' | 'foreign' | 'empty';
30
- stash: 'valid' | 'missing';
27
+ slot: 'original' | 'placeholder' | 'empty';
31
28
  }
32
29
  export interface PiSlot {
33
30
  inspect(): Promise<PiSlotInspection>;
34
31
  enterVault(): Promise<void>;
35
- exitVault(): Promise<'restored' | 'conflict' | 'nothing-to-do'>;
32
+ exitVault(): Promise<'cleared' | 'nothing-to-do'>;
36
33
  }
37
34
  /**
38
35
  * Production entry point. Pi caches which models are usable; after a
@@ -44,7 +41,7 @@ export declare function openPiSlot(options: PiSlotOptions): PiSlot;
44
41
  * Internal test entry point: pause reads, renewals, or renames to simulate races,
45
42
  * and observe durable writes/deletion to simulate crashes. Not a public export.
46
43
  */
47
- export declare function createPiSlot(options: PiSlotOptions, onStep?: (step: 'stash-written' | 'auth-written' | 'stash-deleted') => void, hooks?: {
44
+ export declare function createPiSlot(options: PiSlotOptions, onStep?: (step: 'auth-written' | 'stash-deleted') => void, hooks?: {
48
45
  afterReadCheck?: (path: string) => Promise<void>;
49
46
  onRenew?: (renew: () => Promise<void>) => void;
50
47
  beforeRename?: (path: string) => Promise<void>;
@@ -170,13 +170,11 @@ export type NativeMenuExecutorOptions = {
170
170
  };
171
171
  /**
172
172
  * What a host's vault disconnect reports. `disconnected`: the host is back in
173
- * local custody. `idle`: no active enrollment remains; Pi's saved sign-in may
174
- * still have been restored. `busy`: another process holds the enrollment lock
175
- * and disconnect could not finish. `conflict`:
176
- * the host's stored sign-in could not be restored without overwriting one it
177
- * already has, so both were kept and the enrollment remains.
173
+ * local custody. `idle`: no active enrollment remains. Pi's vault placeholder
174
+ * is cleared in either case, but no discarded sign-in is restored.
175
+ * `busy`: another process holds the enrollment lock and disconnect could not finish.
178
176
  */
179
- export type NativeVaultDisconnectResult = 'disconnected' | 'idle' | 'busy' | 'conflict';
177
+ export type NativeVaultDisconnectResult = 'disconnected' | 'idle' | 'busy';
180
178
  /** The host capability that disconnects this host from the vault. */
181
179
  export type NativeVaultDisconnect = (options: NativeMenuDispatchOptions) => Promise<NativeVaultDisconnectResult>;
182
180
  /** Facts about the invocation that the safety rules depend on. */
@@ -215,7 +213,7 @@ export type NativeMenuExecutionResult = {
215
213
  */
216
214
  readonly status: 'failed';
217
215
  readonly action: NativeMenuDispatchActionId | 'vault-disconnect';
218
- readonly code: 'execution-failed' | 'invalid-outcome' | 'disconnect-unsafe-file' | 'disconnect-wrong-consumer' | 'disconnect-pi-recovery' | 'disconnect-conflict' | 'disconnect-busy' | 'disconnect-io';
216
+ readonly code: 'execution-failed' | 'invalid-outcome' | 'disconnect-unsafe-file' | 'disconnect-wrong-consumer' | 'disconnect-pi-recovery' | 'disconnect-busy' | 'disconnect-io';
219
217
  } | {
220
218
  /** The host's disconnect capability ran and reported this result. */
221
219
  readonly status: 'disconnect';
@@ -1,9 +1,9 @@
1
+ import { type PoolLoad } from "./internal-types/store/index.js";
1
2
  import { type NativeLockEvent } from './native-lock-observer.ts';
2
3
  import { type NativePoolStorePaths } from './pool-store.ts';
3
4
  /**
4
- * A local account could not be authorized because the caller's short wait for
5
- * an account write or a refresh replacing a provider-rejected token expired.
6
- * The shared write or refresh may still finish after the caller stops waiting.
5
+ * An account update prevented a request from reading or authorizing the account
6
+ * within its short wait budget. The shared write or refresh may still finish.
7
7
  *
8
8
  * The request should be retried. `code: 'ECONNRESET'` is how this package
9
9
  * marks an error retryable for its hosts. A host must surface it rather than
@@ -13,10 +13,13 @@ import { type NativePoolStorePaths } from './pool-store.ts';
13
13
  export declare class NativeTransientAccountError extends Error {
14
14
  readonly code: 'ECONNRESET';
15
15
  readonly syscall: 'native-account-update';
16
- constructor();
16
+ readonly poolRead?: true;
17
+ constructor(operation?: 'pool-read');
17
18
  }
18
19
  /** True only for an error Core itself constructed as NativeTransientAccountError. */
19
20
  export declare function isNativeTransientAccountError(value: unknown): value is NativeTransientAccountError;
21
+ export declare function readNativePool(read: Promise<PoolLoad>): Promise<PoolLoad>;
22
+ export declare function readNativePoolSettings<T>(read: Promise<T>): Promise<T>;
20
23
  /**
21
24
  * Wait until no writer holds the pool's store locks, then let them go.
22
25
  *
@@ -26,9 +26,7 @@ export interface NativeUiOptions {
26
26
  /**
27
27
  * Disconnects this host from the vault; while enrolled, this is the host's
28
28
  * only enrollment action. Before ending the enrollment, the callback
29
- * restores any host sign-in set aside when the host joined the vault. If
30
- * that restore would overwrite a sign-in the host already has, the callback
31
- * reports `conflict` and leaves the enrollment in place. Every host must
29
+ * clears Pi's vault placeholder without restoring any sign-in. Every host must
32
30
  * supply it: a host enrolled in the vault, or with an unreadable
33
31
  * enrollment, always needs a way back to local accounts.
34
32
  */
@@ -6,14 +6,14 @@ export interface NativePiAuthSlotOptions {
6
6
  authPath: string;
7
7
  env?: NodeJS.ProcessEnv;
8
8
  }
9
- /** Setup and disconnect must use the same host auth file, private stash and inert API-key marker. */
9
+ /** Keep the legacy stash path stable so setup and disconnect remove old saved credentials. */
10
10
  export declare function nativePiAuthSlotPaths(options: NativePiAuthSlotOptions): {
11
11
  authPath: string;
12
12
  stashPath: string;
13
13
  provider: string;
14
14
  placeholderKey: string;
15
15
  };
16
- /** Delegate private Pi-auth preservation to the shared locked writer; never create a second host-slot writer. */
16
+ /** Delegate Pi-auth replacement and legacy cleanup to the shared locked writer. */
17
17
  export declare function openNativePiAuthSlot(options: NativePiAuthSlotOptions): PiSlot;
18
18
  export type NativeVaultDisconnectOptions = {
19
19
  host: 'opencode';
@@ -23,11 +23,10 @@ export type NativeVaultDisconnectOptions = {
23
23
  env?: NodeJS.ProcessEnv;
24
24
  slot: Pick<PiSlot, 'exitVault'>;
25
25
  };
26
- export type NativeVaultDisconnectResult = 'disconnected' | 'idle' | 'busy' | 'conflict';
26
+ export type NativeVaultDisconnectResult = 'disconnected' | 'idle' | 'busy';
27
27
  /**
28
- * Restore Pi's stored authentication before removing this host's enrollment.
29
- * A conflicting replacement belongs to the user: leave both it and enrollment
30
- * intact rather than selecting local custody with unresolved recovery data.
28
+ * Clear Pi's vault placeholder before removing this host's enrollment.
29
+ * No saved sign-in is restored; a new sign-in made through Pi is left alone.
31
30
  * OpenCode authentication is never changed by this operation.
32
31
  */
33
32
  export declare function disconnectNativeVaultForHost(options: NativeVaultDisconnectOptions): Promise<NativeVaultDisconnectResult>;
@@ -7,6 +7,7 @@ export declare function createNativeVaultNoRouteResponse(input: {
7
7
  policies?: ReadonlyMap<string, NativeAccountPolicy>;
8
8
  sticky?: boolean;
9
9
  sessionId?: string | null;
10
+ waitForReset?: boolean;
10
11
  }): Response;
11
12
  type QuotaPolicyBody = {
12
13
  type: 'error';
package/dist/routing.d.ts CHANGED
@@ -5,6 +5,7 @@ export declare const DEFAULT_ROUTING_MODE: RoutingMode;
5
5
  export declare const MAX_SAME_ACCOUNT_WAITS: readonly ['0', '15', 'max'];
6
6
  export type MaxSameAccountWait = (typeof MAX_SAME_ACCOUNT_WAITS)[number];
7
7
  export declare const DEFAULT_MAX_SAME_ACCOUNT_WAIT: MaxSameAccountWait;
8
+ export declare function getWaitForReset(storage: AccountSettingsReaderInput | null): boolean;
8
9
  export declare function getMaxSameAccountWait(storage: AccountSettingsReaderInput | null): MaxSameAccountWait;
9
10
  type RoutingCommandAction = {
10
11
  type: 'status';
@@ -24,6 +24,17 @@ export declare const settingsDefinition: import("./internal-types/settings/index
24
24
  }>;
25
25
  readonly default: "15m";
26
26
  };
27
+ readonly wait_for_reset: {
28
+ readonly hosts: 'both';
29
+ readonly project: 'user-only';
30
+ readonly overrides: {
31
+ readonly host: true;
32
+ };
33
+ readonly value: Readonly<{
34
+ readonly kind: 'boolean';
35
+ }>;
36
+ readonly default: false;
37
+ };
27
38
  readonly fallback_on: {
28
39
  readonly hosts: 'both';
29
40
  readonly project: 'user-only';
@@ -469,13 +480,14 @@ export type SettingsKey = keyof typeof settingsDefinition.settings;
469
480
  * them, so the one-time move never reads or writes them, and the `/claude`
470
481
  * menu never writes them.
471
482
  */
472
- export declare const SETTINGS_FILE_ONLY_KEYS: readonly ["gateway_url", "gateway_headers"];
483
+ export declare const SETTINGS_FILE_ONLY_KEYS: readonly ["wait_for_reset", "gateway_url", "gateway_headers"];
473
484
  /** Empty: no Pi-specific default is needed beyond per-reader default/on/off handling. */
474
485
  export declare const SETTINGS_PI_DIFFERING_FIELDS: readonly [];
475
486
  /** Names the current readers whose absence behavior determines each schema default. */
476
487
  export declare const SETTINGS_DEFAULT_READERS: {
477
488
  readonly routing_mode: 'packages/core/src/routing.ts:getRoutingMode';
478
489
  readonly max_same_account_wait: 'packages/core/src/routing.ts:getMaxSameAccountWait';
490
+ readonly wait_for_reset: 'packages/core/src/routing.ts:getWaitForReset';
479
491
  readonly fallback_on: 'packages/core/src/accounts.ts:shouldFallbackStatus';
480
492
  readonly refresh_enabled: 'packages/opencode/src/index.ts:mainRefreshEnabled';
481
493
  readonly refresh_interval_minutes: 'packages/core/src/accounts.ts:getRefreshIntervalMs';
@@ -75,6 +75,7 @@ export declare function createStickyNoRouteResponse(input: {
75
75
  storage?: AccountStorage | null;
76
76
  sessionId?: string | null;
77
77
  vaultPolicyLimits?: readonly NativeQuotaPolicyLimit[];
78
+ waitForReset?: boolean;
78
79
  modelId?: string;
79
80
  now?: number;
80
81
  }): Response;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.15.2",
3
+ "version": "2.16.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,7 +31,7 @@
31
31
  "prepublishOnly": "bun run build"
32
32
  },
33
33
  "devDependencies": {
34
- "@cortexkit/common-auth": "0.52.1"
34
+ "@cortexkit/common-auth": "0.54.1"
35
35
  },
36
36
  "dependencies": {
37
37
  "@cortexkit/claustrum-client": "0.18.0",
@@ -85,6 +85,28 @@
85
85
  }
86
86
  ]
87
87
  },
88
+ "wait_for_reset": {
89
+ "anyOf": [
90
+ {
91
+ "type": "boolean"
92
+ },
93
+ {
94
+ "type": "object",
95
+ "properties": {
96
+ "default": {
97
+ "type": "boolean"
98
+ },
99
+ "opencode": {
100
+ "type": "boolean"
101
+ },
102
+ "pi": {
103
+ "type": "boolean"
104
+ }
105
+ },
106
+ "additionalProperties": false
107
+ }
108
+ ]
109
+ },
88
110
  "fallback_on": {
89
111
  "anyOf": [
90
112
  {