@cortexkit/anthropic-auth-core 2.16.3 → 2.16.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2627,6 +2627,8 @@ async function request(operation) {
2627
2627
  function wrapHostClient(client) {
2628
2628
  const watchScoped = client.watchScoped?.bind(client);
2629
2629
  const reportUsageScoped = client.reportUsageScoped?.bind(client);
2630
+ const reportCondition = client.reportCondition?.bind(client);
2631
+ const clearCondition = client.clearCondition?.bind(client);
2630
2632
  return {
2631
2633
  listScoped: (...args) => request(() => client.listScoped(...args)),
2632
2634
  getScoped: (...args) => request(() => client.getScoped(...args)),
@@ -2647,6 +2649,12 @@ function wrapHostClient(client) {
2647
2649
  ...reportUsageScoped && {
2648
2650
  reportUsageScoped: (...args) => request(() => reportUsageScoped(...args))
2649
2651
  },
2652
+ ...reportCondition && {
2653
+ reportCondition: (...args) => request(() => reportCondition(...args))
2654
+ },
2655
+ ...clearCondition && {
2656
+ clearCondition: (...args) => request(() => clearCondition(...args))
2657
+ },
2650
2658
  ...client.insula && {
2651
2659
  insula: wrapInsula(client.insula)
2652
2660
  }
@@ -3732,6 +3740,27 @@ function rowFactsOf(row, { includeProviderIds = true } = {}) {
3732
3740
  authMethod: metadata.authMethod
3733
3741
  };
3734
3742
  }
3743
+ function isVaultConditionReason(reason) {
3744
+ return reason === "provider_verification_required" || reason === "provider_ineligible";
3745
+ }
3746
+ function vaultConditionOf(row) {
3747
+ const condition = row.condition;
3748
+ if (!condition)
3749
+ return;
3750
+ const { reason, sinceMs } = condition;
3751
+ if (isVaultConditionReason(reason) && Number.isSafeInteger(sinceMs) && sinceMs > 0)
3752
+ return Object.freeze({ reason, sinceMs });
3753
+ return;
3754
+ }
3755
+ function httpsActionUrl(actionUrl) {
3756
+ if (typeof actionUrl !== "string")
3757
+ return;
3758
+ try {
3759
+ if (new URL(actionUrl).protocol === "https:")
3760
+ return actionUrl;
3761
+ } catch {}
3762
+ return;
3763
+ }
3735
3764
  function grantReachOf(listed) {
3736
3765
  const { grants, grantTuples } = listed;
3737
3766
  if (grants === undefined || grantTuples === undefined)
@@ -3752,6 +3781,10 @@ class ClaustrumScopedCustody {
3752
3781
  #logger;
3753
3782
  #provenance = new WeakMap;
3754
3783
  #reports = new WeakMap;
3784
+ #conditionReports = new Map;
3785
+ #conditionClears = new Map;
3786
+ #conditionsUnsupported = false;
3787
+ #pendingConditionCalls = 0;
3755
3788
  #kept = new Map;
3756
3789
  #keptAttempts = new WeakMap;
3757
3790
  #usage;
@@ -3769,8 +3802,9 @@ class ClaustrumScopedCustody {
3769
3802
  #probeDelay = 2000;
3770
3803
  #closed = false;
3771
3804
  #discoveredView;
3805
+ #discoveredConditions = new Map;
3772
3806
  #watches = new Set;
3773
- #tokenReads = new Set;
3807
+ #shutdownWork = new Set;
3774
3808
  #warnShutdown;
3775
3809
  #onDrainTimeout;
3776
3810
  #disposing;
@@ -3820,6 +3854,7 @@ class ClaustrumScopedCustody {
3820
3854
  if (hasVaultHost() && !isVaultHostClient(next))
3821
3855
  throw new ClaustrumUnreachableError;
3822
3856
  this.#client = next;
3857
+ this.#conditionsUnsupported = false;
3823
3858
  for (const watch of this.#watches)
3824
3859
  watch.restart();
3825
3860
  }
@@ -3886,12 +3921,12 @@ class ClaustrumScopedCustody {
3886
3921
  phase: "token read begin"
3887
3922
  });
3888
3923
  const pending = this.#readToken();
3889
- this.#tokenReads.add(pending);
3924
+ this.#shutdownWork.add(pending);
3890
3925
  let value;
3891
3926
  try {
3892
3927
  value = await pending;
3893
3928
  } finally {
3894
- this.#tokenReads.delete(pending);
3929
+ this.#shutdownWork.delete(pending);
3895
3930
  if (phaseDiagnostics.hasSubscribers)
3896
3931
  phaseDiagnostics.publish({
3897
3932
  logger: this.#logger,
@@ -3938,6 +3973,11 @@ class ClaustrumScopedCustody {
3938
3973
  async discover(signal) {
3939
3974
  const inventory = await this.#list(signal);
3940
3975
  this.#discoveredView = inventory.view;
3976
+ this.#discoveredConditions.clear();
3977
+ for (const { credentialId, condition } of inventory.credentials) {
3978
+ if (condition)
3979
+ this.#discoveredConditions.set(credentialId, condition);
3980
+ }
3941
3981
  return inventory;
3942
3982
  }
3943
3983
  async#list(signal) {
@@ -4011,6 +4051,7 @@ class ClaustrumScopedCustody {
4011
4051
  });
4012
4052
  continue;
4013
4053
  }
4054
+ const condition = vaultConditionOf(row);
4014
4055
  credentials.push(Object.freeze({
4015
4056
  credentialId: row.id,
4016
4057
  credentialType: type,
@@ -4020,7 +4061,8 @@ class ClaustrumScopedCustody {
4020
4061
  },
4021
4062
  state: row.state,
4022
4063
  ...row.email !== undefined && { email: row.email },
4023
- ...row.orgName !== undefined && { orgName: row.orgName }
4064
+ ...row.orgName !== undefined && { orgName: row.orgName },
4065
+ ...condition && { condition }
4024
4066
  }));
4025
4067
  }
4026
4068
  for (const record2 of skipped)
@@ -4342,6 +4384,81 @@ class ClaustrumScopedCustody {
4342
4384
  throw error;
4343
4385
  }
4344
4386
  }
4387
+ reportCondition(attempt, input) {
4388
+ const provenance = this.#provenance.get(attempt);
4389
+ if (!provenance)
4390
+ return Promise.reject(new ClaustrumConsumerError("no-receipt", "Claustrum condition report requires an original dispatch receipt"));
4391
+ const { reason, providerStatus } = input ?? {};
4392
+ if (this.#closed || this.#keptAttempts.has(attempt) || providerStatus !== 403 || !isVaultConditionReason(reason))
4393
+ return Promise.resolve("skipped");
4394
+ const { credentialId, recordVersion } = attempt;
4395
+ const actionUrl = reason === "provider_verification_required" ? httpsActionUrl(input.actionUrl) : undefined;
4396
+ return this.#conditionOnce(this.#conditionReports, JSON.stringify([credentialId, recordVersion, reason]), { credentialId, recordVersion, reason }, (client) => client.reportCondition?.({
4397
+ credentialId,
4398
+ recordVersion,
4399
+ reason,
4400
+ providerStatus,
4401
+ ...actionUrl !== undefined && { actionUrl },
4402
+ enrollmentToken: provenance.token
4403
+ }));
4404
+ }
4405
+ clearCondition(attempt) {
4406
+ const provenance = this.#provenance.get(attempt);
4407
+ if (!provenance)
4408
+ return Promise.reject(new ClaustrumConsumerError("no-receipt", "Claustrum condition clear requires an original dispatch receipt"));
4409
+ if (this.#closed || this.#keptAttempts.has(attempt))
4410
+ return Promise.resolve("skipped");
4411
+ const { credentialId, recordVersion } = attempt;
4412
+ const condition = this.#discoveredConditions.get(credentialId);
4413
+ if (!condition)
4414
+ return Promise.resolve("skipped");
4415
+ return this.#conditionOnce(this.#conditionClears, JSON.stringify([credentialId, condition.sinceMs]), { credentialId, recordVersion, reason: condition.reason }, (client) => client.clearCondition?.({
4416
+ credentialId,
4417
+ recordVersion,
4418
+ enrollmentToken: provenance.token
4419
+ }));
4420
+ }
4421
+ #conditionOnce(outcomes, key, details, send) {
4422
+ const previous = outcomes.get(key);
4423
+ if (previous)
4424
+ return previous;
4425
+ if (this.#conditionsUnsupported)
4426
+ return Promise.resolve("unsupported");
4427
+ const pending = Promise.resolve().then(async () => {
4428
+ const client = this.#client;
4429
+ if (this.#conditionsUnsupported)
4430
+ return "unsupported";
4431
+ try {
4432
+ const sent = send(client);
4433
+ if (!sent)
4434
+ return "unsupported";
4435
+ if (await sent === false)
4436
+ this.#debugCondition("scoped login condition not cleared", details);
4437
+ return "reported";
4438
+ } catch (error) {
4439
+ if (error instanceof ClaustrumCredentialError5 && error.code === "unknown_method") {
4440
+ if (client === this.#client)
4441
+ this.#conditionsUnsupported = true;
4442
+ return "unsupported";
4443
+ }
4444
+ this.#debugCondition("scoped login condition update failed", details);
4445
+ return "failed";
4446
+ }
4447
+ });
4448
+ outcomes.set(key, pending);
4449
+ this.#pendingConditionCalls++;
4450
+ this.#shutdownWork.add(pending);
4451
+ pending.then(() => {
4452
+ this.#pendingConditionCalls--;
4453
+ this.#shutdownWork.delete(pending);
4454
+ });
4455
+ return pending;
4456
+ }
4457
+ #debugCondition(message, details) {
4458
+ try {
4459
+ this.#logger.debug(message, details);
4460
+ } catch {}
4461
+ }
4345
4462
  watchRoster(options) {
4346
4463
  this.#check();
4347
4464
  const currentView = options.view ?? (() => this.#discoveredView);
@@ -4429,15 +4546,17 @@ class ClaustrumScopedCustody {
4429
4546
  this.#watches.clear();
4430
4547
  this.#kept.clear();
4431
4548
  const usage = this.#usage.close();
4549
+ const keepClientOpen = usage !== undefined || this.#pendingConditionCalls > 0;
4432
4550
  if (usage) {
4433
- this.#tokenReads.add(usage);
4434
- usage.then(() => this.#tokenReads.delete(usage));
4435
- } else
4551
+ this.#shutdownWork.add(usage);
4552
+ usage.then(() => this.#shutdownWork.delete(usage));
4553
+ }
4554
+ if (!keepClientOpen)
4436
4555
  this.#client.close();
4437
- this.#disposing = drainShutdown(this.#tokenReads, (count) => (this.#onDrainTimeout ?? this.#warnShutdown)(count)).finally(() => {
4556
+ this.#disposing = drainShutdown(this.#shutdownWork, (count) => (this.#onDrainTimeout ?? this.#warnShutdown)(count)).finally(() => {
4438
4557
  this.#usage.drop();
4439
4558
  this.#usageServed.clear();
4440
- if (usage)
4559
+ if (keepClientOpen)
4441
4560
  this.#client.close();
4442
4561
  });
4443
4562
  }
@@ -6363,6 +6482,22 @@ class ClaustrumConsumer {
6363
6482
  throw new ClaustrumConsumerError("no-receipt", "Claustrum dispatch receipt has no active owner");
6364
6483
  await this.#custody.reportFailure(attempt, status, source);
6365
6484
  }
6485
+ #issuingCustody(attempt) {
6486
+ const custody = this.#hub ? this.#issuedBy.get(attempt)?.custody : this.#custody;
6487
+ if (!custody)
6488
+ throw new ClaustrumConsumerError("no-receipt", "Claustrum dispatch receipt has no active owner");
6489
+ return custody;
6490
+ }
6491
+ async reportCondition(attempt, input) {
6492
+ if (this.#shutdown.signal.aborted)
6493
+ return "skipped";
6494
+ return this.#issuingCustody(attempt).reportCondition(attempt, input);
6495
+ }
6496
+ async clearCondition(attempt) {
6497
+ if (this.#shutdown.signal.aborted)
6498
+ return "skipped";
6499
+ return this.#issuingCustody(attempt).clearCondition(attempt);
6500
+ }
6366
6501
  async send(routeId, dispatch, options) {
6367
6502
  const signal = options.signal;
6368
6503
  let served = await this.authorize(routeId, signal);
@@ -6885,6 +7020,16 @@ class ClaustrumDiscoveryHub {
6885
7020
  check();
6886
7021
  return custody.reportFailure(attempt, status, source);
6887
7022
  },
7023
+ reportCondition: async (attempt, input) => {
7024
+ if (state.released || generation.ended)
7025
+ return "skipped";
7026
+ return custody.reportCondition(attempt, input);
7027
+ },
7028
+ clearCondition: async (attempt) => {
7029
+ if (state.released || generation.ended)
7030
+ return "skipped";
7031
+ return custody.clearCondition(attempt);
7032
+ },
6888
7033
  reportUsage: (input) => {
6889
7034
  if (!state.released && !generation.ended)
6890
7035
  custody.reportUsage(input);
@@ -7639,8 +7784,6 @@ function candidateView(candidates) {
7639
7784
  accounts.push({ account_id: accountId, credential_id: credentialId });
7640
7785
  }
7641
7786
  }
7642
- if (accounts.length === 0)
7643
- return;
7644
7787
  const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
7645
7788
  `, "utf8")).sort(Buffer.compare);
7646
7789
  const hash2 = createHash4("sha256");
@@ -7732,7 +7875,7 @@ async function askRouting(input) {
7732
7875
  request2.warm_credential = warmCredentialId;
7733
7876
  }
7734
7877
  const candidates = candidateView(input.candidates);
7735
- if (candidates)
7878
+ if (candidates.accounts.length > 0 || request2.mode === "continue")
7736
7879
  request2.candidates = candidates;
7737
7880
  const pending = accountFor.call(handle, request2, { deadlineMs });
7738
7881
  if (!isObject(pending) || typeof pending.then !== "function")
@@ -12605,6 +12748,16 @@ function quotaFieldSource(snapshot, field) {
12605
12748
  return;
12606
12749
  return snapshot.fieldSources?.[field] ?? (snapshot.source === "poll" || snapshot.source === "headers" ? snapshot.source : undefined);
12607
12750
  }
12751
+ function quotaPollCheckedAt(quota) {
12752
+ if (!quota)
12753
+ return 0;
12754
+ const standard = ["five_hour", "seven_day"];
12755
+ const hasPoll = quota.source === "poll" || quotaSnapshotOmitsFiveHour(quota) || quota.scoped !== undefined || quota.extraUsage !== undefined || standard.some((key) => quotaFieldSource(quota, key) === "poll");
12756
+ if (!hasPoll)
12757
+ return 0;
12758
+ const topLevelIsHeader = standard.some((key) => quotaFieldSource(quota, key) === "headers" && quota[key]?.checkedAt === quota.checkedAt);
12759
+ return Math.max(!topLevelIsHeader ? quota.checkedAt ?? 0 : 0, ...(quota.scoped ?? []).map((window) => window.checkedAt), ...standard.map((key) => quotaFieldSource(quota, key) === "poll" ? quota[key]?.checkedAt ?? 0 : 0));
12760
+ }
12608
12761
  function fieldSourcesForMergedQuota(existing, incoming, merged) {
12609
12762
  const fieldSources = {};
12610
12763
  for (const field of QUOTA_FIELD_NAMES) {
@@ -12636,18 +12789,20 @@ function mergeHeaderQuotaForPersistence(existing, incoming) {
12636
12789
  if (!existing || incoming.source !== "headers")
12637
12790
  return incoming;
12638
12791
  const preservePollBinding = existing.bindingWindowSource === "poll";
12792
+ const pollCheckedAt = quotaPollCheckedAt(existing);
12793
+ const preservePollFields = pollCheckedAt > 0 && quotaPollCheckedAt(incoming) <= pollCheckedAt;
12639
12794
  const merged = {
12640
12795
  ...existing,
12641
12796
  ...incoming,
12642
12797
  five_hour: mergeHeaderOwnedWindow(existing, incoming, "five_hour"),
12643
12798
  seven_day: mergeHeaderOwnedWindow(existing, incoming, "seven_day"),
12644
- scoped: mergeHeaderScopedQuota(existing, incoming),
12645
- extraUsage: existing.extraUsage ?? incoming.extraUsage,
12799
+ scoped: preservePollFields && quotaFieldSource(incoming, "scoped") !== "headers" ? existing.scoped : mergeHeaderScopedQuota(existing, incoming),
12800
+ extraUsage: preservePollFields ? existing.extraUsage : existing.extraUsage ?? incoming.extraUsage,
12646
12801
  fallbackAdvised: incoming.fieldSources?.fallbackAdvised !== undefined ? incoming.fallbackAdvised : existing.fallbackAdvised ?? incoming.fallbackAdvised,
12647
12802
  bindingWindow: preservePollBinding ? existing.bindingWindow : incoming.bindingWindow ?? existing.bindingWindow,
12648
12803
  bindingWindowSource: preservePollBinding ? "poll" : incoming.bindingWindowSource ?? existing.bindingWindowSource,
12649
- ...quotaSnapshotOmitsFiveHour(existing) && {
12650
- checkedAt: existing.checkedAt
12804
+ ...pollCheckedAt > 0 && {
12805
+ checkedAt: pollCheckedAt
12651
12806
  }
12652
12807
  };
12653
12808
  const fieldSources = fieldSourcesForMergedQuota(existing, incoming, merged);
@@ -25875,13 +26030,22 @@ var nativeQuotaCodec = {
25875
26030
  return toNativeQuotaMap(mergeHeaderQuotaForPersistence(previous, incoming));
25876
26031
  const previousTime = quotaSnapshotCheckedAt(previous);
25877
26032
  const incomingTime = quotaSnapshotCheckedAt(incoming);
25878
- if (incoming.source === "poll" && incoming.checkedAt !== undefined && previous.checkedAt !== undefined && (previous.source === "poll" || quotaSnapshotOmitsFiveHour(previous)) && incoming.checkedAt < previous.checkedAt)
26033
+ const previousPollAt = quotaPollCheckedAt(previous);
26034
+ if (incoming.source === "poll" && incoming.checkedAt !== undefined && incoming.checkedAt < previousPollAt)
25879
26035
  return toNativeQuotaMap(previous);
25880
26036
  if (incoming.source === "poll" && incoming.seven_day && !incoming.five_hour && incoming.checkedAt !== undefined && incoming.checkedAt > (previous.five_hour?.checkedAt ?? 0) && (previous.source !== "poll" || incoming.checkedAt >= (previous.checkedAt ?? 0)))
25881
26037
  return toNativeQuotaMap(previous.source === "headers" ? mergeHeaderQuotaForPersistence(incoming, {
25882
26038
  ...previous,
25883
- five_hour: undefined
26039
+ five_hour: undefined,
26040
+ scoped: undefined,
26041
+ extraUsage: undefined
25884
26042
  }) : incoming);
26043
+ if (incoming.source === "poll" && incoming.checkedAt !== undefined && previous.source === "headers" && previousPollAt > 0 && previousTime > incomingTime)
26044
+ return toNativeQuotaMap(mergeHeaderQuotaForPersistence(incoming, {
26045
+ ...previous,
26046
+ scoped: undefined,
26047
+ extraUsage: undefined
26048
+ }));
25885
26049
  return toNativeQuotaMap(previousTime > incomingTime || previousTime === incomingTime && previous.source === "poll" && incoming.source !== "poll" ? previous : incoming);
25886
26050
  }
25887
26051
  };
@@ -33125,10 +33289,198 @@ function executeLoggingCommand(input) {
33125
33289
  `);
33126
33290
  }
33127
33291
  // src/message-threads.ts
33292
+ import { createHash as createHash24, randomUUID as randomUUID21 } from "node:crypto";
33293
+
33294
+ // src/message-thread-tail-store.ts
33128
33295
  import { createHash as createHash23, randomUUID as randomUUID20 } from "node:crypto";
33296
+ import { constants as constants4 } from "node:fs";
33297
+ import { lstat as lstat17, mkdir as mkdir14, open as open12, readdir as readdir7, rm as rm9, writeFile as writeFile6 } from "node:fs/promises";
33298
+ import { join as join28 } from "node:path";
33299
+ var FILE2 = /^[a-f0-9]{64}\.json$/;
33300
+ var TEMP2 = /^[a-f0-9]{64}\.json\.[a-f0-9-]+\.tmp$/;
33301
+ var HASH = /^[a-f0-9]{64}$/;
33302
+ var MAX_RECORD_BYTES2 = 4096;
33303
+ var MAX_SESSIONS = 1024;
33304
+ var READ_TIMEOUT_MS = 50;
33305
+ var SWEEP_INTERVAL_MS = 60000;
33306
+ var LONG_LIFETIME_MS = 3600000;
33307
+ function fullCacheTailExpired(tail, now) {
33308
+ return now < tail.acceptedAt || now >= tail.acceptedAt + (tail.control.ttl === "1h" ? LONG_LIFETIME_MS : 300000);
33309
+ }
33310
+ function entryFromBytes(bytes) {
33311
+ if (bytes.length > MAX_RECORD_BYTES2)
33312
+ return;
33313
+ const value = JSON.parse(bytes.toString("utf8"));
33314
+ const tail = value?.tail;
33315
+ if (value?.v !== 1 || typeof value.continued !== "boolean" || !tail || typeof tail.identity !== "string" || !HASH.test(tail.identity) || typeof tail.prefix !== "string" || !HASH.test(tail.prefix) || !Number.isSafeInteger(tail.messageIndex) || tail.messageIndex < 0 || !Array.isArray(tail.blockPath) || !tail.blockPath.length || !tail.blockPath.every((index) => Number.isSafeInteger(index) && index >= 0) || tail.control?.type !== "ephemeral" || tail.control.ttl !== undefined && tail.control.ttl !== "1h" && tail.control.ttl !== "5m" || !Number.isSafeInteger(tail.acceptedAt) || tail.acceptedAt < 0)
33316
+ return;
33317
+ return {
33318
+ continued: value.continued,
33319
+ tail: {
33320
+ identity: tail.identity,
33321
+ messageIndex: tail.messageIndex,
33322
+ blockPath: tail.blockPath,
33323
+ prefix: tail.prefix,
33324
+ control: {
33325
+ type: "ephemeral",
33326
+ ...tail.control.ttl && { ttl: tail.control.ttl }
33327
+ },
33328
+ acceptedAt: tail.acceptedAt
33329
+ }
33330
+ };
33331
+ }
33332
+
33333
+ class MessageThreadTailStore {
33334
+ now;
33335
+ directory;
33336
+ writes = Promise.resolve();
33337
+ nextSweep = 0;
33338
+ constructor(host, root = getHostDataHome(), now = Date.now) {
33339
+ this.now = now;
33340
+ this.directory = join28(root, "cortexkit", "anthropic-auth", "thread-tails", host);
33341
+ }
33342
+ pathFor(session) {
33343
+ const key = createHash23("sha256").update(session).digest("hex");
33344
+ return join28(this.directory, `${key}.json`);
33345
+ }
33346
+ async directoryReady(create) {
33347
+ if (create && !await ensureWindowsOwnerOnlyDirectory(this.directory))
33348
+ await mkdir14(this.directory, { recursive: true, mode: 448 });
33349
+ const stat13 = await lstat17(this.directory);
33350
+ return stat13.isDirectory() && await isOwnerOnly(this.directory, () => stat13.uid === process.getuid?.() && (stat13.mode & 511) === 448);
33351
+ }
33352
+ async read(path2, stat13) {
33353
+ if (!stat13.isFile() || stat13.size > MAX_RECORD_BYTES2 || !await isOwnerOnly(path2, () => stat13.uid === process.getuid?.() && (stat13.mode & 511) === 384))
33354
+ return;
33355
+ try {
33356
+ const windows = await readWindowsOwnerOnly(path2);
33357
+ if (windows)
33358
+ return entryFromBytes(windows);
33359
+ const file = await open12(path2, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
33360
+ try {
33361
+ const actual = await file.stat();
33362
+ if (!actual.isFile() || actual.uid !== process.getuid?.() || (actual.mode & 511) !== 384 || actual.size > MAX_RECORD_BYTES2)
33363
+ return;
33364
+ const bytes = Buffer.alloc(MAX_RECORD_BYTES2 + 1);
33365
+ const { bytesRead } = await file.read(bytes);
33366
+ return entryFromBytes(bytes.subarray(0, bytesRead));
33367
+ } finally {
33368
+ await file.close();
33369
+ }
33370
+ } catch {
33371
+ return;
33372
+ }
33373
+ }
33374
+ async load(session) {
33375
+ const path2 = this.pathFor(session);
33376
+ const read = async () => {
33377
+ if (!await this.directoryReady(false))
33378
+ return;
33379
+ const stat13 = await lstat17(path2);
33380
+ const entry2 = await this.read(path2, stat13);
33381
+ if (entry2 && fullCacheTailExpired(entry2.tail, this.now()))
33382
+ this.enqueue(() => this.removeUnchanged(path2, stat13));
33383
+ return entry2;
33384
+ };
33385
+ let cancelTimeout;
33386
+ try {
33387
+ return await Promise.race([
33388
+ read().catch(() => {
33389
+ return;
33390
+ }),
33391
+ new Promise((resolve18) => {
33392
+ const timeout = setTimeout(resolve18, READ_TIMEOUT_MS);
33393
+ timeout.unref();
33394
+ cancelTimeout = () => clearTimeout(timeout);
33395
+ })
33396
+ ]);
33397
+ } finally {
33398
+ cancelTimeout?.();
33399
+ }
33400
+ }
33401
+ enqueue(action) {
33402
+ this.writes = this.writes.then(action).catch(() => {});
33403
+ }
33404
+ changed(session, tail, continued) {
33405
+ const path2 = this.pathFor(session);
33406
+ this.enqueue(async () => {
33407
+ if (!await this.directoryReady(Boolean(tail)))
33408
+ return;
33409
+ const now = this.now();
33410
+ if (tail && !fullCacheTailExpired(tail, now)) {
33411
+ const data = JSON.stringify({ v: 1, continued, tail });
33412
+ if (Buffer.byteLength(data) <= MAX_RECORD_BYTES2)
33413
+ await this.publish(path2, data);
33414
+ else
33415
+ await rm9(path2, { force: true });
33416
+ } else
33417
+ await rm9(path2, { force: true });
33418
+ await this.prune(now);
33419
+ });
33420
+ }
33421
+ async publish(path2, data) {
33422
+ const temp = `${path2}.${randomUUID20()}.tmp`;
33423
+ try {
33424
+ if (!await createWindowsOwnerOnly(temp, data))
33425
+ await writeFile6(temp, data, { flag: "wx", mode: 384 });
33426
+ await renameWithWindowsSharingRetry(temp, path2);
33427
+ } finally {
33428
+ await rm9(temp, { force: true });
33429
+ }
33430
+ }
33431
+ async removeUnchanged(path2, stat13) {
33432
+ const current = await lstat17(path2).catch(() => {
33433
+ return;
33434
+ });
33435
+ if (current?.dev === stat13.dev && current.ino === stat13.ino && current.ctimeMs === stat13.ctimeMs)
33436
+ await rm9(path2, { force: true });
33437
+ }
33438
+ async prune(now) {
33439
+ const names = await readdir7(this.directory);
33440
+ const files = names.filter((name) => FILE2.test(name));
33441
+ const sweep = now >= this.nextSweep;
33442
+ if (!sweep && files.length <= MAX_SESSIONS)
33443
+ return;
33444
+ if (sweep)
33445
+ this.nextSweep = now + SWEEP_INTERVAL_MS;
33446
+ const candidates = sweep ? [...files, ...names.filter((name) => TEMP2.test(name))] : files;
33447
+ const live = [];
33448
+ for (let i = 0;i < candidates.length; i += 32) {
33449
+ await Promise.all(candidates.slice(i, i + 32).map(async (name) => {
33450
+ const path2 = join28(this.directory, name);
33451
+ const stat13 = await lstat17(path2).catch(() => {
33452
+ return;
33453
+ });
33454
+ if (!stat13?.isFile())
33455
+ return;
33456
+ if (TEMP2.test(name)) {
33457
+ if (stat13.mtimeMs <= Date.now() - LONG_LIFETIME_MS)
33458
+ await this.removeUnchanged(path2, stat13);
33459
+ return;
33460
+ }
33461
+ if (sweep) {
33462
+ const entry2 = await this.read(path2, stat13);
33463
+ if (!entry2 || fullCacheTailExpired(entry2.tail, now)) {
33464
+ await this.removeUnchanged(path2, stat13);
33465
+ return;
33466
+ }
33467
+ }
33468
+ live.push({ path: path2, stat: stat13 });
33469
+ }));
33470
+ }
33471
+ live.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
33472
+ for (const { path: path2, stat: stat13 } of live.slice(MAX_SESSIONS))
33473
+ await this.removeUnchanged(path2, stat13);
33474
+ }
33475
+ async drain() {
33476
+ await this.writes;
33477
+ }
33478
+ }
33479
+
33480
+ // src/message-threads.ts
33129
33481
  var MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
33130
33482
  var MAX_AGE_MS = 5 * 60000;
33131
- var MAX_SESSIONS = 2048;
33483
+ var MAX_SESSIONS2 = 2048;
33132
33484
  var MAX_MESSAGE_HASHES = 131072;
33133
33485
  function localMessageThreadCredential(binding2) {
33134
33486
  return JSON.stringify([
@@ -33139,7 +33491,7 @@ function localMessageThreadCredential(binding2) {
33139
33491
  ]);
33140
33492
  }
33141
33493
  function hash4(value) {
33142
- return createHash23("sha256").update(JSON.stringify(value)).digest("hex");
33494
+ return createHash24("sha256").update(JSON.stringify(value)).digest("hex");
33143
33495
  }
33144
33496
  function normalizedReplyName(name) {
33145
33497
  const bare = name.startsWith("mcp_") ? name.slice(4) : name;
@@ -33186,7 +33538,7 @@ class ReplyFingerprint {
33186
33538
  layout = new Map;
33187
33539
  textBlocks = new Map;
33188
33540
  signatures = new Map;
33189
- text = createHash23("sha256");
33541
+ text = createHash24("sha256");
33190
33542
  committedText = this.text.copy();
33191
33543
  hasText = false;
33192
33544
  activeText;
@@ -33208,7 +33560,7 @@ class ReplyFingerprint {
33208
33560
  this.text.update(part.slice(visible.length));
33209
33561
  }
33210
33562
  appendBlockText(state, value) {
33211
- state.text ??= createHash23("sha256");
33563
+ state.text ??= createHash24("sha256");
33212
33564
  state.committedText ??= state.text.copy();
33213
33565
  const part = state.textHasContent ? value : value.trimStart();
33214
33566
  const visible = part.trimEnd();
@@ -33259,7 +33611,7 @@ class ReplyFingerprint {
33259
33611
  state.input = block.input;
33260
33612
  }
33261
33613
  if (block.type === "thinking" || block.type === "redacted_thinking") {
33262
- state.signature = createHash23("sha256");
33614
+ state.signature = createHash24("sha256");
33263
33615
  const signature = block.type === "redacted_thinking" ? block.data : block.signature;
33264
33616
  if (typeof signature === "string") {
33265
33617
  state.signature.update(signature);
@@ -33679,7 +34031,7 @@ function restoreFullCacheTail(input, history, now) {
33679
34031
  return { reason: "no_full_tail" };
33680
34032
  if (tail.identity !== hash4([input.account, input.credential]))
33681
34033
  return { reason: "account_changed" };
33682
- if (now < tail.acceptedAt || now >= tail.acceptedAt + (tail.control.ttl === "1h" ? 3600000 : 300000))
34034
+ if (fullCacheTailExpired(tail, now))
33683
34035
  return { reason: "expired" };
33684
34036
  if (input.body.cache_control)
33685
34037
  return { reason: "slot_taken" };
@@ -33732,16 +34084,46 @@ class MessageThreadTracker {
33732
34084
  sessions = new Map;
33733
34085
  messageHashes = 0;
33734
34086
  dispositions = new Map;
33735
- instance = randomUUID20();
34087
+ instance = randomUUID21();
34088
+ #tailStore;
33736
34089
  fullTails = new Map;
33737
- constructor(capacity = MAX_SESSIONS, now = Date.now, hashBudget = MAX_MESSAGE_HASHES) {
34090
+ constructor(capacity = MAX_SESSIONS2, now = Date.now, hashBudget = MAX_MESSAGE_HASHES, tailStore) {
33738
34091
  this.capacity = capacity;
33739
34092
  this.now = now;
33740
34093
  this.hashBudget = hashBudget;
34094
+ this.#tailStore = tailStore;
34095
+ }
34096
+ static withTailPersistence(host) {
34097
+ return new MessageThreadTracker(MAX_SESSIONS2, Date.now, MAX_MESSAGE_HASHES, new MessageThreadTailStore(host));
34098
+ }
34099
+ canLoadFullTail(session) {
34100
+ const disposition = this.dispositions.get(session);
34101
+ return !this.fullTails.has(session) && !this.sessions.has(session) && disposition !== "session_deleted" && disposition !== "evicted";
34102
+ }
34103
+ loadFullTail(session) {
34104
+ if (!this.#tailStore || !this.canLoadFullTail(session))
34105
+ return;
34106
+ const disposition = this.dispositions.get(session);
34107
+ return this.#tailStore.load(session).then((entry2) => {
34108
+ if (entry2 && this.dispositions.get(session) === disposition && this.canLoadFullTail(session))
34109
+ this.rememberFullTail(session, { hadThread: true, ...entry2 });
34110
+ });
34111
+ }
34112
+ rememberFullTail(session, history) {
34113
+ this.fullTails.delete(session);
34114
+ this.fullTails.set(session, history);
34115
+ while (this.fullTails.size > this.capacity) {
34116
+ const oldest = this.fullTails.keys().next().value;
34117
+ if (oldest === undefined)
34118
+ break;
34119
+ this.fullTails.delete(oldest);
34120
+ }
33741
34121
  }
33742
34122
  forget(session, disposition = "session_deleted") {
33743
34123
  if (disposition === "session_deleted" || disposition === "evicted")
33744
34124
  this.fullTails.delete(session);
34125
+ if (disposition === "session_deleted")
34126
+ this.#tailStore?.changed(session, undefined, false);
33745
34127
  this.messageHashes -= this.sessions.get(session)?.anchor?.messages.length ?? 0;
33746
34128
  this.sessions.delete(session);
33747
34129
  this.dispositions.delete(session);
@@ -33884,25 +34266,18 @@ class MessageThreadTracker {
33884
34266
  const completedAt = this.now();
33885
34267
  accepted = true;
33886
34268
  const sentInput = { ...input, body: tailResult?.body ?? input.body };
33887
- this.fullTails.delete(input.session);
33888
- if (decision.type === "create") {
33889
- if (!input.stateless || oldTail?.hadThread)
33890
- this.fullTails.set(input.session, {
33891
- hadThread: true,
33892
- continued: false,
33893
- tail: fullCacheTail(sentInput, completedAt)
33894
- });
33895
- } else
33896
- this.fullTails.set(input.session, {
34269
+ if (decision.type === "continue" || !input.stateless || oldTail?.hadThread) {
34270
+ const continued = decision.type === "continue";
34271
+ const tail = continued ? oldTail?.tail : fullCacheTail(sentInput, completedAt);
34272
+ this.rememberFullTail(input.session, {
33897
34273
  hadThread: true,
33898
- continued: true,
33899
- tail: oldTail?.tail
34274
+ continued,
34275
+ tail
33900
34276
  });
33901
- while (this.fullTails.size > this.capacity) {
33902
- const oldest = this.fullTails.keys().next().value;
33903
- if (oldest === undefined)
33904
- break;
33905
- this.fullTails.delete(oldest);
34277
+ }
34278
+ if (this.#tailStore) {
34279
+ const history = this.fullTails.get(input.session);
34280
+ this.#tailStore.changed(input.session, history?.tail, history?.continued ?? false);
33906
34281
  }
33907
34282
  if (input.stateless)
33908
34283
  return;
@@ -34147,6 +34522,11 @@ async function prepareMessageThreadRequest(tracker, input) {
34147
34522
  const fullText = input.bodyText;
34148
34523
  let full;
34149
34524
  const fullBody = () => full ??= JSON.parse(fullText);
34525
+ if (input.session) {
34526
+ const loading = tracker.loadFullTail(input.session);
34527
+ if (loading)
34528
+ await loading;
34529
+ }
34150
34530
  const accountKey = input.account;
34151
34531
  let threading = !disabledThreadAccounts.has(accountKey);
34152
34532
  if (threading)
@@ -34420,7 +34800,7 @@ function remapRequestBodyModel(parsed) {
34420
34800
  return true;
34421
34801
  }
34422
34802
  // src/native-account-runtime.ts
34423
- import { randomUUID as randomUUID23 } from "node:crypto";
34803
+ import { randomUUID as randomUUID24 } from "node:crypto";
34424
34804
  import { resolve as resolve22 } from "node:path";
34425
34805
 
34426
34806
  // src/native-account-view.ts
@@ -35207,7 +35587,7 @@ function createNativeLocalRuntimeReaders(options) {
35207
35587
  }
35208
35588
 
35209
35589
  // src/native-refresh-coordinator.ts
35210
- import { createHash as createHash24 } from "node:crypto";
35590
+ import { createHash as createHash25 } from "node:crypto";
35211
35591
 
35212
35592
  // src/native-transient-account.ts
35213
35593
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -35325,7 +35705,7 @@ function pause(ms, signals) {
35325
35705
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
35326
35706
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
35327
35707
  function nativeAccountProviderLock(paths, identity5) {
35328
- const key = createHash24("sha256").update(JSON.stringify([paths.storageId, identity5])).digest("hex");
35708
+ const key = createHash25("sha256").update(JSON.stringify([paths.storageId, identity5])).digest("hex");
35329
35709
  return {
35330
35710
  path: paths.state,
35331
35711
  name: `native-account-provider-${key}`,
@@ -36139,9 +36519,9 @@ function createNativeRefreshCoordinator(options) {
36139
36519
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
36140
36520
 
36141
36521
  // src/migration-source.ts
36142
- import { createHash as createHash25 } from "node:crypto";
36143
- import { constants as constants4 } from "node:fs";
36144
- import { lstat as lstat17, open as open12 } from "node:fs/promises";
36522
+ import { createHash as createHash26 } from "node:crypto";
36523
+ import { constants as constants5 } from "node:fs";
36524
+ import { lstat as lstat18, open as open13 } from "node:fs/promises";
36145
36525
  class NativeMigrationSourceError extends Error {
36146
36526
  role;
36147
36527
  code;
@@ -36184,7 +36564,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
36184
36564
  });
36185
36565
  let initial;
36186
36566
  try {
36187
- initial = await lstat17(path2, { bigint: true });
36567
+ initial = await lstat18(path2, { bigint: true });
36188
36568
  } catch (error) {
36189
36569
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
36190
36570
  return missing2;
@@ -36194,7 +36574,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
36194
36574
  throw new NativeMigrationSourceError(role, "unsafe-source");
36195
36575
  let handle;
36196
36576
  try {
36197
- handle = await open12(path2, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0));
36577
+ handle = await open13(path2, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0) | (constants5.O_NONBLOCK ?? 0));
36198
36578
  const before = await handle.stat({ bigint: true });
36199
36579
  if (!before.isFile() || before.dev !== initial.dev || before.ino !== initial.ino) {
36200
36580
  throw new NativeMigrationSourceError(role, "source-changed");
@@ -36222,7 +36602,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
36222
36602
  chunks.push(chunk.subarray(0, read.bytesRead));
36223
36603
  }
36224
36604
  const after = await handle.stat({ bigint: true });
36225
- const current = await lstat17(path2, { bigint: true });
36605
+ const current = await lstat18(path2, { bigint: true });
36226
36606
  if (before.uid !== after.uid || before.gid !== after.gid || before.mode !== after.mode || current.uid !== before.uid || current.gid !== before.gid || current.mode !== before.mode || before.dev !== after.dev || before.ino !== after.ino || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || before.size !== after.size || current.dev !== before.dev || current.ino !== before.ino || current.isSymbolicLink() || current.mtimeNs !== before.mtimeNs || current.ctimeNs !== before.ctimeNs || current.size !== before.size || BigInt(bytes) !== before.size) {
36227
36607
  throw new NativeMigrationSourceError(role, "source-changed");
36228
36608
  }
@@ -36238,7 +36618,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
36238
36618
  return sourceSnapshot({
36239
36619
  role,
36240
36620
  path: path2,
36241
- digest: createHash25("sha256").update(content).digest("hex"),
36621
+ digest: createHash26("sha256").update(content).digest("hex"),
36242
36622
  data: freezeJson(data),
36243
36623
  metadata: Object.freeze({
36244
36624
  uid: Number(before.uid),
@@ -37681,8 +38061,8 @@ import { resolve as resolve21 } from "node:path";
37681
38061
  import { parse as parse4 } from "jsonc-parser";
37682
38062
 
37683
38063
  // src/settings-protection-copy.ts
37684
- import { randomUUID as randomUUID21 } from "node:crypto";
37685
- import { readFile as readFile16, rm as rm9 } from "node:fs/promises";
38064
+ import { randomUUID as randomUUID22 } from "node:crypto";
38065
+ import { readFile as readFile16, rm as rm10 } from "node:fs/promises";
37686
38066
  function record13(value) {
37687
38067
  return !!value && typeof value === "object" && !Array.isArray(value);
37688
38068
  }
@@ -37771,7 +38151,7 @@ async function writeSettingsProtectionCopy(file, host2, entry2, lockTimeoutMs =
37771
38151
  ...Object.hasOwn(copy, other) ? { [other]: copy[other] } : {},
37772
38152
  [host2]: entry2
37773
38153
  };
37774
- const temp = `${path2}.${process.pid}.${randomUUID21()}.tmp`;
38154
+ const temp = `${path2}.${process.pid}.${randomUUID22()}.tmp`;
37775
38155
  try {
37776
38156
  await writeOwnerOnlyExclusive(temp, Buffer.from(`${JSON.stringify(merged, null, 2)}
37777
38157
  `), process.platform);
@@ -37781,7 +38161,7 @@ async function writeSettingsProtectionCopy(file, host2, entry2, lockTimeoutMs =
37781
38161
  return "publish";
37782
38162
  });
37783
38163
  } finally {
37784
- await rm9(temp, { force: true });
38164
+ await rm10(temp, { force: true });
37785
38165
  }
37786
38166
  });
37787
38167
  }
@@ -39143,10 +39523,10 @@ function settingsNotImportedText(source2, target, differing) {
39143
39523
  }
39144
39524
 
39145
39525
  // src/settings-mode.ts
39146
- import { lstat as lstat18, mkdir as mkdir14 } from "node:fs/promises";
39526
+ import { lstat as lstat19, mkdir as mkdir15 } from "node:fs/promises";
39147
39527
  async function exists4(path2) {
39148
39528
  try {
39149
- await lstat18(path2);
39529
+ await lstat19(path2);
39150
39530
  return true;
39151
39531
  } catch (error) {
39152
39532
  if (error.code === "ENOENT")
@@ -39194,7 +39574,7 @@ async function writeSettingsRecord(target, path2, record15, options) {
39194
39574
  ...options.ownership,
39195
39575
  platform: context.platform
39196
39576
  }))
39197
- await mkdir14(parent, { recursive: true, mode: 448 });
39577
+ await mkdir15(parent, { recursive: true, mode: 448 });
39198
39578
  try {
39199
39579
  if (options.fs?.writeMarker)
39200
39580
  await options.fs.writeMarker(path2, bytes);
@@ -39569,10 +39949,10 @@ function createNativeRuntimeSettings(options) {
39569
39949
  }
39570
39950
  const before = fallback;
39571
39951
  const legacy = before ? undefined : reopenLegacy;
39572
- const open13 = before?.reopen ?? legacy;
39573
- if (!open13)
39952
+ const open14 = before?.reopen ?? legacy;
39953
+ if (!open14)
39574
39954
  return;
39575
- const next = await open13();
39955
+ const next = await open14();
39576
39956
  if (!next) {
39577
39957
  if (legacy && reopenLegacy === legacy && legacy.separate?.()) {
39578
39958
  probedMode = "separate";
@@ -39987,7 +40367,7 @@ function legacyNativeSettings(settings) {
39987
40367
  }
39988
40368
 
39989
40369
  // src/native-vault-runtime.ts
39990
- import { randomUUID as randomUUID22 } from "node:crypto";
40370
+ import { randomUUID as randomUUID23 } from "node:crypto";
39991
40371
  import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
39992
40372
 
39993
40373
  // src/insula-quota.ts
@@ -40126,27 +40506,23 @@ function newer(reading2, stored) {
40126
40506
  return stored.checkedAt > reading2.checkedAt ? stored : reading2;
40127
40507
  }
40128
40508
  function mergeInsulaQuota(reading2, stored) {
40129
- if (!stored || quotaSnapshotCheckedAt(stored) <= reading2.checkedAt)
40509
+ if (!stored)
40130
40510
  return reading2;
40131
- const five_hour = quotaSnapshotOmitsFiveHour(stored) ? undefined : !reading2.five_hour && (stored.five_hour?.checkedAt ?? 0) <= reading2.checkedAt ? undefined : newer(reading2.five_hour, stored.five_hour);
40511
+ if (quotaPollCheckedAt(stored) > reading2.checkedAt)
40512
+ return stored;
40513
+ if (quotaSnapshotCheckedAt(stored) <= reading2.checkedAt)
40514
+ return reading2;
40515
+ const five_hour = !reading2.five_hour && (stored.five_hour?.checkedAt ?? 0) <= reading2.checkedAt ? undefined : newer(reading2.five_hour, stored.five_hour);
40132
40516
  const seven_day = newer(reading2.seven_day, stored.seven_day);
40133
- const scoped = new Map(reading2.scoped.map((window2) => [window2.id, window2]));
40134
- for (const window2 of stored.scoped ?? []) {
40135
- const merged = newer(scoped.get(window2.id), window2);
40136
- if (merged)
40137
- scoped.set(window2.id, merged);
40138
- }
40139
40517
  const fieldSources2 = { ...reading2.fieldSources };
40140
- if (five_hour !== reading2.five_hour && stored.fieldSources?.five_hour)
40141
- fieldSources2.five_hour = stored.fieldSources.five_hour;
40142
- if (seven_day !== reading2.seven_day && stored.fieldSources?.seven_day)
40143
- fieldSources2.seven_day = stored.fieldSources.seven_day;
40518
+ if (five_hour && five_hour !== reading2.five_hour)
40519
+ fieldSources2.five_hour = quotaFieldSource(stored, "five_hour");
40520
+ if (seven_day !== reading2.seven_day)
40521
+ fieldSources2.seven_day = quotaFieldSource(stored, "seven_day");
40144
40522
  return {
40145
40523
  ...reading2,
40146
40524
  five_hour,
40147
40525
  ...seven_day && { seven_day },
40148
- scoped: [...scoped.values()],
40149
- checkedAt: quotaSnapshotOmitsFiveHour(stored) ? stored.checkedAt : quotaSnapshotOmitsFiveHour(reading2) ? reading2.checkedAt : Math.max(reading2.checkedAt, quotaSnapshotCheckedAt(stored)),
40150
40526
  fieldSources: fieldSources2
40151
40527
  };
40152
40528
  }
@@ -41853,7 +42229,7 @@ function createNativeVaultRuntime(options) {
41853
42229
  async getOrCreateAuthLineage(receipt) {
41854
42230
  let lineage;
41855
42231
  const kept = await mutateReceipt(receipt, (old) => {
41856
- lineage = old.authLineageId ?? randomUUID22();
42232
+ lineage = old.authLineageId ?? randomUUID23();
41857
42233
  return { ...old, authLineageId: lineage };
41858
42234
  });
41859
42235
  return kept ? lineage : undefined;
@@ -41875,9 +42251,11 @@ function createNativeVaultRuntime(options) {
41875
42251
  },
41876
42252
  async fetchQuota(routeId, fetchImpl = fetch, signal, dispatch, purpose) {
41877
42253
  const row = await rowFor(await runtime2.read(), routeId);
42254
+ const cacheOnly = purpose === "background-cache";
41878
42255
  let swept;
41879
- if (purpose === "background" && row) {
41880
- await refreshInsula();
42256
+ if ((purpose === "background" || cacheOnly) && row) {
42257
+ if (!cacheOnly)
42258
+ await refreshInsula();
41881
42259
  check(signal);
41882
42260
  swept = insulaLookup(row.accountIdentity);
41883
42261
  if (swept.miss === "cold" || swept.miss === "upstream-failed") {
@@ -41885,6 +42263,8 @@ function createNativeVaultRuntime(options) {
41885
42263
  throw new QuotaRefreshDeferred;
41886
42264
  }
41887
42265
  }
42266
+ if (cacheOnly && (swept?.miss || !swept?.reading))
42267
+ throw new QuotaRefreshDeferred;
41888
42268
  const state = await readNativeRuntime(paths2.runtime, paths2.storageId);
41889
42269
  const before = state.status === "ready" ? state.state.accounts[row?.routeId ?? ""] : undefined;
41890
42270
  const matchingBefore = (receipt) => {
@@ -41898,7 +42278,7 @@ function createNativeVaultRuntime(options) {
41898
42278
  miss: "unreachable"
41899
42279
  };
41900
42280
  let accountChanged = false;
41901
- if (purpose === "background") {
42281
+ if (purpose === "background" || cacheOnly) {
41902
42282
  if (swept && row?.accountIdentity && receipt.assertedAccountIdentity === row.accountIdentity)
41903
42283
  lookup = swept;
41904
42284
  else if (swept)
@@ -41913,7 +42293,7 @@ function createNativeVaultRuntime(options) {
41913
42293
  const stored = matchingBefore(receipt)?.quota;
41914
42294
  return mergeInsulaQuota(reading2, stored ? fromNativeQuotaMap(stored) : undefined);
41915
42295
  }
41916
- if (purpose === "admission" && lookup.miss === "upstream-failed")
42296
+ if (cacheOnly || purpose === "admission" && lookup.miss === "upstream-failed")
41917
42297
  return;
41918
42298
  return fetchOAuthQuotaSnapshot({
41919
42299
  accessToken: receipt.accessToken,
@@ -42716,7 +43096,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42716
43096
  const sameAccount = old?.kind === "local" && old.rowId === binding2.rowId && binding2.identity !== undefined && old.identity === binding2.identity;
42717
43097
  const next = {
42718
43098
  binding: binding2,
42719
- ...row.credential?.type === "oauth" ? { authLineageId: randomUUID23() } : {}
43099
+ ...row.credential?.type === "oauth" ? { authLineageId: randomUUID24() } : {}
42720
43100
  };
42721
43101
  if (sameAccount && previous) {
42722
43102
  for (const key of [
@@ -42906,7 +43286,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42906
43286
  throw new NativeRuntimeError("publication-refused");
42907
43287
  const previous = relayFlags(read.settings.relay);
42908
43288
  const previousGeneration = relayGeneration(read.settings.relay);
42909
- const generation = randomUUID23();
43289
+ const generation = randomUUID24();
42910
43290
  const metadata2 = await readNativeRuntime(paths3.runtime, paths3.storageId);
42911
43291
  const token2 = patch.token === undefined ? metadata2.status === "ready" ? metadata2.state.relay?.token : undefined : patch.token?.trim();
42912
43292
  const next = relayFlags({
@@ -43147,7 +43527,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
43147
43527
  const snapshot = await runtime2.read();
43148
43528
  if (snapshot.mode !== "local")
43149
43529
  throw new NativeCustodyError("route-unavailable");
43150
- const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID23()) : input.routeId;
43530
+ const id2 = input.routeId === "main" ? await physicalId("main").catch(() => randomUUID24()) : input.routeId;
43151
43531
  if (input.credential.type === "api" && (input.routeId === "main" || id2 === snapshot.settings.mainAccountId))
43152
43532
  throw new NativeCustodyError("route-unavailable");
43153
43533
  const old = await poolRow(id2);
@@ -43186,7 +43566,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
43186
43566
  return row;
43187
43567
  },
43188
43568
  addApi: (input) => runtime2.putAccount({
43189
- routeId: input.routeId ?? randomUUID23(),
43569
+ routeId: input.routeId ?? randomUUID24(),
43190
43570
  label: input.label,
43191
43571
  replace: input.replace,
43192
43572
  credential: {
@@ -43508,7 +43888,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
43508
43888
  return;
43509
43889
  let lineage;
43510
43890
  const kept = await metadataPublications.run(() => localMetadataWrite(fence, (old) => {
43511
- lineage = old.authLineageId ?? randomUUID23();
43891
+ lineage = old.authLineageId ?? randomUUID24();
43512
43892
  return {
43513
43893
  ...old,
43514
43894
  authLineageId: lineage
@@ -43538,6 +43918,8 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
43538
43918
  const snapshot = await runtime2.read();
43539
43919
  if (snapshot.mode === "claustrum")
43540
43920
  return vault.fetchQuota(routeId, fetchImpl, signal, dispatch, purpose);
43921
+ if (purpose === "background-cache")
43922
+ throw new QuotaRefreshDeferred;
43541
43923
  const before = snapshot.accounts.find((row) => row.id === routeId);
43542
43924
  const result = await fetchReading(routeId, fetchImpl, signal, (attempt, transport) => fetchOAuthQuotaSnapshot({
43543
43925
  accessToken: attempt.access,
@@ -43728,9 +44110,9 @@ function relayGeneration(input) {
43728
44110
  return generation;
43729
44111
  }
43730
44112
  // src/native-host-auth-write.ts
43731
- import { randomUUID as randomUUID24 } from "node:crypto";
43732
- import { lstat as lstat19, open as open13, rename as rename15, unlink as unlink9 } from "node:fs/promises";
43733
- import { dirname as dirname22, isAbsolute as isAbsolute6, join as join28 } from "node:path";
44113
+ import { randomUUID as randomUUID25 } from "node:crypto";
44114
+ import { lstat as lstat20, open as open14, rename as rename15, unlink as unlink9 } from "node:fs/promises";
44115
+ import { dirname as dirname22, isAbsolute as isAbsolute6, join as join29 } from "node:path";
43734
44116
  class NativeHostAuthWriteError extends Error {
43735
44117
  code;
43736
44118
  effect;
@@ -43791,11 +44173,11 @@ async function writeNativeHostAuth(input, hooks = {}) {
43791
44173
  const removingFile = host2 === "pi" && Object.keys(next).length === 0;
43792
44174
  const outcome = Object.freeze(host2 === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
43793
44175
  if (!removingFile) {
43794
- stage = join28(dirname22(authPath), `.native-host-auth-write.${randomUUID24()}.tmp`);
44176
+ stage = join29(dirname22(authPath), `.native-host-auth-write.${randomUUID25()}.tmp`);
43795
44177
  const bytes = `${JSON.stringify(next, null, 2)}
43796
44178
  `;
43797
44179
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
43798
- const handle = await open13(stage, nativeCreated ? "r+" : "wx", 384);
44180
+ const handle = await open14(stage, nativeCreated ? "r+" : "wx", 384);
43799
44181
  try {
43800
44182
  const identity5 = await handle.stat();
43801
44183
  ownedStage = { dev: identity5.dev, ino: identity5.ino };
@@ -43841,7 +44223,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
43841
44223
  } finally {
43842
44224
  if (stage && ownedStage) {
43843
44225
  try {
43844
- const current = await lstat19(stage);
44226
+ const current = await lstat20(stage);
43845
44227
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
43846
44228
  await unlink9(stage);
43847
44229
  } catch {}
@@ -43850,8 +44232,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
43850
44232
  }
43851
44233
 
43852
44234
  // src/native-migration.ts
43853
- import { createHash as createHash26 } from "node:crypto";
43854
- import { lstat as lstat20, mkdir as mkdir15, unlink as unlink10 } from "node:fs/promises";
44235
+ import { createHash as createHash27 } from "node:crypto";
44236
+ import { lstat as lstat21, mkdir as mkdir16, unlink as unlink10 } from "node:fs/promises";
43855
44237
  import { dirname as dirname23, isAbsolute as isAbsolute7 } from "node:path";
43856
44238
  class NativeMigrationError extends Error {
43857
44239
  code;
@@ -43909,7 +44291,7 @@ function owned(snapshot) {
43909
44291
  }
43910
44292
  async function absent(path2) {
43911
44293
  try {
43912
- await lstat20(path2);
44294
+ await lstat21(path2);
43913
44295
  return false;
43914
44296
  } catch (error) {
43915
44297
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -44242,7 +44624,7 @@ function routingBytes(captured) {
44242
44624
  `;
44243
44625
  }
44244
44626
  function bytesDigest(bytes) {
44245
- return bytes === undefined ? null : createHash26("sha256").update(bytes).digest("hex");
44627
+ return bytes === undefined ? null : createHash27("sha256").update(bytes).digest("hex");
44246
44628
  }
44247
44629
  function expectedAuth(input, snapshot) {
44248
44630
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -44639,7 +45021,7 @@ async function runNativeMigration(input, hooks = {}) {
44639
45021
  refuse3();
44640
45022
  await step("before:host");
44641
45023
  await recheck(false);
44642
- await mkdir15(dirname23(operation.hostAuthPath), {
45024
+ await mkdir16(dirname23(operation.hostAuthPath), {
44643
45025
  recursive: true,
44644
45026
  mode: 448
44645
45027
  });
@@ -47502,7 +47884,7 @@ function waitForRequest(pending, signal) {
47502
47884
  });
47503
47885
  }
47504
47886
  // src/native-vault-connection.ts
47505
- import { dirname as dirname25, join as join29, resolve as resolve24 } from "node:path";
47887
+ import { dirname as dirname25, join as join30, resolve as resolve24 } from "node:path";
47506
47888
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
47507
47889
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
47508
47890
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -47510,14 +47892,14 @@ function placeholderSecret(integrationID) {
47510
47892
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
47511
47893
  }
47512
47894
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
47513
- import { constants as constants5 } from "node:fs";
47514
- import { lstat as lstat21, mkdir as mkdir17, open as open14, unlink as unlink11 } from "node:fs/promises";
47895
+ import { constants as constants6 } from "node:fs";
47896
+ import { lstat as lstat22, mkdir as mkdir18, open as open15, unlink as unlink11 } from "node:fs/promises";
47515
47897
  import { dirname as dirname24, resolve as resolve23 } from "node:path";
47516
47898
  import { setTimeout as sleep } from "node:timers/promises";
47517
47899
 
47518
47900
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
47519
47901
  import { rmdirSync, statSync as statSync7, utimesSync } from "node:fs";
47520
- import { mkdir as mkdir16, rmdir, stat as stat13, utimes } from "node:fs/promises";
47902
+ import { mkdir as mkdir17, rmdir, stat as stat13, utimes } from "node:fs/promises";
47521
47903
  var STALE = 30000;
47522
47904
  var RENEWAL_STALE = 1e4;
47523
47905
  var UPDATE = 3000;
@@ -47553,7 +47935,7 @@ async function remove(path2) {
47553
47935
  }
47554
47936
  async function acquire(path2, stale) {
47555
47937
  try {
47556
- await mkdir16(path2);
47938
+ await mkdir17(path2);
47557
47939
  } catch (error) {
47558
47940
  if (errorCode4(error) !== "EEXIST")
47559
47941
  throw error;
@@ -47799,13 +48181,13 @@ async function safeRead(path2, afterReadCheck) {
47799
48181
  }
47800
48182
  let file;
47801
48183
  try {
47802
- file = await open14(path2, constants5.O_RDONLY | constants5.O_NOFOLLOW);
48184
+ file = await open15(path2, constants6.O_RDONLY | constants6.O_NOFOLLOW);
47803
48185
  const stat14 = await file.stat();
47804
48186
  if (!stat14.isFile()) {
47805
48187
  throw new PiSlotError("unsafe-path");
47806
48188
  }
47807
48189
  await afterReadCheck?.(path2);
47808
- const current = await lstat21(path2);
48190
+ const current = await lstat22(path2);
47809
48191
  if (!current.isFile() || current.dev !== stat14.dev || current.ino !== stat14.ino) {
47810
48192
  throw new PiSlotError("unsafe-path");
47811
48193
  }
@@ -47873,7 +48255,7 @@ function replaceEntry(auth, provider, next) {
47873
48255
  async function syncDir(path2) {
47874
48256
  if (windowsPrivateFiles)
47875
48257
  return;
47876
- const dir = await open14(path2, "r");
48258
+ const dir = await open15(path2, "r");
47877
48259
  try {
47878
48260
  await dir.sync();
47879
48261
  } finally {
@@ -47920,7 +48302,7 @@ function createPiSlot(options, onStep, hooks) {
47920
48302
  if (windowsPrivateFiles)
47921
48303
  await ensurePrivateDirectory(dirname24(authPath));
47922
48304
  else
47923
- await mkdir17(dirname24(authPath), { recursive: true, mode: 448 });
48305
+ await mkdir18(dirname24(authPath), { recursive: true, mode: 448 });
47924
48306
  const deadline = Date.now() + timeout;
47925
48307
  let retry = 0;
47926
48308
  while (!release2) {
@@ -47957,7 +48339,7 @@ function createPiSlot(options, onStep, hooks) {
47957
48339
  }
47958
48340
  async function deleteStash(assertLock) {
47959
48341
  try {
47960
- const file = await lstat21(stashPath);
48342
+ const file = await lstat22(stashPath);
47961
48343
  if (!file.isFile())
47962
48344
  throw new PiSlotError("unsafe-path");
47963
48345
  } catch (error) {
@@ -47968,7 +48350,7 @@ function createPiSlot(options, onStep, hooks) {
47968
48350
  if (windowsPrivateFiles)
47969
48351
  await verifySafeDirectory(dirname24(stashPath));
47970
48352
  else {
47971
- const dir = await lstat21(dirname24(stashPath));
48353
+ const dir = await lstat22(dirname24(stashPath));
47972
48354
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
47973
48355
  throw new PiSlotError("unsafe-path");
47974
48356
  }
@@ -48007,7 +48389,7 @@ function createPiSlot(options, onStep, hooks) {
48007
48389
  function nativePiAuthSlotPaths(options) {
48008
48390
  return {
48009
48391
  authPath: resolve24(options.authPath),
48010
- stashPath: join29(dirname25(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
48392
+ stashPath: join30(dirname25(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
48011
48393
  provider: "anthropic",
48012
48394
  placeholderKey: placeholderSecret("anthropic")
48013
48395
  };
@@ -48175,11 +48557,11 @@ function requestMethod(input) {
48175
48557
  return input instanceof Request ? input.method : "GET";
48176
48558
  }
48177
48559
  // src/prime.ts
48178
- import { createHash as createHash27 } from "node:crypto";
48560
+ import { createHash as createHash28 } from "node:crypto";
48179
48561
  import * as fs4 from "node:fs";
48180
- import { mkdir as mkdir18, readdir as readdir7, rm as rm10, stat as stat14, writeFile as writeFile6 } from "node:fs/promises";
48562
+ import { mkdir as mkdir19, readdir as readdir8, rm as rm11, stat as stat14, writeFile as writeFile7 } from "node:fs/promises";
48181
48563
  import { tmpdir as tmpdir8 } from "node:os";
48182
- import { join as join30, resolve as resolve25 } from "node:path";
48564
+ import { join as join31, resolve as resolve25 } from "node:path";
48183
48565
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
48184
48566
  var PRIME_TICK_MS = 60000;
48185
48567
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -48367,7 +48749,7 @@ function buildPrimeRequestBody() {
48367
48749
  return JSON.parse(JSON.stringify(PRIME_REQUEST_BODY));
48368
48750
  }
48369
48751
  function defaultMarkerDir() {
48370
- return join30(tmpdir8(), "opencode-anthropic-auth", "prime");
48752
+ return join31(tmpdir8(), "opencode-anthropic-auth", "prime");
48371
48753
  }
48372
48754
  function primeStorageFingerprint(storagePath) {
48373
48755
  const absolutePath = resolve25(storagePath);
@@ -48384,22 +48766,22 @@ function primeStorageFingerprint(storagePath) {
48384
48766
  throw error;
48385
48767
  canonicalPath3 = absolutePath;
48386
48768
  }
48387
- return createHash27("sha256").update(canonicalPath3).digest("hex").slice(0, 12);
48769
+ return createHash28("sha256").update(canonicalPath3).digest("hex").slice(0, 12);
48388
48770
  }
48389
48771
  function primeMarkerNamespaceDir(markerDir, storagePath) {
48390
- return join30(markerDir, primeStorageFingerprint(storagePath));
48772
+ return join31(markerDir, primeStorageFingerprint(storagePath));
48391
48773
  }
48392
48774
  function primeAccountMarkerDir(markerDir, storagePath, accountFingerprint) {
48393
48775
  if (!/^[a-f0-9]{12,}$/i.test(accountFingerprint)) {
48394
48776
  throw new Error("Prime account fingerprint must be a hexadecimal digest");
48395
48777
  }
48396
- return join30(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
48778
+ return join31(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
48397
48779
  }
48398
48780
  function primeMarkerPath(markerDir, accountId2, resetsAtEpochMs) {
48399
- return join30(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
48781
+ return join31(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
48400
48782
  }
48401
48783
  function primeBootstrapMarkerPath(markerDir, accountId2) {
48402
- return join30(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
48784
+ return join31(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
48403
48785
  }
48404
48786
  function primeAccountLabel(id2, fallback) {
48405
48787
  if (id2 === "main")
@@ -48676,16 +49058,16 @@ class PrimeManager {
48676
49058
  }
48677
49059
  const postClaimStorage = await this.options.loadStorage();
48678
49060
  if (this.stopped || postClaimStorage?.prime?.enabled !== true) {
48679
- await Promise.all(markerPaths.map((path2) => rm10(path2, { force: true })));
49061
+ await Promise.all(markerPaths.map((path2) => rm11(path2, { force: true })));
48680
49062
  return;
48681
49063
  }
48682
49064
  if (markerEpoch !== undefined) {
48683
- await rm10(bootstrapMarkerPath, { force: true });
49065
+ await rm11(bootstrapMarkerPath, { force: true });
48684
49066
  if (accountIdentity) {
48685
- await rm10(this.verifiedMarkerPath(accountIdentity), { force: true });
49067
+ await rm11(this.verifiedMarkerPath(accountIdentity), { force: true });
48686
49068
  }
48687
49069
  if (this.stopped) {
48688
- await Promise.all(markerPaths.map((path2) => rm10(path2, { force: true })));
49070
+ await Promise.all(markerPaths.map((path2) => rm11(path2, { force: true })));
48689
49071
  return;
48690
49072
  }
48691
49073
  }
@@ -48707,7 +49089,7 @@ class PrimeManager {
48707
49089
  return [markerPath];
48708
49090
  const verifiedPath = this.verifiedMarkerPath(accountIdentity, resetsAtEpochMs);
48709
49091
  if (resetsAtEpochMs === undefined) {
48710
- const digest2 = createHash27("sha256").update(accountIdentity).digest("hex");
49092
+ const digest2 = createHash28("sha256").update(accountIdentity).digest("hex");
48711
49093
  if ((await this.readMarkerNames(this.verifiedMarkerDir())).some((name) => name.startsWith(`${digest2}-`)))
48712
49094
  return null;
48713
49095
  }
@@ -48716,15 +49098,15 @@ class PrimeManager {
48716
49098
  return [markerPath, verifiedPath];
48717
49099
  }
48718
49100
  verifiedMarkerDir() {
48719
- return join30(this.options.markerDir ?? defaultMarkerDir(), "accounts");
49101
+ return join31(this.options.markerDir ?? defaultMarkerDir(), "accounts");
48720
49102
  }
48721
49103
  verifiedMarkerPath(accountIdentity, resetsAtEpochMs) {
48722
- const digest2 = createHash27("sha256").update(accountIdentity).digest("hex");
48723
- return join30(this.verifiedMarkerDir(), `${digest2}-${resetsAtEpochMs ?? "bootstrap"}`);
49104
+ const digest2 = createHash28("sha256").update(accountIdentity).digest("hex");
49105
+ return join31(this.verifiedMarkerDir(), `${digest2}-${resetsAtEpochMs ?? "bootstrap"}`);
48724
49106
  }
48725
49107
  async readMarkerNames(dir) {
48726
49108
  try {
48727
- return await readdir7(dir);
49109
+ return await readdir8(dir);
48728
49110
  } catch (error) {
48729
49111
  if (error.code === "ENOENT")
48730
49112
  return [];
@@ -48733,10 +49115,10 @@ class PrimeManager {
48733
49115
  }
48734
49116
  async tryClaimPath(dir, markerPath) {
48735
49117
  try {
48736
- await mkdir18(dir, { recursive: true });
49118
+ await mkdir19(dir, { recursive: true });
48737
49119
  } catch {}
48738
49120
  try {
48739
- await writeFile6(markerPath, "", { encoding: "utf8", flag: "wx" });
49121
+ await writeFile7(markerPath, "", { encoding: "utf8", flag: "wx" });
48740
49122
  return markerPath;
48741
49123
  } catch (error) {
48742
49124
  const code2 = error.code;
@@ -48749,7 +49131,7 @@ class PrimeManager {
48749
49131
  const dir = this.markerDir(accountFingerprint);
48750
49132
  const prefix = `${encodeURIComponent(accountId2)}-`;
48751
49133
  try {
48752
- return (await readdir7(dir)).some((entry2) => entry2.startsWith(prefix));
49134
+ return (await readdir8(dir)).some((entry2) => entry2.startsWith(prefix));
48753
49135
  } catch (error) {
48754
49136
  if (error.code === "ENOENT")
48755
49137
  return false;
@@ -48861,21 +49243,21 @@ class PrimeManager {
48861
49243
  async sweepMarkerDirectory(dir, now) {
48862
49244
  let entries;
48863
49245
  try {
48864
- entries = await readdir7(dir);
49246
+ entries = await readdir8(dir);
48865
49247
  } catch {
48866
49248
  return 0;
48867
49249
  }
48868
49250
  let swept = 0;
48869
49251
  for (const entry2 of entries) {
48870
49252
  try {
48871
- const path2 = join30(dir, entry2);
49253
+ const path2 = join31(dir, entry2);
48872
49254
  const s = await stat14(path2);
48873
49255
  if (s.isDirectory()) {
48874
49256
  swept += await this.sweepMarkerDirectory(path2, now);
48875
49257
  continue;
48876
49258
  }
48877
49259
  if (now - s.mtimeMs > PRIME_MARKER_MAX_AGE_MS) {
48878
- await rm10(path2, { force: true });
49260
+ await rm11(path2, { force: true });
48879
49261
  swept += 1;
48880
49262
  }
48881
49263
  } catch {}
@@ -48890,24 +49272,24 @@ class PrimeManager {
48890
49272
  }
48891
49273
  }
48892
49274
  // src/quota-header-feed.ts
48893
- import { randomUUID as randomUUID25 } from "node:crypto";
49275
+ import { randomUUID as randomUUID26 } from "node:crypto";
48894
49276
  import {
48895
49277
  chmod as chmod3,
48896
- lstat as lstat22,
48897
- mkdir as mkdir19,
48898
- readdir as readdir8,
49278
+ lstat as lstat23,
49279
+ mkdir as mkdir20,
49280
+ readdir as readdir9,
48899
49281
  readFile as readFile18,
48900
49282
  rename as rename16,
48901
- rm as rm11,
49283
+ rm as rm12,
48902
49284
  stat as stat15,
48903
- writeFile as writeFile7
49285
+ writeFile as writeFile8
48904
49286
  } from "node:fs/promises";
48905
49287
  import { tmpdir as tmpdir9 } from "node:os";
48906
- import { join as join31 } from "node:path";
49288
+ import { join as join32 } from "node:path";
48907
49289
  var QUOTA_HEADER_FEED_SCHEMA_VERSION = 3;
48908
49290
  var QUOTA_HEADER_FEED_LEASE_MS = 180000;
48909
49291
  function getDefaultQuotaHeaderFeedDirectory() {
48910
- return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join31(tmpdir9(), "opencode-anthropic-auth", "quota-header-feed");
49292
+ return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join32(tmpdir9(), "opencode-anthropic-auth", "quota-header-feed");
48911
49293
  }
48912
49294
  function configuredAnthropicOAuthAccountCount(input) {
48913
49295
  const fallbackCount = input.storage?.accounts.filter(isOAuthAccount).length ?? 0;
@@ -49065,8 +49447,8 @@ class QuotaHeaderFeedRegistry {
49065
49447
  writeChain = Promise.resolve();
49066
49448
  constructor(options = {}) {
49067
49449
  this.options = options;
49068
- const instanceId = options.instanceId ?? `${process.pid}-${randomUUID25()}`;
49069
- this.filePath = join31(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
49450
+ const instanceId = options.instanceId ?? `${process.pid}-${randomUUID26()}`;
49451
+ this.filePath = join32(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
49070
49452
  }
49071
49453
  publish(entry2) {
49072
49454
  const { accountKey, quota: quota2 } = entry2;
@@ -49095,7 +49477,7 @@ class QuotaHeaderFeedRegistry {
49095
49477
  return Promise.reject(new Error("Invalid quota header feed account key"));
49096
49478
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
49097
49479
  const directory = this.options.directory ?? getDefaultQuotaHeaderFeedDirectory();
49098
- await mkdir19(directory, { recursive: true, mode: 448 });
49480
+ await mkdir20(directory, { recursive: true, mode: 448 });
49099
49481
  await chmod3(directory, 448);
49100
49482
  await this.reapStaleSiblingLeases(directory);
49101
49483
  let entries = {};
@@ -49105,14 +49487,14 @@ class QuotaHeaderFeedRegistry {
49105
49487
  entries = record17.entries;
49106
49488
  } catch {}
49107
49489
  entries[accountKey] = cleanEntry;
49108
- const tempPath = `${this.filePath}.${randomUUID25()}.tmp`;
49490
+ const tempPath = `${this.filePath}.${randomUUID26()}.tmp`;
49109
49491
  try {
49110
- await writeFile7(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
49492
+ await writeFile8(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
49111
49493
  `, { mode: 384 });
49112
49494
  await chmod3(tempPath, 384);
49113
49495
  await rename16(tempPath, this.filePath);
49114
49496
  } finally {
49115
- await rm11(tempPath, { force: true });
49497
+ await rm12(tempPath, { force: true });
49116
49498
  }
49117
49499
  });
49118
49500
  return this.writeChain;
@@ -49122,12 +49504,12 @@ class QuotaHeaderFeedRegistry {
49122
49504
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
49123
49505
  let names2;
49124
49506
  try {
49125
- names2 = await readdir8(directory);
49507
+ names2 = await readdir9(directory);
49126
49508
  } catch {
49127
49509
  return;
49128
49510
  }
49129
49511
  await Promise.all(names2.filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)).map(async (name) => {
49130
- const path2 = join31(directory, name);
49512
+ const path2 = join32(directory, name);
49131
49513
  if (path2 === this.filePath)
49132
49514
  return;
49133
49515
  try {
@@ -49135,10 +49517,10 @@ class QuotaHeaderFeedRegistry {
49135
49517
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
49136
49518
  return;
49137
49519
  await this.options.beforeRemoveFile?.(path2);
49138
- const current = await lstat22(path2);
49520
+ const current = await lstat23(path2);
49139
49521
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
49140
49522
  return;
49141
- await (this.options.removeFile ?? ((target2) => rm11(target2)))(path2);
49523
+ await (this.options.removeFile ?? ((target2) => rm12(target2)))(path2);
49142
49524
  } catch {}
49143
49525
  }));
49144
49526
  }
@@ -49149,14 +49531,14 @@ class QuotaHeaderFeedRegistry {
49149
49531
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
49150
49532
  let names2;
49151
49533
  try {
49152
- names2 = (await readdir8(directory)).filter((name) => name.endsWith(".json"));
49534
+ names2 = (await readdir9(directory)).filter((name) => name.endsWith(".json"));
49153
49535
  } catch {
49154
49536
  return [];
49155
49537
  }
49156
49538
  const newest = new Map;
49157
49539
  await Promise.all(names2.map(async (name) => {
49158
49540
  try {
49159
- const record17 = JSON.parse(await readFile18(join31(directory, name), "utf8"));
49541
+ const record17 = JSON.parse(await readFile18(join32(directory, name), "utf8"));
49160
49542
  if (record17.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record17.entries || typeof record17.entries !== "object")
49161
49543
  return;
49162
49544
  for (const [accountKey, candidate] of Object.entries(record17.entries)) {
@@ -49175,7 +49557,7 @@ class QuotaHeaderFeedRegistry {
49175
49557
  }
49176
49558
  async dispose() {
49177
49559
  await this.writeChain.catch(() => {});
49178
- await rm11(this.filePath, { force: true });
49560
+ await rm12(this.filePath, { force: true });
49179
49561
  }
49180
49562
  }
49181
49563
  // src/quotas.ts
@@ -49336,8 +49718,8 @@ function buildClaudeQuotaSummary(input) {
49336
49718
  `).trimEnd();
49337
49719
  }
49338
49720
  // src/request-gzip.ts
49339
- import { mkdir as mkdir20, readFile as readFile19, rename as rename17, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
49340
- import { basename as basename14, dirname as dirname26, join as join32 } from "node:path";
49721
+ import { mkdir as mkdir21, readFile as readFile19, rename as rename17, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
49722
+ import { basename as basename14, dirname as dirname26, join as join33 } from "node:path";
49341
49723
  import { promisify as promisify2 } from "node:util";
49342
49724
  import { gzip as gzip2 } from "node:zlib";
49343
49725
  var gzipAsync = promisify2(gzip2);
@@ -49451,7 +49833,7 @@ class RequestGzipLatch {
49451
49833
  const age = typeof latchedAt === "number" && Number.isFinite(latchedAt) ? this.now() - latchedAt : -1;
49452
49834
  if (age >= 0 && age < GZIP_LATCH_TTL_MS)
49453
49835
  return true;
49454
- await rm12(this.path, { force: true }).catch(() => {});
49836
+ await rm13(this.path, { force: true }).catch(() => {});
49455
49837
  return false;
49456
49838
  }
49457
49839
  async persist(status) {
@@ -49461,12 +49843,12 @@ class RequestGzipLatch {
49461
49843
  return;
49462
49844
  const temporary = `${this.path}.${process.pid}.tmp`;
49463
49845
  try {
49464
- await mkdir20(dirname26(this.path), { recursive: true });
49465
- await writeFile8(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
49846
+ await mkdir21(dirname26(this.path), { recursive: true });
49847
+ await writeFile9(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
49466
49848
  `, { mode: 384 });
49467
49849
  await rename17(temporary, this.path);
49468
49850
  } catch {
49469
- await rm12(temporary, { force: true }).catch(() => {});
49851
+ await rm13(temporary, { force: true }).catch(() => {});
49470
49852
  }
49471
49853
  }
49472
49854
  }
@@ -49485,7 +49867,7 @@ function getRequestGzipLatchPath(accountStoragePath, layout = LEGACY_STATE_LAYOU
49485
49867
  return stateHomeFilePaths(layout.dir).requestGzip;
49486
49868
  const name = basename14(accountStoragePath);
49487
49869
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
49488
- return join32(dirname26(accountStoragePath), `${stem}-request-gzip.json`);
49870
+ return join33(dirname26(accountStoragePath), `${stem}-request-gzip.json`);
49489
49871
  }
49490
49872
  async function decideRequestGzip(options) {
49491
49873
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -49896,7 +50278,7 @@ function createRoutingRelay(quotaFor) {
49896
50278
  };
49897
50279
  }
49898
50280
  // src/routing-wait.ts
49899
- import { randomUUID as randomUUID26 } from "node:crypto";
50281
+ import { randomUUID as randomUUID27 } from "node:crypto";
49900
50282
  var messages = {
49901
50283
  account_limit: "Waiting for the current account limit to reset.",
49902
50284
  account_free: "Waiting for an account to become available.",
@@ -49909,7 +50291,7 @@ function startRoutingWait(input) {
49909
50291
  const report2 = {
49910
50292
  sessionId: input.sessionId,
49911
50293
  kind: "wait",
49912
- waitId: randomUUID26(),
50294
+ waitId: randomUUID27(),
49913
50295
  reason: input.reason,
49914
50296
  message: messages[input.reason],
49915
50297
  ...input.nextMs !== undefined ? { nextMs: Math.round(input.nextMs) } : {},
@@ -49928,9 +50310,9 @@ function startRoutingWait(input) {
49928
50310
  };
49929
50311
  }
49930
50312
  // src/layout-fence.ts
49931
- import { open as open15, readdir as readdir9 } from "node:fs/promises";
50313
+ import { open as open16, readdir as readdir10 } from "node:fs/promises";
49932
50314
  import { homedir as homedir7 } from "node:os";
49933
- import { basename as basename15, join as join33, resolve as resolve26 } from "node:path";
50315
+ import { basename as basename15, join as join34, resolve as resolve26 } from "node:path";
49934
50316
  var STATE_PATH_OVERRIDE_VARIABLES = [
49935
50317
  "OPENCODE_ANTHROPIC_AUTH_FILE",
49936
50318
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -49966,7 +50348,7 @@ async function holderFenceBlockers(input) {
49966
50348
  const files = new Set(input.files);
49967
50349
  const blockers = [];
49968
50350
  for (const dir of [...new Set(input.directories)].sort()) {
49969
- const holderFile = join33(dir, HOLDER_FILE_NAME);
50351
+ const holderFile = join34(dir, HOLDER_FILE_NAME);
49970
50352
  let contents;
49971
50353
  try {
49972
50354
  contents = await readHolderFile(holderFile);
@@ -50016,7 +50398,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir7()) {
50016
50398
  });
50017
50399
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
50018
50400
  return {
50019
- rpcRoots: [join33(root, "rpc")],
50401
+ rpcRoots: [join34(root, "rpc")],
50020
50402
  rpcDirs: rpcOverride ? [resolve26(rpcOverride)] : [],
50021
50403
  cacheKeepDirs: [
50022
50404
  ...new Set([
@@ -50032,7 +50414,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir7()) {
50032
50414
  }
50033
50415
  async function listDir(dir, blockers) {
50034
50416
  try {
50035
- return await readdir9(dir);
50417
+ return await readdir10(dir);
50036
50418
  } catch (error) {
50037
50419
  if (errorCode5(error) === "ENOENT")
50038
50420
  return [];
@@ -50056,7 +50438,7 @@ async function readArtifact(path2, blockers, malformedIsStale) {
50056
50438
  let mtimeMs;
50057
50439
  let regular;
50058
50440
  try {
50059
- const file = await open15(path2, "r");
50441
+ const file = await open16(path2, "r");
50060
50442
  try {
50061
50443
  text6 = await file.readFile("utf8");
50062
50444
  const stat16 = await file.stat();
@@ -50104,12 +50486,12 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
50104
50486
  const portDirs = [...locations.rpcDirs];
50105
50487
  for (const root of locations.rpcRoots)
50106
50488
  for (const name of await listDir(root, blockers))
50107
- portDirs.push(join33(root, name));
50489
+ portDirs.push(join34(root, name));
50108
50490
  for (const dir of [...new Set(portDirs)]) {
50109
50491
  for (const name of await listDir(dir, blockers)) {
50110
50492
  if (!/^port-\d+\.json$/.test(name))
50111
50493
  continue;
50112
- const path2 = join33(dir, name);
50494
+ const path2 = join34(dir, name);
50113
50495
  const filenamePid = publisherPid("rpc", name);
50114
50496
  const isStale = (startedAt2) => malformedIsStale(filenamePid, startedAt2);
50115
50497
  const record17 = await readArtifact(path2, blockers, isStale);
@@ -50131,7 +50513,7 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
50131
50513
  const match = /^(\d+)-.+\.json$/.exec(name);
50132
50514
  if (!match)
50133
50515
  continue;
50134
- const path2 = join33(dir, name);
50516
+ const path2 = join34(dir, name);
50135
50517
  const filenamePid = publisherPid("cachekeep", name);
50136
50518
  const record17 = await readArtifact(path2, blockers, (startedAt) => malformedIsStale(filenamePid, startedAt));
50137
50519
  if (record17 === undefined || exempt(record17.value))
@@ -50400,14 +50782,14 @@ import { isDeepStrictEqual as isDeepStrictEqual7 } from "node:util";
50400
50782
  import { parse as parse6 } from "jsonc-parser";
50401
50783
 
50402
50784
  // src/settings-move-sources.ts
50403
- import { lstat as lstat23, readFile as readFile20 } from "node:fs/promises";
50785
+ import { lstat as lstat24, readFile as readFile20 } from "node:fs/promises";
50404
50786
  var loggedSkips = new Set;
50405
50787
  async function peerStoreAbsent(host2, store, options) {
50406
50788
  try {
50407
50789
  const pool = await resolveNativePoolPaths(store.account, store.state, await peerLayout(host2, options));
50408
50790
  for (const config of [pool.config, nativeVaultPaths(pool).config]) {
50409
50791
  try {
50410
- await lstat23(config);
50792
+ await lstat24(config);
50411
50793
  return false;
50412
50794
  } catch (error) {
50413
50795
  if (error.code !== "ENOENT")
@@ -50560,7 +50942,7 @@ async function prepareSettingsMoveSources(options) {
50560
50942
  const pool = own && options.ownPoolPaths ? options.ownPoolPaths : await resolveNativePoolPaths(store.account, store.state, own ? undefined : await peerLayout(host2, options));
50561
50943
  const selected = mode === "claustrum" ? nativeVaultPaths(pool) : pool;
50562
50944
  try {
50563
- await lstat23(selected.config);
50945
+ await lstat24(selected.config);
50564
50946
  } catch (error) {
50565
50947
  if (error.code === "ENOENT") {
50566
50948
  skip(host2, selected.config, mode === "claustrum" ? "vault settings have not been seeded" : "file is missing");
@@ -50864,7 +51246,7 @@ async function startSettings(options) {
50864
51246
  refused2 = false;
50865
51247
  };
50866
51248
  const move = options.start?.move ?? runSettingsMoveAtStartup;
50867
- const open16 = options.start?.open ?? openSettingsService;
51249
+ const open17 = options.start?.open ?? openSettingsService;
50868
51250
  const diagnostic = {
50869
51251
  outcome: refused2 ? "authority-refused" : "startup-failed"
50870
51252
  };
@@ -50924,7 +51306,7 @@ async function startSettings(options) {
50924
51306
  adopted = moved && !started.importPending;
50925
51307
  if (!started.mayOpenService)
50926
51308
  return { mode: started.mode, file, diagnostic };
50927
- const service = track(await open16(serviceOptions(file)));
51309
+ const service = track(await open17(serviceOptions(file)));
50928
51310
  if (!service)
50929
51311
  return { mode: started.mode, file, diagnostic };
50930
51312
  if (started.importPending)
@@ -50941,7 +51323,7 @@ async function startSettings(options) {
50941
51323
  if (!file)
50942
51324
  return;
50943
51325
  try {
50944
- return track(await open16(serviceOptions(file)));
51326
+ return track(await open17(serviceOptions(file)));
50945
51327
  } catch {
50946
51328
  return;
50947
51329
  }
@@ -51072,20 +51454,20 @@ function executeLaneStartCommand(input) {
51072
51454
  };
51073
51455
  }
51074
51456
  // src/state-layout-decision.ts
51075
- import { mkdir as mkdir21, readdir as readdir11 } from "node:fs/promises";
51457
+ import { mkdir as mkdir22, readdir as readdir12 } from "node:fs/promises";
51076
51458
  import { homedir as homedir9 } from "node:os";
51077
- import { basename as basename17, dirname as dirname28, join as join36 } from "node:path";
51459
+ import { basename as basename17, dirname as dirname28, join as join37 } from "node:path";
51078
51460
 
51079
51461
  // src/state-layout-move.ts
51080
- import { randomUUID as randomUUID27 } from "node:crypto";
51081
- import { lstat as lstat24, readdir as readdir10, readFile as readFile22, stat as stat16, unlink as unlink12 } from "node:fs/promises";
51082
- import { basename as basename16, dirname as dirname27, join as join34, sep as sep2 } from "node:path";
51462
+ import { randomUUID as randomUUID28 } from "node:crypto";
51463
+ import { lstat as lstat25, readdir as readdir11, readFile as readFile22, stat as stat16, unlink as unlink12 } from "node:fs/promises";
51464
+ import { basename as basename16, dirname as dirname27, join as join35, sep as sep2 } from "node:path";
51083
51465
  var ACCOUNT_FILE = "anthropic-auth.json";
51084
51466
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
51085
51467
  var LAYOUT_LOCK_NAME = "runtime-layout";
51086
51468
  var LAYOUT_LOCK_TIMEOUT_MS = 120000;
51087
51469
  async function resolveLegacyDatasetFiles(configDir) {
51088
- const oldPaths = await resolveNativePoolPaths(join34(configDir, ACCOUNT_FILE), join34(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
51470
+ const oldPaths = await resolveNativePoolPaths(join35(configDir, ACCOUNT_FILE), join35(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
51089
51471
  return {
51090
51472
  oldDir: await canonicalPath2(configDir),
51091
51473
  oldPaths,
@@ -51093,8 +51475,8 @@ async function resolveLegacyDatasetFiles(configDir) {
51093
51475
  };
51094
51476
  }
51095
51477
  async function resolveRelocationDataset(input) {
51096
- const legacyConfig = join34(input.configDir, ACCOUNT_FILE);
51097
- const legacyState = join34(input.configDir, ACCOUNT_STATE_FILE);
51478
+ const legacyConfig = join35(input.configDir, ACCOUNT_FILE);
51479
+ const legacyState = join35(input.configDir, ACCOUNT_STATE_FILE);
51098
51480
  const { oldDir, oldPaths, oldVault } = await resolveLegacyDatasetFiles(input.configDir);
51099
51481
  const stateHome = { kind: "state-home", dir: input.sub };
51100
51482
  const newPaths = await resolveNativePoolPaths(legacyConfig, legacyState, stateHome);
@@ -51123,7 +51505,7 @@ async function resolveRelocationDataset(input) {
51123
51505
  role,
51124
51506
  from: pairs[role][0],
51125
51507
  to: pairs[role][1],
51126
- configured: join34(input.configDir, STATE_HOME_FILE_NAMES[role])
51508
+ configured: join35(input.configDir, STATE_HOME_FILE_NAMES[role])
51127
51509
  })),
51128
51510
  storageIds: { local: oldPaths.storageId, vault: oldVault.storageId }
51129
51511
  };
@@ -51145,8 +51527,8 @@ function errorCode6(error) {
51145
51527
  }
51146
51528
  function transitionHolderFiles(dataset) {
51147
51529
  return [
51148
- join34(dataset.oldDir, HOLDER_FILE_NAME),
51149
- join34(dataset.sub, HOLDER_FILE_NAME)
51530
+ join35(dataset.oldDir, HOLDER_FILE_NAME),
51531
+ join35(dataset.sub, HOLDER_FILE_NAME)
51150
51532
  ].sort();
51151
51533
  }
51152
51534
  async function acquireHolderLock(ctx, holderFile, timeoutMs) {
@@ -51163,7 +51545,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
51163
51545
  }
51164
51546
  }
51165
51547
  async function acquireHolderLocks(dataset, ctx) {
51166
- const oldHolders = join34(dataset.oldDir, HOLDER_FILE_NAME);
51548
+ const oldHolders = join35(dataset.oldDir, HOLDER_FILE_NAME);
51167
51549
  for (const file of transitionHolderFiles(dataset)) {
51168
51550
  if (file === oldHolders)
51169
51551
  await stateLayoutStep(ctx, "old-holders-locking");
@@ -51369,7 +51751,7 @@ function restoringPath(path2, attempt) {
51369
51751
  }
51370
51752
  async function exists5(path2) {
51371
51753
  try {
51372
- await lstat24(path2);
51754
+ await lstat25(path2);
51373
51755
  return true;
51374
51756
  } catch (error) {
51375
51757
  if (errorCode6(error) === "ENOENT")
@@ -51379,7 +51761,7 @@ async function exists5(path2) {
51379
51761
  }
51380
51762
  async function removeOwnStaging(path2) {
51381
51763
  try {
51382
- const info = await lstat24(path2);
51764
+ const info = await lstat25(path2);
51383
51765
  if (info.isFile())
51384
51766
  await unlink12(path2);
51385
51767
  } catch (error) {
@@ -51422,7 +51804,7 @@ async function movePreconditionFailure(dataset, platform) {
51422
51804
  for (const path2 of new Set([slot.configured, slot.from])) {
51423
51805
  let info;
51424
51806
  try {
51425
- info = await lstat24(path2);
51807
+ info = await lstat25(path2);
51426
51808
  } catch (error) {
51427
51809
  if (errorCode6(error) === "ENOENT")
51428
51810
  continue;
@@ -51439,7 +51821,7 @@ async function movePreconditionFailure(dataset, platform) {
51439
51821
  anyOld ||= fromExists;
51440
51822
  if (await exists5(slot.to)) {
51441
51823
  if (fromExists) {
51442
- const [a, b] = await Promise.all([lstat24(slot.from), lstat24(slot.to)]);
51824
+ const [a, b] = await Promise.all([lstat25(slot.from), lstat25(slot.to)]);
51443
51825
  if (a.dev === b.dev && a.ino === b.ino)
51444
51826
  return `${slot.from} and ${slot.to} are the same file`;
51445
51827
  }
@@ -51577,9 +51959,9 @@ async function rollbackPreparing(record17, dataset, ctx) {
51577
51959
  continue;
51578
51960
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
51579
51961
  }
51580
- for (const name of await readdir10(dataset.sub))
51962
+ for (const name of await readdir11(dataset.sub))
51581
51963
  if (isLayoutRecordStage(name, attempt))
51582
- await removeOwnStaging(join34(dataset.sub, name));
51964
+ await removeOwnStaging(join35(dataset.sub, name));
51583
51965
  await stateLayoutStep(ctx, "rollback:destination-removed");
51584
51966
  await ctx.fs.syncDirectory(dataset.sub);
51585
51967
  await stateLayoutStep(ctx, "rollback:sub-flushed");
@@ -51682,7 +52064,7 @@ class MoveRefused extends Error {
51682
52064
  }
51683
52065
  }
51684
52066
  async function moveDataset(dataset, ctx, checkArtifacts) {
51685
- const attempt = randomUUID27();
52067
+ const attempt = randomUUID28();
51686
52068
  const files = [];
51687
52069
  for (const slot of dataset.slots)
51688
52070
  files.push({
@@ -51693,7 +52075,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
51693
52075
  });
51694
52076
  const sha = (role) => files.find((file) => file.role === role)?.sha256 ?? null;
51695
52077
  await ctx.stack.assertAll();
51696
- const configDirPath = join34(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
52078
+ const configDirPath = join35(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
51697
52079
  if (!await exists5(configDirPath)) {
51698
52080
  const stage = `${configDirPath}.${attempt}.tmp`;
51699
52081
  await createOwnerOnlyFile(ctx.fs, stage, Buffer.from(`${JSON.stringify({ version: 1, identity: dataset.identity })}
@@ -51704,7 +52086,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
51704
52086
  await removeOwnStaging(stage);
51705
52087
  }
51706
52088
  }
51707
- const holderFile = join34(dataset.sub, HOLDER_FILE_NAME);
52089
+ const holderFile = join35(dataset.sub, HOLDER_FILE_NAME);
51708
52090
  if (!await exists5(holderFile))
51709
52091
  await writeJsonAtomic(holderFile, { version: 1, entries: [] }, {
51710
52092
  beforeRename: () => ctx.stack.assertAll(),
@@ -51855,10 +52237,10 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
51855
52237
  }
51856
52238
 
51857
52239
  // src/state-layout-restore.ts
51858
- import { randomUUID as randomUUID28 } from "node:crypto";
52240
+ import { randomUUID as randomUUID29 } from "node:crypto";
51859
52241
  import { readFile as readFile23 } from "node:fs/promises";
51860
52242
  import { homedir as homedir8 } from "node:os";
51861
- import { join as join35 } from "node:path";
52243
+ import { join as join36 } from "node:path";
51862
52244
  var DATA_ROLES = [
51863
52245
  "localPoolState",
51864
52246
  "localRoster",
@@ -52134,7 +52516,7 @@ async function newRestoreProblems(record17, dataset, options) {
52134
52516
  if (await exists5(path2))
52135
52517
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
52136
52518
  }
52137
- problems.push(...await holderProblems(join35(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join35(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
52519
+ problems.push(...await holderProblems(join36(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join36(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
52138
52520
  const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir8());
52139
52521
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
52140
52522
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
@@ -52156,7 +52538,7 @@ async function startRestore(record17, dataset, ctx, options) {
52156
52538
  const problems = await newRestoreProblems(record17, dataset, options);
52157
52539
  if (problems.length)
52158
52540
  throw refused2(`anthropic-auth can't restore its state to ${dataset.oldDir} yet: ${problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir, dataset.sub]);
52159
- const attempt = randomUUID28();
52541
+ const attempt = randomUUID29();
52160
52542
  const files = [];
52161
52543
  for (const slot of dataset.slots) {
52162
52544
  let digest2;
@@ -52323,7 +52705,7 @@ async function restoreLegacyLayout(options = {}) {
52323
52705
  break;
52324
52706
  case "restore-staged": {
52325
52707
  await syncObservedRestoreRecord(dataset, ctx);
52326
- const problems = await holderProblems(join35(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
52708
+ const problems = await holderProblems(join36(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
52327
52709
  if (problems.length)
52328
52710
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${problems.join("; ")}. Close them, then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.sub]);
52329
52711
  result = await finishStagedRestore(record17, dataset, ctx);
@@ -52445,8 +52827,8 @@ async function preflightOpenCodeAuthority(configDir, env, home) {
52445
52827
  return;
52446
52828
  }
52447
52829
  }
52448
- const config = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join36(configDir, ACCOUNT_FILE2);
52449
- const state = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (config.endsWith(ACCOUNT_FILE2) ? join36(dirname28(config), ACCOUNT_STATE_FILE2) : `${config}.state.json`);
52830
+ const config = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join37(configDir, ACCOUNT_FILE2);
52831
+ const state = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (config.endsWith(ACCOUNT_FILE2) ? join37(dirname28(config), ACCOUNT_STATE_FILE2) : `${config}.state.json`);
52450
52832
  await preflightExistingAuthority(await resolveNativePoolPaths(config, state, LEGACY_STATE_LAYOUT), "opencode", env);
52451
52833
  }
52452
52834
  async function registerHeld(holderFile, paths2, kind, identity5, options, ctx) {
@@ -52481,7 +52863,7 @@ function deferLegacyRegistration(paths2, dir, options, error) {
52481
52863
  }
52482
52864
  async function registerLegacyHeld(oldDir, paths2, identity5, options, ctx) {
52483
52865
  try {
52484
- await registerHeld(join36(oldDir, HOLDER_FILE_NAME), paths2, "legacy", identity5, options, ctx);
52866
+ await registerHeld(join37(oldDir, HOLDER_FILE_NAME), paths2, "legacy", identity5, options, ctx);
52485
52867
  return {
52486
52868
  status: "registered",
52487
52869
  settled: Promise.resolve(),
@@ -52518,14 +52900,14 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
52518
52900
  throw conflict;
52519
52901
  }
52520
52902
  await warnReappearedMetadata(record17);
52521
- await registerHeld(join36(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
52903
+ await registerHeld(join37(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
52522
52904
  const layout = { kind: "state-home", dir: dataset.sub };
52523
52905
  recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
52524
52906
  return { kind: "state-home", layout, dataset, record: record17, moved };
52525
52907
  }
52526
52908
  async function admitFast(dataset, options, ctx) {
52527
52909
  try {
52528
- await acquireHolderLock(ctx, join36(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
52910
+ await acquireHolderLock(ctx, join37(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
52529
52911
  } catch (error) {
52530
52912
  if (error instanceof LockContentionError)
52531
52913
  busy(dataset.configDir, error);
@@ -52590,7 +52972,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
52590
52972
  }
52591
52973
  let names2;
52592
52974
  try {
52593
- names2 = await readdir11(dirname28(journal));
52975
+ names2 = await readdir12(dirname28(journal));
52594
52976
  } catch (error) {
52595
52977
  if (error?.code === "ENOENT")
52596
52978
  return false;
@@ -52633,7 +53015,7 @@ async function legacyWhileMoveOff(configDir, identity5, options, ctx, stayReason
52633
53015
  await stateLayoutStep(ctx, "old-holders-locking");
52634
53016
  let lockFailure2;
52635
53017
  try {
52636
- await acquireHolderLock(ctx, join36(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
53018
+ await acquireHolderLock(ctx, join37(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
52637
53019
  } catch (error) {
52638
53020
  lockFailure2 = { error };
52639
53021
  }
@@ -52665,8 +53047,8 @@ async function decideOpenCodeStateLayout(options) {
52665
53047
  holderLockTimeoutMs: options.timeouts?.holderMs
52666
53048
  });
52667
53049
  if (isExplicit(env)) {
52668
- const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join36(configDir, ACCOUNT_FILE2);
52669
- const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join36(dirname28(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
53050
+ const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join37(configDir, ACCOUNT_FILE2);
53051
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join37(dirname28(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
52670
53052
  const paths2 = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
52671
53053
  const registration = await registerNativePoolHolder({
52672
53054
  paths: paths2,
@@ -52689,7 +53071,7 @@ async function decideOpenCodeStateLayout(options) {
52689
53071
  } catch (error) {
52690
53072
  if (unmovedRegistrationPolicy(options) === "mandatory")
52691
53073
  throw new HolderRegistrationError("unavailable", configDir, error);
52692
- const paths2 = await resolveNativePoolPaths(join36(configDir, ACCOUNT_FILE2), join36(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
53074
+ const paths2 = await resolveNativePoolPaths(join37(configDir, ACCOUNT_FILE2), join37(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
52693
53075
  return chooseLegacy(paths2, [reason], true, deferLegacyRegistration(paths2, configDir, options, error));
52694
53076
  }
52695
53077
  identity5 = configIdentity(configDir);
@@ -52759,7 +53141,7 @@ async function decideOpenCodeStateLayout(options) {
52759
53141
  try {
52760
53142
  await stateLayoutStep(ctx, "old-holders-locking");
52761
53143
  try {
52762
- await acquireHolderLock(ctx, join36(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
53144
+ await acquireHolderLock(ctx, join37(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
52763
53145
  } catch (error) {
52764
53146
  if (unmovedRegistrationPolicy(options) === "mandatory")
52765
53147
  throw error;
@@ -52823,7 +53205,7 @@ async function ensureSubfolder(sub, fs5) {
52823
53205
  await ensureWindowsOwnerOnlyDirectory(sub);
52824
53206
  return;
52825
53207
  }
52826
- const created = await mkdir21(sub, { recursive: true, mode: 448 });
53208
+ const created = await mkdir22(sub, { recursive: true, mode: 448 });
52827
53209
  if (created === undefined)
52828
53210
  return;
52829
53211
  for (let dir = dirname28(sub);; dir = dirname28(dir)) {
@@ -53346,6 +53728,7 @@ export {
53346
53728
  quotaRefusalTiming,
53347
53729
  quotaRefusalRetryAfterSeconds,
53348
53730
  quotaRefusalDetails,
53731
+ quotaPollCheckedAt,
53349
53732
  quotaFieldSource,
53350
53733
  quotaExhaustionFromHeaders,
53351
53734
  quotaEnabled,