@cortexkit/anthropic-auth-core 2.14.0 → 2.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8543,7 +8543,20 @@ import { setTimeout as delay } from "node:timers/promises";
8543
8543
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
8544
8544
 
8545
8545
  // ../../node_modules/@cortexkit/common-auth/dist/setup/process-fence.js
8546
+ import { statSync as statSync3 } from "node:fs";
8547
+ import { win32 as win322 } from "node:path";
8546
8548
  var WINDOWS_CIM_TIMEOUT_MS = 45000;
8549
+ var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 90000;
8550
+ function isFile(file) {
8551
+ try {
8552
+ return statSync3(file).isFile();
8553
+ } catch {
8554
+ return false;
8555
+ }
8556
+ }
8557
+ function windowsEnv(env, name) {
8558
+ return Object.entries(env).find(([key]) => key.toUpperCase() === name.toUpperCase())?.[1];
8559
+ }
8547
8560
  var HOSTS = new Set(["opencode", "litecode", "opencode2", "pi"]);
8548
8561
  var RUNTIMES = new Set(["node", "bun"]);
8549
8562
  var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
@@ -8616,6 +8629,7 @@ function hostName(command) {
8616
8629
  class ProcessInspectionError extends Error {
8617
8630
  code = "process-inspection-failed";
8618
8631
  step;
8632
+ program;
8619
8633
  exitCode;
8620
8634
  signal;
8621
8635
  timedOut;
@@ -8624,6 +8638,7 @@ class ProcessInspectionError extends Error {
8624
8638
  super("Process inspection failed; setup cannot prove hosts are stopped.");
8625
8639
  this.name = "ProcessInspectionError";
8626
8640
  this.step = details.step;
8641
+ this.program = details.program;
8627
8642
  this.exitCode = details.exitCode;
8628
8643
  this.signal = details.signal;
8629
8644
  this.timedOut = details.timedOut;
@@ -8653,6 +8668,8 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
8653
8668
  }
8654
8669
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8655
8670
  const windows = (options.platform ?? process.platform) === "win32";
8671
+ const env = options.env ?? process.env;
8672
+ const system32 = windows ? win322.resolve(windowsEnv(env, "SystemRoot") ?? windowsEnv(env, "windir") ?? "C:\\Windows", "System32") : "";
8656
8673
  const selfPid = options.selfPid ?? process.pid;
8657
8674
  let inspection = {
8658
8675
  step: windows ? "tasklist" : "ps",
@@ -8661,10 +8678,11 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8661
8678
  timedOut: false,
8662
8679
  durationMs: 0
8663
8680
  };
8664
- const inspect = async (step, file, args, timeoutMs) => {
8681
+ const inspect = async (step, file, args, timeoutMs, program) => {
8665
8682
  const started = performance.now();
8666
8683
  inspection = {
8667
8684
  step,
8685
+ ...program && { program },
8668
8686
  exitCode: null,
8669
8687
  signal: null,
8670
8688
  timedOut: false,
@@ -8677,6 +8695,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8677
8695
  });
8678
8696
  inspection = {
8679
8697
  step,
8698
+ ...program && { program },
8680
8699
  exitCode: result.exitCode,
8681
8700
  signal: result.signal ?? null,
8682
8701
  timedOut: result.timedOut ?? false,
@@ -8689,9 +8708,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8689
8708
  options.onStep?.({ ...inspection });
8690
8709
  }
8691
8710
  };
8711
+ const inspectCim = (args) => {
8712
+ const pwsh = win322.resolve(windowsEnv(env, "ProgramFiles") ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
8713
+ const program = (options.isFile ?? isFile)(pwsh) ? "pwsh" : "powershell";
8714
+ const arm64 = (windowsEnv(env, "PROCESSOR_ARCHITEW6432") ?? windowsEnv(env, "PROCESSOR_ARCHITECTURE"))?.toUpperCase() === "ARM64";
8715
+ const slow = program === "powershell" && arm64;
8716
+ if (slow)
8717
+ options.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");
8718
+ return inspect("CIM", program === "pwsh" ? pwsh : win322.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
8719
+ };
8692
8720
  try {
8693
8721
  if (windows && options.hostImagesOnly) {
8694
- const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
8722
+ const details = await inspectCim([
8723
+ "-NoProfile",
8724
+ "-NonInteractive",
8725
+ "-Command",
8726
+ WINDOWS_FENCE_QUERY
8727
+ ]);
8695
8728
  if (details.exitCode !== 0)
8696
8729
  throw new ProcessInspectionError(inspection);
8697
8730
  const value = JSON.parse(details.stdout);
@@ -8713,7 +8746,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8713
8746
  }
8714
8747
  return processes2;
8715
8748
  }
8716
- const result = await inspect(windows ? "tasklist" : "ps", windows ? "tasklist.exe" : "ps", windows ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
8749
+ const result = await inspect(windows ? "tasklist" : "ps", windows ? win322.resolve(system32, "tasklist.exe") : "ps", windows ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
8717
8750
  if (result.exitCode !== 0)
8718
8751
  throw new ProcessInspectionError(inspection);
8719
8752
  const processes = [];
@@ -8747,12 +8780,12 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8747
8780
  throw new ProcessInspectionError(inspection);
8748
8781
  const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
8749
8782
  if (windows && runtimes.length && options.inspectRuntimes !== false) {
8750
- const details = await inspect("CIM", "powershell.exe", [
8783
+ const details = await inspectCim([
8751
8784
  "-NoProfile",
8752
8785
  "-NonInteractive",
8753
8786
  "-Command",
8754
8787
  `$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`
8755
- ], WINDOWS_CIM_TIMEOUT_MS);
8788
+ ]);
8756
8789
  if (details.exitCode !== 0)
8757
8790
  throw new ProcessInspectionError(inspection);
8758
8791
  const value = JSON.parse(details.stdout || "null");
@@ -8808,6 +8841,35 @@ async function assertHostsStopped(fence, env) {
8808
8841
  throw new ProcessFenceViolationError(active);
8809
8842
  }
8810
8843
 
8844
+ // ../../node_modules/@cortexkit/common-auth/dist/setup/process-guard.js
8845
+ class SetupProcessGuard {
8846
+ inspect;
8847
+ now;
8848
+ #checkedAt;
8849
+ constructor(inspect, now = () => performance.now()) {
8850
+ this.inspect = inspect;
8851
+ this.now = now;
8852
+ }
8853
+ async check(options = {}) {
8854
+ if (options.reuse && this.#checkedAt !== undefined) {
8855
+ const age = this.now() - this.#checkedAt;
8856
+ if (age >= 0 && age < 5000)
8857
+ return;
8858
+ }
8859
+ this.#checkedAt = undefined;
8860
+ await this.inspect();
8861
+ this.#checkedAt = this.now();
8862
+ }
8863
+ async step(run) {
8864
+ this.#checkedAt = undefined;
8865
+ try {
8866
+ return await run();
8867
+ } finally {
8868
+ this.#checkedAt = undefined;
8869
+ }
8870
+ }
8871
+ }
8872
+
8811
8873
  // ../../node_modules/@cortexkit/common-auth/dist/setup/enroll.js
8812
8874
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
8813
8875
  var UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
@@ -8837,7 +8899,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8837
8899
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
8838
8900
  const { name, displayName, requestedGrants, grantFallback, paths: input } = plugin.vault.hosts[host];
8839
8901
  const paths = hostEnrollmentPaths(input);
8840
- await fence();
8902
+ const guard = typeof fence === "function" ? new SetupProcessGuard(fence, io.now) : fence;
8903
+ await guard.check({ reuse: true });
8841
8904
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
8842
8905
  connectionFile: plugin.vault.connectionFile,
8843
8906
  handshakeTimeoutMs: 2000
@@ -8854,11 +8917,10 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8854
8917
  paths,
8855
8918
  client,
8856
8919
  writeTokenFile: async (path, file) => {
8857
- await fence();
8858
- await writeEnrollmentTokenFile2(path, file);
8920
+ await guard.check();
8921
+ await guard.step(() => writeEnrollmentTokenFile2(path, file));
8859
8922
  }
8860
8923
  });
8861
- await fence();
8862
8924
  const initial = await manager.status();
8863
8925
  if (initial.state === "approved") {
8864
8926
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
@@ -8875,7 +8937,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8875
8937
  let reportedCode;
8876
8938
  let failedProposals = 0;
8877
8939
  for (;; ) {
8878
- const status = await manager.reconcile();
8940
+ await guard.check({ reuse: true });
8941
+ const status = await guard.step(() => manager.reconcile());
8879
8942
  if (status.state === "approved") {
8880
8943
  printLine(terminal, `Connected ${host} to Claustrum.`);
8881
8944
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
@@ -8923,8 +8986,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8923
8986
  const remaining = deadline - now();
8924
8987
  if (remaining <= 0)
8925
8988
  break;
8926
- await wait(Math.min(pause, remaining));
8927
- await fence();
8989
+ await guard.step(() => wait(Math.min(pause, remaining)));
8990
+ await guard.check();
8928
8991
  }
8929
8992
  if (printedRequest)
8930
8993
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -9084,6 +9147,8 @@ async function selectSetupHosts(terminal, found) {
9084
9147
  }
9085
9148
 
9086
9149
  // ../../node_modules/@cortexkit/common-auth/dist/setup/register.js
9150
+ import { rename as rename6 } from "node:fs/promises";
9151
+ import { setTimeout as delay3 } from "node:timers/promises";
9087
9152
  import { domainToUnicode } from "node:url";
9088
9153
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2, parseTree } from "jsonc-parser";
9089
9154
 
@@ -9295,12 +9360,14 @@ function planOpenCodeRegistration(plugin, generation, io = {}) {
9295
9360
  });
9296
9361
  }
9297
9362
  async function registerOpenCode(writes, beforeWrite) {
9363
+ const guard = typeof beforeWrite === "function" ? new SetupProcessGuard(beforeWrite) : beforeWrite;
9298
9364
  for (const write of writes) {
9299
9365
  if (!write.changed)
9300
9366
  continue;
9301
- await beforeWrite?.();
9302
9367
  await writeHostConfigAtomic(write.path, write.content, {
9303
- beforeRename: beforeWrite
9368
+ beforeRename: guard ? () => guard.check({ reuse: true }) : undefined,
9369
+ rename: guard ? (from, to) => guard.step(() => rename6(from, to)) : undefined,
9370
+ wait: guard ? (ms) => guard.step(() => delay3(ms)) : undefined
9304
9371
  });
9305
9372
  }
9306
9373
  }
@@ -9401,7 +9468,11 @@ async function runSetup(plugin, argv = [], io = {}) {
9401
9468
  return { hosts, dryRun: options.dryRun, mode: "local", detection };
9402
9469
  }
9403
9470
  const { env, platform } = setupPaths(io);
9404
- const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, { platform });
9471
+ const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, {
9472
+ platform,
9473
+ isFile: io.fs?.isFile.bind(io.fs),
9474
+ onProgress: (line) => printLine(terminal, line)
9475
+ });
9405
9476
  const stopped = async () => {
9406
9477
  try {
9407
9478
  await assertHostsStopped(fence, env);
@@ -9411,6 +9482,7 @@ async function runSetup(plugin, argv = [], io = {}) {
9411
9482
  throw error;
9412
9483
  }
9413
9484
  };
9485
+ const guard = new SetupProcessGuard(stopped, io.now);
9414
9486
  printLine(terminal, "Checking that OpenCode and Pi are not running…");
9415
9487
  if (options.dryRun) {
9416
9488
  try {
@@ -9426,16 +9498,17 @@ async function runSetup(plugin, argv = [], io = {}) {
9426
9498
  if (error instanceof ProcessInspectionError)
9427
9499
  printLine(terminal, error.refusalText);
9428
9500
  }
9429
- } else
9430
- await stopped();
9501
+ } else {
9502
+ await guard.check();
9503
+ }
9431
9504
  if ((options.claustrum || options.enrollOnly) && !detection.claustrum.available)
9432
9505
  throw new Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");
9433
9506
  let useVault = options.claustrum || options.enrollOnly;
9434
9507
  if (!useVault && !options.login && !options.noClaustrum && !assumeYes && detection.claustrum.available && isInteractive(terminal)) {
9435
- const choice = await select(terminal, [
9508
+ const choice = await guard.step(() => select(terminal, [
9436
9509
  { label: "No", value: false },
9437
9510
  { label: "Yes", value: true }
9438
- ], { message: "Connect these hosts to the Claustrum vault?" });
9511
+ ], { message: "Connect these hosts to the Claustrum vault?" }));
9439
9512
  if (choice === null) {
9440
9513
  printLine(terminal, "Setup cancelled. Nothing was changed.");
9441
9514
  return { hosts: [], dryRun: options.dryRun, mode: "local", detection };
@@ -9486,13 +9559,14 @@ ${write.content}`);
9486
9559
  const enrollmentAccess = new Map;
9487
9560
  try {
9488
9561
  for (const host of hosts) {
9489
- await stopped();
9490
- await plugin.beforeSignIn?.(host, context);
9491
- await stopped();
9562
+ if (plugin.beforeSignIn) {
9563
+ await guard.check({ reuse: true });
9564
+ await guard.step(() => plugin.beforeSignIn?.(host, context));
9565
+ }
9492
9566
  if (useVault) {
9493
9567
  enrollment.set(host, "unknown");
9494
9568
  try {
9495
- const access = await connectSetupHost(plugin, host, io, terminal, stopped);
9569
+ const access = await connectSetupHost(plugin, host, io, terminal, guard);
9496
9570
  if (access)
9497
9571
  enrollmentAccess.set(host, access);
9498
9572
  } catch (error) {
@@ -9501,19 +9575,26 @@ ${write.content}`);
9501
9575
  throw error;
9502
9576
  }
9503
9577
  enrollment.set(host, "enrolled");
9504
- } else
9505
- await plugin.signInLocal(host, context);
9506
- await stopped();
9578
+ } else {
9579
+ await guard.check({ reuse: true });
9580
+ await guard.step(() => plugin.signInLocal(host, context));
9581
+ }
9507
9582
  if (options.enrollOnly)
9508
9583
  continue;
9509
- await plugin.beforeRegister?.(host, mode, context);
9510
- await stopped();
9584
+ if (plugin.beforeRegister) {
9585
+ await guard.check({ reuse: true });
9586
+ await guard.step(() => plugin.beforeRegister?.(host, mode, context));
9587
+ }
9511
9588
  if (host === "opencode")
9512
- await registerOpenCode(writes, stopped);
9513
- else
9514
- await registerPi(plugin, detection.pi.executable, io);
9515
- await stopped();
9516
- await plugin.migrate?.(host, context);
9589
+ await registerOpenCode(writes, guard);
9590
+ else {
9591
+ await guard.check({ reuse: true });
9592
+ await guard.step(() => registerPi(plugin, detection.pi.executable, io));
9593
+ }
9594
+ if (plugin.migrate) {
9595
+ await guard.check({ reuse: true });
9596
+ await guard.step(() => plugin.migrate?.(host, context));
9597
+ }
9517
9598
  }
9518
9599
  } catch (error) {
9519
9600
  if (enrollment.size === 0)
@@ -9537,12 +9618,12 @@ ${write.content}`);
9537
9618
  }
9538
9619
  // src/accounts.ts
9539
9620
  import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
9540
- import { mkdir as mkdir6, readFile as readFile7, rename as rename7, rm as rm4, stat as stat10, writeFile } from "node:fs/promises";
9621
+ import { mkdir as mkdir6, readFile as readFile7, rename as rename8, rm as rm4, stat as stat10, writeFile } from "node:fs/promises";
9541
9622
  import { homedir as homedir3 } from "node:os";
9542
9623
  import { join as join13 } from "node:path";
9543
9624
 
9544
9625
  // src/claustrum.ts
9545
- import { readdirSync, statSync as statSync3 } from "node:fs";
9626
+ import { readdirSync, statSync as statSync4 } from "node:fs";
9546
9627
  import * as fs from "node:fs/promises";
9547
9628
  import { tmpdir as tmpdir3, userInfo } from "node:os";
9548
9629
  import { join as join9 } from "node:path";
@@ -9554,7 +9635,7 @@ var CLAUSTRUM_TEMP_PREFIX = "subc-";
9554
9635
  var CLAUSTRUM_TEMP_SUFFIX = ".connection.json";
9555
9636
  function safeIsFile(path) {
9556
9637
  try {
9557
- return statSync3(path).isFile();
9638
+ return statSync4(path).isFile();
9558
9639
  } catch {
9559
9640
  return false;
9560
9641
  }
@@ -10323,8 +10404,8 @@ async function refreshClaudeOAuthToken(input) {
10323
10404
  for (let attempt = 0;attempt <= maxRetries; attempt++) {
10324
10405
  try {
10325
10406
  if (attempt > 0) {
10326
- const delay3 = baseDelayMs * 2 ** (attempt - 1);
10327
- await new Promise((resolve12) => setTimeoutImpl(resolve12, delay3));
10407
+ const delay4 = baseDelayMs * 2 ** (attempt - 1);
10408
+ await new Promise((resolve12) => setTimeoutImpl(resolve12, delay4));
10328
10409
  }
10329
10410
  const signal = auxiliaryRequestSignal();
10330
10411
  const response = await raceWithSignal(signal, () => fetchImpl(TOKEN_URL, {
@@ -10497,7 +10578,7 @@ function hostRetryResponse(response, now = Date.now()) {
10497
10578
  // src/path-options.ts
10498
10579
  import { realpath as realpath3 } from "node:fs/promises";
10499
10580
  import { homedir as homedir2 } from "node:os";
10500
- import { posix as posix3, win32 as win323 } from "node:path";
10581
+ import { posix as posix3, win32 as win324 } from "node:path";
10501
10582
 
10502
10583
  // ../../node_modules/@cortexkit/common-auth/dist/settings/descriptors.js
10503
10584
  function boolean() {
@@ -10611,7 +10692,7 @@ function isOverrideKeyAllowed(overrides, key) {
10611
10692
  import { join as join11, resolve as resolve13 } from "node:path";
10612
10693
 
10613
10694
  // ../../node_modules/@cortexkit/common-auth/dist/tui-prefs/watcher.js
10614
- import { lstatSync, readFileSync as readFileSync2, readlinkSync, realpathSync as realpathSync2, statSync as statSync4, watch } from "node:fs";
10695
+ import { lstatSync, readFileSync as readFileSync2, readlinkSync, realpathSync as realpathSync2, statSync as statSync5, watch } from "node:fs";
10615
10696
  import { readFile as readFile5, stat as stat8 } from "node:fs/promises";
10616
10697
  import { basename as basename5, dirname as dirname9, join as join10, resolve as resolve12 } from "node:path";
10617
10698
  import { clearTimeout as clearTimeout2, setTimeout as setTimeout2 } from "node:timers";
@@ -10655,7 +10736,7 @@ function watchFile(file, onChange, options, settings) {
10655
10736
  let lastSeen = null;
10656
10737
  if (settings || !windowsPrivateFiles)
10657
10738
  try {
10658
- const metadata = identity2((options.fs?.statSync ?? statSync4)(path), settings);
10739
+ const metadata = identity2((options.fs?.statSync ?? statSync5)(path), settings);
10659
10740
  lastSeen = (options.fs?.readFileSync ?? ((file2) => readFileSync2(file2, "utf8")))(path);
10660
10741
  lastMetadata = metadata;
10661
10742
  } catch {}
@@ -12096,7 +12177,7 @@ async function moveSettingsOnce(options) {
12096
12177
  }
12097
12178
  }
12098
12179
  // ../../node_modules/@cortexkit/common-auth/dist/settings/paths.js
12099
- import { posix as posix2, win32 as win322 } from "node:path";
12180
+ import { posix as posix2, win32 as win323 } from "node:path";
12100
12181
  function isAbsoluteForPlatform(path, platform) {
12101
12182
  if (platform !== "win32")
12102
12183
  return path.startsWith("/");
@@ -12107,7 +12188,7 @@ function isAbsoluteForPlatform(path, platform) {
12107
12188
  return /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(path);
12108
12189
  }
12109
12190
  function cortexkitConfigDir({ env, platform, homedir: homedir2 }) {
12110
- const paths = platform === "win32" ? win322 : posix2;
12191
+ const paths = platform === "win32" ? win323 : posix2;
12111
12192
  const absolute = (value) => value !== undefined && isAbsoluteForPlatform(value, platform);
12112
12193
  let base;
12113
12194
  if (absolute(env.XDG_CONFIG_HOME)) {
@@ -12130,7 +12211,7 @@ function settingsFilePath({ plugin, override, ...options }) {
12130
12211
  if (override && isAbsoluteForPlatform(override, options.platform)) {
12131
12212
  return override;
12132
12213
  }
12133
- const paths = options.platform === "win32" ? win322 : posix2;
12214
+ const paths = options.platform === "win32" ? win323 : posix2;
12134
12215
  return paths.join(cortexkitConfigDir(options), `${plugin}.jsonc`);
12135
12216
  }
12136
12217
  // src/path-options.ts
@@ -12144,7 +12225,7 @@ function resolvePathOptions(options = {}) {
12144
12225
  home,
12145
12226
  platform,
12146
12227
  realpath: options.realpath ?? realpath3,
12147
- paths: platform === "win32" ? win323 : posix3
12228
+ paths: platform === "win32" ? win324 : posix3
12148
12229
  };
12149
12230
  }
12150
12231
 
@@ -12591,7 +12672,7 @@ async function acquireRefreshFileLock2(options) {
12591
12672
  await options.onStep?.("stale-marker-stat");
12592
12673
  const claimedPath = `${evictPath}.${randomUUID8()}`;
12593
12674
  try {
12594
- await rename7(evictPath, claimedPath);
12675
+ await rename8(evictPath, claimedPath);
12595
12676
  } catch (renameError) {
12596
12677
  if (renameError.code === "ENOENT") {
12597
12678
  await backoff();
@@ -12720,15 +12801,15 @@ function buildRefreshOperationError(input) {
12720
12801
  const previousRetryCount = input.previous?.accountIdentity === input.accountIdentity && input.previous?.refreshTokenFingerprint === input.refreshTokenFingerprint ? input.previous?.retryCount ?? 0 : 0;
12721
12802
  const retryCount = previousRetryCount + 1;
12722
12803
  const retryAfterFromError = input.error.retryAfter;
12723
- let delay3;
12804
+ let delay4;
12724
12805
  if (typeof retryAfterFromError === "number" && retryAfterFromError > 0) {
12725
- delay3 = retryAfterFromError * 1000;
12806
+ delay4 = retryAfterFromError * 1000;
12726
12807
  } else if (isTransientNetworkError(input.error)) {
12727
- delay3 = MIN_REFRESH_RETRY_DELAY_MS;
12808
+ delay4 = MIN_REFRESH_RETRY_DELAY_MS;
12728
12809
  } else if (isTransientRefreshError(input.error)) {
12729
- delay3 = Math.min(MAX_REFRESH_RETRY_DELAY_MS, MIN_REFRESH_RETRY_DELAY_MS * 2 ** Math.min(retryCount - 1, 6));
12810
+ delay4 = Math.min(MAX_REFRESH_RETRY_DELAY_MS, MIN_REFRESH_RETRY_DELAY_MS * 2 ** Math.min(retryCount - 1, 6));
12730
12811
  } else {
12731
- delay3 = NON_TRANSIENT_REFRESH_RETRY_DELAY_MS;
12812
+ delay4 = NON_TRANSIENT_REFRESH_RETRY_DELAY_MS;
12732
12813
  }
12733
12814
  const statusFromError = input.error.status;
12734
12815
  const status = typeof statusFromError === "number" && Number.isFinite(statusFromError) ? statusFromError : undefined;
@@ -12738,7 +12819,7 @@ function buildRefreshOperationError(input) {
12738
12819
  return {
12739
12820
  message,
12740
12821
  checkedAt: input.now,
12741
- nextRetryAt: input.now + delay3,
12822
+ nextRetryAt: input.now + delay4,
12742
12823
  retryCount,
12743
12824
  accountIdentity: input.accountIdentity,
12744
12825
  refreshTokenFingerprint: input.refreshTokenFingerprint,
@@ -12800,11 +12881,11 @@ function isQuotaPolicyAuthError(error) {
12800
12881
  function buildQuotaOperationError(input) {
12801
12882
  const previousRetryCount = input.previous?.accountIdentity === input.accountIdentity ? input.previous?.retryCount ?? 0 : 0;
12802
12883
  const retryCount = previousRetryCount + 1;
12803
- const delay3 = isTransientQuotaError(input.error) ? Math.min(MAX_QUOTA_RETRY_DELAY_MS, MIN_QUOTA_RETRY_DELAY_MS * 2 ** Math.min(retryCount - 1, 6)) : NON_TRANSIENT_QUOTA_RETRY_DELAY_MS;
12884
+ const delay4 = isTransientQuotaError(input.error) ? Math.min(MAX_QUOTA_RETRY_DELAY_MS, MIN_QUOTA_RETRY_DELAY_MS * 2 ** Math.min(retryCount - 1, 6)) : NON_TRANSIENT_QUOTA_RETRY_DELAY_MS;
12804
12885
  return {
12805
12886
  message: formatErrorMessage(input.error),
12806
12887
  checkedAt: input.now,
12807
- nextRetryAt: input.now + delay3,
12888
+ nextRetryAt: input.now + delay4,
12808
12889
  retryCount,
12809
12890
  ...input.accountIdentity !== undefined && {
12810
12891
  accountIdentity: input.accountIdentity
@@ -13012,15 +13093,26 @@ function quotaRefusalTiming(input) {
13012
13093
  }
13013
13094
  const earliest = resetTimes.sort((a, b) => a.resetAt - b.resetAt)[0];
13014
13095
  const resetAt = earliest?.resetAt;
13015
- const wait = getMaxSameAccountWait(input.storage ?? null);
13016
- const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
13017
- const capMs = clampHostRetryMs(wait === "max" ? ttlMs : Number(wait) * 60000);
13018
13096
  return {
13019
13097
  resetAt,
13020
13098
  ...earliest ? { limitName: earliest.limitName } : {},
13021
- retryAfterSeconds: wait === "0" ? undefined : Math.max(1, Math.ceil(Math.min(resetAt === undefined ? 300000 : resetAt - now, capMs) / 1000))
13099
+ retryAfterSeconds: quotaRefusalRetryAfterSeconds({
13100
+ resetAt,
13101
+ storage: input.storage,
13102
+ sessionTtlMs: input.sessionTtlMs,
13103
+ now
13104
+ })
13022
13105
  };
13023
13106
  }
13107
+ function quotaRefusalRetryAfterSeconds(input) {
13108
+ const now = input.now ?? Date.now();
13109
+ const wait = getMaxSameAccountWait(input.storage ?? null);
13110
+ if (wait === "0")
13111
+ return;
13112
+ const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
13113
+ const capMs = clampHostRetryMs(wait === "max" ? ttlMs : Number(wait) * 60000);
13114
+ return Math.max(1, Math.ceil(Math.min(input.resetAt === undefined ? 300000 : input.resetAt - now, capMs) / 1000));
13115
+ }
13024
13116
  function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId, options) {
13025
13117
  return quotaRefusalTiming({
13026
13118
  ...options,
@@ -14752,16 +14844,16 @@ class CacheKeepManager {
14752
14844
  return;
14753
14845
  target.failures += 1;
14754
14846
  const now = this.now();
14755
- let delay3 = typeof this.backoff === "function" ? this.backoff({ sessionKey, failures: target.failures }) : this.backoff ?? DEFAULT_BACKOFF_MS;
14847
+ let delay4 = typeof this.backoff === "function" ? this.backoff({ sessionKey, failures: target.failures }) : this.backoff ?? DEFAULT_BACKOFF_MS;
14756
14848
  const deadline = this.lastRetryStart(target);
14757
14849
  const fastRetry = this.backoff === undefined && transient && now < deadline;
14758
14850
  if (fastRetry) {
14759
- delay3 = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
14851
+ delay4 = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
14760
14852
  }
14761
- target.backoffUntil = now + (Number.isFinite(delay3) && delay3 > 0 ? delay3 : 0);
14853
+ target.backoffUntil = now + (Number.isFinite(delay4) && delay4 > 0 ? delay4 : 0);
14762
14854
  this.clearRetry(target);
14763
14855
  if (fastRetry)
14764
- this.scheduleRetry(sessionKey, target, delay3);
14856
+ this.scheduleRetry(sessionKey, target, delay4);
14765
14857
  else if (target.plan) {
14766
14858
  this.schedulePlan(sessionKey, target, target.backoffUntil);
14767
14859
  }
@@ -14786,7 +14878,7 @@ class CacheKeepManager {
14786
14878
  this.clearIntervalImpl(target.retryTimer);
14787
14879
  target.retryTimer = undefined;
14788
14880
  }
14789
- scheduleRetry(sessionKey, target, delay3) {
14881
+ scheduleRetry(sessionKey, target, delay4) {
14790
14882
  target.retryTimer = this.setIntervalImpl(() => {
14791
14883
  this.clearRetry(target);
14792
14884
  return (async () => {
@@ -14796,7 +14888,7 @@ class CacheKeepManager {
14796
14888
  })().catch((error) => {
14797
14889
  this.log?.warn("cachekeep tick failed", classifyFailure(error, "send"));
14798
14890
  });
14799
- }, delay3);
14891
+ }, delay4);
14800
14892
  if (typeof target.retryTimer === "object" && "unref" in target.retryTimer) {
14801
14893
  target.retryTimer.unref();
14802
14894
  }
@@ -14984,7 +15076,7 @@ import {
14984
15076
  mkdir as mkdir7,
14985
15077
  open as open8,
14986
15078
  realpath as realpath4,
14987
- rename as rename8,
15079
+ rename as rename9,
14988
15080
  stat as stat11,
14989
15081
  unlink as unlink6
14990
15082
  } from "node:fs/promises";
@@ -15577,7 +15669,7 @@ async function writeStateAtomic2(path2, state, beforeRename) {
15577
15669
  descriptor = undefined;
15578
15670
  await chmod2(temporary, 384);
15579
15671
  await beforeRename();
15580
- await rename8(temporary, path2);
15672
+ await rename9(temporary, path2);
15581
15673
  } finally {
15582
15674
  await descriptor?.close().catch(() => {});
15583
15675
  await unlink6(temporary).catch(() => {});
@@ -15588,7 +15680,7 @@ async function writeTokenAtomic(path2, value, writeTokenFile, beforeRename) {
15588
15680
  try {
15589
15681
  await writeTokenFile(staged, value);
15590
15682
  await beforeRename();
15591
- await rename8(staged, path2);
15683
+ await rename9(staged, path2);
15592
15684
  } finally {
15593
15685
  await unlink6(staged).catch(() => {});
15594
15686
  }
@@ -16049,14 +16141,14 @@ function createNativeCustody(options) {
16049
16141
  let probe;
16050
16142
  const setTimer = options.setTimeout ?? setTimeout;
16051
16143
  const clearTimer = options.clearTimeout ?? clearTimeout;
16052
- const guardedTimer = (callback, delay3, ...args) => setTimer(() => {
16144
+ const guardedTimer = (callback, delay4, ...args) => setTimer(() => {
16053
16145
  try {
16054
16146
  check();
16055
16147
  } catch {
16056
16148
  return;
16057
16149
  }
16058
16150
  callback(...args);
16059
- }, delay3);
16151
+ }, delay4);
16060
16152
  function closeProbe(held) {
16061
16153
  if (held.closed || held.promoted)
16062
16154
  return;
@@ -16631,6 +16723,9 @@ class ClaudeCodeFirstUserTextTracker {
16631
16723
  has(sessionId) {
16632
16724
  return this.#values.has(sessionId);
16633
16725
  }
16726
+ peek(sessionId) {
16727
+ return this.#values.get(sessionId);
16728
+ }
16634
16729
  clear() {
16635
16730
  this.#values.clear();
16636
16731
  }
@@ -17154,7 +17249,7 @@ import {
17154
17249
  mkdir as mkdir8,
17155
17250
  readdir as readdir4,
17156
17251
  readFile as readFile9,
17157
- rename as rename9,
17252
+ rename as rename10,
17158
17253
  unlink as unlink7,
17159
17254
  writeFile as writeFile2
17160
17255
  } from "node:fs/promises";
@@ -17164,7 +17259,7 @@ import { join as join17, resolve as resolve17 } from "node:path";
17164
17259
  // src/gateway.ts
17165
17260
  import { execFile } from "node:child_process";
17166
17261
  import { readFile as readFile8, realpath as realpath5 } from "node:fs/promises";
17167
- import { posix as posix4, resolve as resolve16, win32 as win324 } from "node:path";
17262
+ import { posix as posix4, resolve as resolve16, win32 as win325 } from "node:path";
17168
17263
 
17169
17264
  // src/custom-headers.ts
17170
17265
  var ANTHROPIC_CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
@@ -17495,7 +17590,7 @@ async function posixAccountHome(dependencies) {
17495
17590
  return passwdHome(await dependencies.readFile("/etc/passwd"), uid);
17496
17591
  }
17497
17592
  async function windowsAppData(dependencies) {
17498
- const output = await dependencies.run(win324.join(WINDOWS_ROOT, "System32", "reg.exe"), ["query", WINDOWS_SHELL_FOLDERS, "/v", "AppData"], { SystemRoot: WINDOWS_ROOT });
17593
+ const output = await dependencies.run(win325.join(WINDOWS_ROOT, "System32", "reg.exe"), ["query", WINDOWS_SHELL_FOLDERS, "/v", "AppData"], { SystemRoot: WINDOWS_ROOT });
17499
17594
  const value = /^\s*AppData\s+REG_SZ\s+(.+?)\s*$/im.exec(output)?.[1];
17500
17595
  return value && !value.includes("%") ? value : undefined;
17501
17596
  }
@@ -17503,7 +17598,7 @@ async function lookupGatewaySettingsFile(dependencies) {
17503
17598
  try {
17504
17599
  if (dependencies.platform === "win32") {
17505
17600
  const appData = await windowsAppData(dependencies);
17506
- return appData && win324.isAbsolute(appData) ? win324.join(appData, "cortexkit", "anthropic-auth.jsonc") : undefined;
17601
+ return appData && win325.isAbsolute(appData) ? win325.join(appData, "cortexkit", "anthropic-auth.jsonc") : undefined;
17507
17602
  }
17508
17603
  const home = await posixAccountHome(dependencies);
17509
17604
  return home && posix4.isAbsolute(home) ? posix4.join(home, ".config", "cortexkit", "anthropic-auth.jsonc") : undefined;
@@ -17518,11 +17613,11 @@ function registryPath(output, name) {
17518
17613
  return value && !value.includes("%") ? value : undefined;
17519
17614
  }
17520
17615
  async function windowsAccountSid(dependencies) {
17521
- const output = await dependencies.run(win324.join(WINDOWS_ROOT, "System32", "whoami.exe"), ["/user", "/fo", "csv", "/nh"], { SystemRoot: WINDOWS_ROOT });
17616
+ const output = await dependencies.run(win325.join(WINDOWS_ROOT, "System32", "whoami.exe"), ["/user", "/fo", "csv", "/nh"], { SystemRoot: WINDOWS_ROOT });
17522
17617
  return /"(S-1-\d+(?:-\d+)+)"\s*$/m.exec(output)?.[1];
17523
17618
  }
17524
17619
  async function windowsProfile(dependencies) {
17525
- const reg = win324.join(WINDOWS_ROOT, "System32", "reg.exe");
17620
+ const reg = win325.join(WINDOWS_ROOT, "System32", "reg.exe");
17526
17621
  const env = { SystemRoot: WINDOWS_ROOT };
17527
17622
  const fromProfileList = await windowsAccountSid(dependencies).then(async (sid) => sid ? registryPath(await dependencies.run(reg, [
17528
17623
  "query",
@@ -17540,7 +17635,7 @@ async function lookupAccountHome(dependencies) {
17540
17635
  try {
17541
17636
  if (dependencies.platform === "win32") {
17542
17637
  const profile = await windowsProfile(dependencies);
17543
- return profile && win324.isAbsolute(profile) ? profile : undefined;
17638
+ return profile && win325.isAbsolute(profile) ? profile : undefined;
17544
17639
  }
17545
17640
  const home = await posixAccountHome(dependencies);
17546
17641
  return home && posix4.isAbsolute(home) ? home : undefined;
@@ -17687,7 +17782,7 @@ async function writeDumpFile(path2, contents) {
17687
17782
  try {
17688
17783
  await writeFile2(partialPath, contents, { encoding: "utf8", flag: "wx" });
17689
17784
  created = true;
17690
- await rename9(partialPath, path2);
17785
+ await rename10(partialPath, path2);
17691
17786
  return true;
17692
17787
  } catch (error) {
17693
17788
  if (error.code === "EEXIST")
@@ -21284,8 +21379,8 @@ class CacheKeepManager2 {
21284
21379
  }
21285
21380
  target.consecutiveFailures += 1;
21286
21381
  const backoff = cacheKeepRetryDelayMs(target.id, target.consecutiveFailures);
21287
- const delay3 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
21288
- target.nextPrewarmAt = Math.min(now + delay3, deadline);
21382
+ const delay4 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
21383
+ target.nextPrewarmAt = Math.min(now + delay4, deadline);
21289
21384
  }
21290
21385
  async sendPrewarm(target, onAccepted) {
21291
21386
  const generation = this.schedulerGeneration;
@@ -21705,7 +21800,7 @@ import {
21705
21800
  mkdir as mkdir12,
21706
21801
  readdir as readdir5,
21707
21802
  readFile as readFile15,
21708
- rename as rename13,
21803
+ rename as rename14,
21709
21804
  rm as rm7,
21710
21805
  writeFile as writeFile4
21711
21806
  } from "node:fs/promises";
@@ -21771,7 +21866,7 @@ import { basename as basename11, dirname as dirname17, join as join21 } from "no
21771
21866
 
21772
21867
  // src/sticky-routing.ts
21773
21868
  import { createHash as createHash17, randomUUID as randomUUID15 } from "node:crypto";
21774
- import { mkdir as mkdir10, readFile as readFile11, rename as rename12, rm as rm6, stat as stat12, writeFile as writeFile3 } from "node:fs/promises";
21869
+ import { mkdir as mkdir10, readFile as readFile11, rename as rename13, rm as rm6, stat as stat12, writeFile as writeFile3 } from "node:fs/promises";
21775
21870
  import { basename as basename10, dirname as dirname16, join as join20 } from "node:path";
21776
21871
 
21777
21872
  // src/native-vault-seed.ts
@@ -24556,11 +24651,11 @@ class PoolQuotaWriter {
24556
24651
  overlay(rows) {
24557
24652
  return rows.map((row) => this.overlayRow(row));
24558
24653
  }
24559
- schedule(delay3) {
24654
+ schedule(delay4) {
24560
24655
  if (this.running || this.timer || !this.pending.size || this.stopped)
24561
24656
  return;
24562
24657
  const remaining = this.closed ? 0 : (this.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - this.clock.now();
24563
- this.timer = this.clock.schedule(Math.max(delay3, remaining), () => {
24658
+ this.timer = this.clock.schedule(Math.max(delay4, remaining), () => {
24564
24659
  this.timer = undefined;
24565
24660
  return this.flush();
24566
24661
  });
@@ -24658,8 +24753,8 @@ class PoolQuotaWriter {
24658
24753
  this.running = undefined;
24659
24754
  for (const wake of this.wake)
24660
24755
  wake();
24661
- const delay3 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24662
- this.schedule(delay3);
24756
+ const delay4 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24757
+ this.schedule(delay4);
24663
24758
  }
24664
24759
  })();
24665
24760
  return this.running;
@@ -25655,7 +25750,7 @@ var nativeQuotaCodec = {
25655
25750
  // src/native-runtime.ts
25656
25751
  import { randomUUID as randomUUID14 } from "node:crypto";
25657
25752
  import { constants as constants2 } from "node:fs";
25658
- import { lstat as lstat8, mkdir as mkdir9, open as open9, rename as rename11, rm as rm5 } from "node:fs/promises";
25753
+ import { lstat as lstat8, mkdir as mkdir9, open as open9, rename as rename12, rm as rm5 } from "node:fs/promises";
25659
25754
  import { basename as basename9, dirname as dirname15, isAbsolute as isAbsolute4, join as join19 } from "node:path";
25660
25755
  import { types as utilTypes5 } from "node:util";
25661
25756
 
@@ -25831,7 +25926,7 @@ function openNativePoolStore(options) {
25831
25926
  }
25832
25927
 
25833
25928
  // src/publication-rename.ts
25834
- import { rename as rename10 } from "node:fs/promises";
25929
+ import { rename as rename11 } from "node:fs/promises";
25835
25930
  import { types as utilTypes4 } from "node:util";
25836
25931
  function capturePublicationOptions(options = {}) {
25837
25932
  return {
@@ -25854,7 +25949,7 @@ function sharingViolation(error) {
25854
25949
  return fields2.win32Code !== undefined ? fields2.win32Code === 32 || fields2.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(fields2.code) && !fields2.reason;
25855
25950
  }
25856
25951
  async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry) {
25857
- const move = options.rename ?? rename10;
25952
+ const move = options.rename ?? rename11;
25858
25953
  if ((options.platform ?? process.platform) !== "win32") {
25859
25954
  await move(from, to);
25860
25955
  return "published";
@@ -25871,11 +25966,11 @@ async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry
25871
25966
  throw error;
25872
25967
  original = error;
25873
25968
  }
25874
- for (const delay3 of [10, 20, 40, 80, 100]) {
25969
+ for (const delay4 of [10, 20, 40, 80, 100]) {
25875
25970
  const remaining = 500 - (now() - start);
25876
25971
  if (remaining <= 0)
25877
25972
  break;
25878
- await sleep(Math.min(delay3, remaining));
25973
+ await sleep(Math.min(delay4, remaining));
25879
25974
  if (now() - start >= 500)
25880
25975
  break;
25881
25976
  if (await beforeRetry?.() === "skip")
@@ -28067,7 +28162,7 @@ async function writeNativeRuntimeOutcome(path2, storageId, change, hooks, firstI
28067
28162
  } catch {
28068
28163
  throw new NativeRuntimeError("publication-refused");
28069
28164
  }
28070
- return (publication2.rename ?? rename11)(from, to);
28165
+ return (publication2.rename ?? rename12)(from, to);
28071
28166
  };
28072
28167
  try {
28073
28168
  await mkdir9(dirname15(path2), { recursive: true, mode: 448 });
@@ -29604,16 +29699,13 @@ function decideStickyQuotaFailure(input) {
29604
29699
  const scope = input.unconfirmedRetry;
29605
29700
  return scope && !scope.counter.retain(scope.sessionId, scope.turnId, scope.accountId) ? { action: "migrate", reason: "unconfirmed-retry-limit" } : { action: "retain", reason };
29606
29701
  };
29607
- let reading2 = knownQuota(input.quota);
29608
- const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, now) : undefined;
29609
- if (reading2 && input.responseHeaders) {
29610
- reading2 = { ...reading2 };
29611
- for (const key of ["five_hour", "seven_day", "scoped"]) {
29612
- if (quotaFieldSource(reading2, key) === "headers")
29613
- delete reading2[key];
29614
- }
29615
- }
29616
- const quota2 = reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
29702
+ const quota2 = stickyQuotaEvidence({
29703
+ quota: input.quota,
29704
+ responseHeaders: input.responseHeaders,
29705
+ modelId: input.modelId,
29706
+ now,
29707
+ storedHeaderReadings: true
29708
+ });
29617
29709
  if (!quota2)
29618
29710
  return retain("unknown");
29619
29711
  let blocking;
@@ -29642,6 +29734,60 @@ function decideStickyQuotaFailure(input) {
29642
29734
  }
29643
29735
  return { action: "migrate", reason: blocking.reason };
29644
29736
  }
29737
+ function stickyQuotaEvidence(input) {
29738
+ let reading2 = knownQuota(input.quota);
29739
+ const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, input.now) : undefined;
29740
+ if (reading2 && (input.responseHeaders || !input.storedHeaderReadings)) {
29741
+ reading2 = { ...reading2 };
29742
+ for (const key of ["five_hour", "seven_day", "scoped"]) {
29743
+ if (quotaFieldSource(reading2, key) === "headers")
29744
+ delete reading2[key];
29745
+ }
29746
+ }
29747
+ return reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
29748
+ }
29749
+ function stickyQuotaExhaustionInForce(input) {
29750
+ const now = input.now ?? Date.now();
29751
+ const quota2 = stickyQuotaEvidence({
29752
+ quota: input.quota,
29753
+ responseHeaders: input.responseHeaders,
29754
+ modelId: input.modelId,
29755
+ now,
29756
+ storedHeaderReadings: false
29757
+ });
29758
+ if (!quota2)
29759
+ return;
29760
+ const scoped = getScopedQuotaWindowForModel(quota2, input.modelId);
29761
+ let blocking;
29762
+ for (const [reason, limitName, window2] of [
29763
+ ["model-scoped", `${scoped?.modelName ?? "Model"} weekly`, scoped],
29764
+ ["seven-day", "weekly", quota2.seven_day],
29765
+ ["five-hour", "5-hour", quota2.five_hour]
29766
+ ]) {
29767
+ if (!window2 || !Number.isFinite(window2.remainingPercent) || window2.remainingPercent > 0)
29768
+ continue;
29769
+ const resetAt = window2.resetsAt ? Date.parse(window2.resetsAt) : NaN;
29770
+ if (!Number.isFinite(resetAt) || resetAt <= now)
29771
+ continue;
29772
+ if (!blocking || resetAt > blocking.resetAt)
29773
+ blocking = { resetAt, reason, limitName };
29774
+ }
29775
+ return blocking;
29776
+ }
29777
+ function createExhaustedNoRouteResponse(input) {
29778
+ const now = input.now ?? Date.now();
29779
+ const earliest = [...input.exhausted].sort((a, b) => a.resetAt - b.resetAt)[0];
29780
+ return createQuotaRefusalResponse("Claude reports every account that could take this request as out of quota.", {
29781
+ resetAt: earliest?.resetAt,
29782
+ ...earliest ? { limitName: earliest.limitName } : {},
29783
+ retryAfterSeconds: quotaRefusalRetryAfterSeconds({
29784
+ resetAt: earliest?.resetAt,
29785
+ storage: input.storage,
29786
+ sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId),
29787
+ now
29788
+ })
29789
+ }, now);
29790
+ }
29645
29791
  function stickyRetainRetryHeaders(upstream, now = Date.now()) {
29646
29792
  const headers = new Headers(upstream);
29647
29793
  let seconds = 60;
@@ -29841,7 +29987,7 @@ class StickySessionRouter {
29841
29987
  await writeFile3(tempPath, `${JSON.stringify(state)}
29842
29988
  `, { mode: 384 });
29843
29989
  await beforeRename();
29844
- await rename12(tempPath, this.options.path);
29990
+ await rename13(tempPath, this.options.path);
29845
29991
  } finally {
29846
29992
  await rm6(tempPath, { force: true }).catch(() => {});
29847
29993
  }
@@ -31674,7 +31820,7 @@ class CacheKeepSessionRegistry {
31674
31820
  }
31675
31821
  const sweptPath = `${recordPath}.${randomUUID18()}.sweep`;
31676
31822
  try {
31677
- await rename13(recordPath, sweptPath);
31823
+ await rename14(recordPath, sweptPath);
31678
31824
  } catch {
31679
31825
  return;
31680
31826
  }
@@ -32028,8 +32174,8 @@ class CacheKeepStore {
32028
32174
  this.pending.set(entry2.id, entry2);
32029
32175
  if (this.timers.has(entry2.id))
32030
32176
  return;
32031
- const delay3 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
32032
- const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay3);
32177
+ const delay4 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
32178
+ const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay4);
32033
32179
  timer.unref?.();
32034
32180
  this.timers.set(entry2.id, timer);
32035
32181
  }
@@ -36379,7 +36525,7 @@ async function beginNativeEmptyInit(paths, hooks = {}) {
36379
36525
  host: "opencode",
36380
36526
  phase: "committed"
36381
36527
  };
36382
- await hooks.assertOwned?.();
36528
+ await (hooks.validate ?? hooks.assertOwned)?.();
36383
36529
  await writeJournal(paths, initial, () => lock.assertOwned(), hooks);
36384
36530
  return initial;
36385
36531
  });
@@ -38857,6 +39003,70 @@ function isSettingsImportPending(service) {
38857
39003
  return service ? pendingImports.has(service) : false;
38858
39004
  }
38859
39005
 
39006
+ // src/settings-mode-status.ts
39007
+ function settingsMoveBlockerIdentity(blocker) {
39008
+ switch (blocker.kind) {
39009
+ case "registration":
39010
+ return { kind: blocker.kind };
39011
+ case "floor":
39012
+ return { kind: blocker.kind, release: blocker.release };
39013
+ case "settings-holder":
39014
+ return {
39015
+ kind: blocker.kind,
39016
+ path: blocker.holderFile,
39017
+ pid: blocker.pid,
39018
+ release: blocker.release
39019
+ };
39020
+ case "holder-file":
39021
+ return { kind: blocker.kind, path: blocker.holderFile };
39022
+ case "pre-n-artifact":
39023
+ return { kind: blocker.kind, path: blocker.artifact, pid: blocker.pid };
39024
+ case "artifact-scan":
39025
+ return { kind: blocker.kind, path: blocker.path };
39026
+ }
39027
+ }
39028
+ var blockerWords = {
39029
+ registration: "this process to register as a settings holder",
39030
+ floor: "a valid minimum plugin release",
39031
+ "holder-file": "a settings holder registry that could not be read",
39032
+ "settings-holder": "an older or unrecognized settings holder",
39033
+ "pre-n-artifact": "an older plugin process that may still be running",
39034
+ "artifact-scan": "an old plugin file that could not be read (the log names it)"
39035
+ };
39036
+ var outcomeWords = {
39037
+ "fence-closed": "a safe settings-holder check",
39038
+ "separate-install": "this separate install, which keeps its own settings",
39039
+ "source-unavailable": "the old settings stores to become readable and ready",
39040
+ "import-refused": "this host's protection settings to be safely imported",
39041
+ "import-unknown": "this host's old protection settings to become readable",
39042
+ "import-pending": "the shared file to become usable so this host's protection settings can be checked",
39043
+ "authority-refused": "account enrollment or credential migration to allow settings access",
39044
+ "startup-failed": "settings startup to succeed",
39045
+ busy: "another settings operation to finish; restart to try the move again",
39046
+ failed: "the settings move to succeed; restart to try again",
39047
+ "aborted-target-appeared": "a settings file published by another process to be checked",
39048
+ "done-already": "the existing settings file to be checked",
39049
+ "marker-present": "the previously moved settings file to be checked",
39050
+ moved: "the moved settings file to be opened"
39051
+ };
39052
+ var sourceWords = {
39053
+ "custody-unreadable": "account enrollment to become readable",
39054
+ "seeding-failed": "the vault settings to be initialized",
39055
+ "paths-unreadable": "the old settings store paths to become readable",
39056
+ "vault-unseeded": "the vault settings to be ready"
39057
+ };
39058
+ function formatSettingsModeStatus(options) {
39059
+ const target = options.file ? `\`${options.file}\`` : "the shared settings file";
39060
+ if (options.mode === "user-file")
39061
+ return `Settings: shared file ${target}`;
39062
+ if (options.mode === "separate")
39063
+ return "Settings: using the old settings; this separate install keeps its own settings and does not move them to the shared file";
39064
+ const diagnostic = options.diagnostic;
39065
+ const kinds = [...new Set(diagnostic?.blockers?.map(({ kind }) => kind))];
39066
+ const reason = kinds.length ? kinds.map((kind) => blockerWords[kind]).join("; ") : diagnostic?.outcome === "source-unavailable" && diagnostic.sourceReason ? sourceWords[diagnostic.sourceReason] : diagnostic ? outcomeWords[diagnostic.outcome] : "the settings move to complete at a later start";
39067
+ return `Settings: using the old settings; the move to ${target} waits for: ${reason}`;
39068
+ }
39069
+
38860
39070
  // src/settings-record.ts
38861
39071
  function settingsFileSets(generation, key, host2, model2) {
38862
39072
  const levels = generation.fileLevels[key];
@@ -38993,6 +39203,7 @@ function resolveSettingsRecord(stored, generation, host2, model2) {
38993
39203
  // src/native-runtime-settings.ts
38994
39204
  function createNativeRuntimeSettings(options) {
38995
39205
  const env = options.env ?? process.env;
39206
+ let diagnostic = options.settingsDiagnostic;
38996
39207
  let adoption = getSettingsAdoptionCheck(options.settingsService);
38997
39208
  const startedPending = isSettingsImportPending(options.settingsService);
38998
39209
  let service = options.settingsService?.retain();
@@ -39200,6 +39411,16 @@ function createNativeRuntimeSettings(options) {
39200
39411
  return {
39201
39412
  resolve: resolve22,
39202
39413
  status,
39414
+ modeStatus(file) {
39415
+ return formatSettingsModeStatus({
39416
+ mode: mode() === "separate" ? "separate" : userAuthority || mode() === "user-file" ? "user-file" : "legacy",
39417
+ file: service?.file ?? fallback?.file ?? file,
39418
+ diagnostic
39419
+ });
39420
+ },
39421
+ setDiagnostic(next) {
39422
+ diagnostic = next;
39423
+ },
39203
39424
  gateway,
39204
39425
  applyEffects,
39205
39426
  file: () => generation()?.file,
@@ -41947,6 +42168,8 @@ function acquireNativeAccountRuntime(options) {
41947
42168
  const { use, close } = sharedAccounts.acquire(key, () => createNativeAccountRuntime(options));
41948
42169
  const vault = leaseNativeVaultRuntime(() => use().vault, close);
41949
42170
  const quotaObservations = use().quotaObservations;
42171
+ if (options.settingsDiagnostic)
42172
+ use().setSettingsDiagnostic?.(options.settingsDiagnostic);
41950
42173
  const onLockEvent = use().onLockEvent;
41951
42174
  const relocationGuard = use().relocationGuard;
41952
42175
  const drainRoutingPublications = use().drainRoutingPublications;
@@ -41966,6 +42189,7 @@ function acquireNativeAccountRuntime(options) {
41966
42189
  read: (model2) => use().read(model2),
41967
42190
  resolveSettings: (stored, model2) => use().resolveSettings?.(stored, model2) ?? stored,
41968
42191
  getSettingsStatus: () => use().getSettingsStatus?.(),
42192
+ getSettingsModeStatus: () => use().getSettingsModeStatus?.() ?? "",
41969
42193
  getClaudeGateway: () => use().getClaudeGateway?.(),
41970
42194
  applySettingsEffects: () => use().applySettingsEffects?.(),
41971
42195
  prepareSettingsAction: () => use().prepareSettingsAction?.() ?? Promise.resolve(),
@@ -42495,6 +42719,8 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
42495
42719
  return runtimeSettings.file() ?? (await selectedStorage()).paths.config;
42496
42720
  },
42497
42721
  getSettingsStatus: runtimeSettings.status,
42722
+ getSettingsModeStatus: () => runtimeSettings.modeStatus(options.settingsFile ?? getSettingsFilePath({ env })),
42723
+ setSettingsDiagnostic: runtimeSettings.setDiagnostic,
42498
42724
  getClaudeGateway: runtimeSettings.gateway,
42499
42725
  resolveSettings: runtimeSettings.resolve,
42500
42726
  applySettingsEffects: runtimeSettings.applyEffects,
@@ -43274,7 +43500,7 @@ function relayGeneration(input) {
43274
43500
  }
43275
43501
  // src/native-host-auth-write.ts
43276
43502
  import { randomUUID as randomUUID24 } from "node:crypto";
43277
- import { lstat as lstat19, open as open13, rename as rename14, unlink as unlink9 } from "node:fs/promises";
43503
+ import { lstat as lstat19, open as open13, rename as rename15, unlink as unlink9 } from "node:fs/promises";
43278
43504
  import { dirname as dirname22, isAbsolute as isAbsolute6, join as join28 } from "node:path";
43279
43505
  class NativeHostAuthWriteError extends Error {
43280
43506
  code;
@@ -43371,7 +43597,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
43371
43597
  return "publish";
43372
43598
  });
43373
43599
  } else
43374
- await (publication2.rename ?? rename14)(stage, authPath);
43600
+ await (publication2.rename ?? rename15)(stage, authPath);
43375
43601
  ownedStage = undefined;
43376
43602
  effect = outcome;
43377
43603
  await barrier(afterRename, "hook-failed", effect);
@@ -43467,7 +43693,8 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43467
43693
  const env = { ...input.env };
43468
43694
  const routingDestinationPath = input.routingDestinationPath;
43469
43695
  const processFence = input.processFence;
43470
- await processFence();
43696
+ const validate = input.validate ?? processFence;
43697
+ await validate();
43471
43698
  requireNoSupervisedAuthContentSnapshot(env);
43472
43699
  return withLock(paths2.journal, {
43473
43700
  name: "native-migration",
@@ -43476,9 +43703,9 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43476
43703
  ...hooks.lockOptions,
43477
43704
  renew: true
43478
43705
  }, async (lease) => {
43479
- await processFence();
43480
- const checkDestinations = async () => {
43481
- await processFence();
43706
+ await validate();
43707
+ const checkDestinations = async (publication2 = true) => {
43708
+ await (publication2 ? processFence : validate)();
43482
43709
  try {
43483
43710
  await lease.assertOwned();
43484
43711
  } catch {
@@ -43519,6 +43746,7 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43519
43746
  return beginNativeEmptyInit(paths2, {
43520
43747
  lockOptions: hooks.lockOptions,
43521
43748
  assertOwned: checkDestinations,
43749
+ validate: () => checkDestinations(false),
43522
43750
  onWriteStep: async (step) => hooks.onStep?.(`${step}:journal:committed`)
43523
43751
  });
43524
43752
  });
@@ -43537,7 +43765,7 @@ function releaseNativeMigrationPreflight(token2) {
43537
43765
  }
43538
43766
  async function capture2(input, checkPool = false) {
43539
43767
  requireNoSupervisedAuthContentSnapshot(input.env);
43540
- await input.processFence();
43768
+ await (input.validate ?? input.processFence)();
43541
43769
  const resolved = await resolveNativePoolPaths(input.paths.legacyConfig, input.paths.legacyState, processStateLayout(input.paths.legacyConfig));
43542
43770
  for (const key of Object.keys(resolved))
43543
43771
  if (input.paths[key] !== resolved[key])
@@ -43991,13 +44219,13 @@ async function runNativeMigration(input, hooks = {}) {
43991
44219
  const projection = captured.projection;
43992
44220
  if (!projection)
43993
44221
  refuse3();
43994
- const beforeMutator = async () => {
44222
+ const beforeMutator = async (publication2 = true) => {
43995
44223
  await checkPaths(operation, captured);
43996
44224
  await checkLegacy(captured);
43997
- await operation.processFence();
44225
+ await (publication2 ? operation.processFence : operation.validate ?? operation.processFence)();
43998
44226
  await assertMigration();
43999
44227
  };
44000
- await beforeMutator();
44228
+ await beforeMutator(false);
44001
44229
  await store.initialize();
44002
44230
  for (const account of [...projection.accounts].filter((account2) => account2.credential).sort((a, b) => Number(a.enabled) - Number(b.enabled))) {
44003
44231
  const current = (await publicRows(store)).find((row) => row.id === account.id);
@@ -44013,7 +44241,7 @@ async function runNativeMigration(input, hooks = {}) {
44013
44241
  ]
44014
44242
  }, [current], false);
44015
44243
  else {
44016
- await beforeMutator();
44244
+ await beforeMutator(false);
44017
44245
  if (!account.credential)
44018
44246
  refuse3();
44019
44247
  const result = await store.add({
@@ -44026,7 +44254,7 @@ async function runNativeMigration(input, hooks = {}) {
44026
44254
  refuse3();
44027
44255
  await step(`after:add:${account.id}`);
44028
44256
  }
44029
- await beforeMutator();
44257
+ await beforeMutator(false);
44030
44258
  if (!account.enabled)
44031
44259
  await store.disable(account.id, "user-disabled");
44032
44260
  else
@@ -44035,21 +44263,21 @@ async function runNativeMigration(input, hooks = {}) {
44035
44263
  const row = (await publicRows(store)).find((row2) => row2.id === account.id);
44036
44264
  if (!row?.credentialEpoch)
44037
44265
  refuse3();
44038
- await beforeMutator();
44266
+ await beforeMutator(false);
44039
44267
  await store.recordQuota(account.id, {
44040
44268
  credentialEpoch: row.credentialEpoch,
44041
44269
  ...row.identity !== undefined ? { identity: row.identity } : {}
44042
44270
  }, account.quota);
44043
44271
  }
44044
44272
  }
44045
- await beforeMutator();
44273
+ await beforeMutator(false);
44046
44274
  await store.reorder(projection.accounts.filter((account) => account.credential).map((account) => account.id));
44047
44275
  if (journal.kind !== "legacy-import") {
44048
- await beforeMutator();
44276
+ await beforeMutator(false);
44049
44277
  await store.updateSettings(() => projection.settings);
44050
44278
  }
44051
44279
  if (captured.seedInput) {
44052
- await beforeMutator();
44280
+ await beforeMutator(false);
44053
44281
  await step("before:roster");
44054
44282
  if (!operation.custody)
44055
44283
  refuse3();
@@ -44062,7 +44290,7 @@ async function runNativeMigration(input, hooks = {}) {
44062
44290
  const rows = await publicRows(store);
44063
44291
  requireNativeMigrationSourceRows(projection, rows);
44064
44292
  const projected = projectNativeMigrationRuntime(paths2, projection, rows, seed);
44065
- await beforeMutator();
44293
+ await beforeMutator(false);
44066
44294
  await step("before:runtime");
44067
44295
  if (captured.seedInput) {
44068
44296
  if (!operation.custody)
@@ -44144,13 +44372,13 @@ async function runNativeMigration(input, hooks = {}) {
44144
44372
  }
44145
44373
  requireNativeMigrationPreparedProof(journal.preparedProof, rows, runtime2);
44146
44374
  const authoritative = journal;
44147
- const recheck = async () => {
44375
+ const recheck = async (publication2 = true) => {
44148
44376
  await checkPaths(operation, captured);
44149
44377
  await checkLegacy(captured);
44150
44378
  rows = await publicRows(store);
44151
44379
  runtime2 = await importedRuntimeProjection(paths2, store, rows);
44152
44380
  requireNativeMigrationPreparedProof(authoritative.preparedProof, rows, runtime2);
44153
- await operation.processFence();
44381
+ await (publication2 ? operation.processFence : operation.validate ?? operation.processFence)();
44154
44382
  await assertOwned();
44155
44383
  };
44156
44384
  await withLock(operation.routingDestinationPath, { name: "write", ttlMs: 30000, timeoutMs: 15000, renew: true }, async (routingLease) => {
@@ -44181,7 +44409,7 @@ async function runNativeMigration(input, hooks = {}) {
44181
44409
  if (authoritative.phase === "activation-installed" && entry2.digest !== authoritative.expectedHostAuth)
44182
44410
  refuse3();
44183
44411
  await step("before:host");
44184
- await recheck();
44412
+ await recheck(false);
44185
44413
  await mkdir15(dirname23(operation.hostAuthPath), {
44186
44414
  recursive: true,
44187
44415
  mode: 448
@@ -44200,7 +44428,7 @@ async function runNativeMigration(input, hooks = {}) {
44200
44428
  }
44201
44429
  }, hooks.hostWrite);
44202
44430
  await step("after:host");
44203
- await recheck();
44431
+ await recheck(false);
44204
44432
  const effect = await readNativeMigrationSource("hostAuth", operation.hostAuthPath);
44205
44433
  if (inspectNativeHostAuthEntry(operation.host, effect.data).digest !== authoritative.expectedHostAuth)
44206
44434
  refuse3();
@@ -47070,7 +47298,7 @@ import { dirname as dirname24, resolve as resolve23 } from "node:path";
47070
47298
  import { setTimeout as sleep } from "node:timers/promises";
47071
47299
 
47072
47300
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
47073
- import { rmdirSync, statSync as statSync6, utimesSync } from "node:fs";
47301
+ import { rmdirSync, statSync as statSync7, utimesSync } from "node:fs";
47074
47302
  import { mkdir as mkdir16, rmdir, stat as stat13, utimes } from "node:fs/promises";
47075
47303
  var STALE = 30000;
47076
47304
  var RENEWAL_STALE = 1e4;
@@ -47082,7 +47310,7 @@ process.once("exit", () => {
47082
47310
  try {
47083
47311
  if (identity5.renewedAt + RENEWAL_STALE < Date.now())
47084
47312
  continue;
47085
- const observed = statSync6(path2);
47313
+ const observed = statSync7(path2);
47086
47314
  if (sameDirectory(observed, identity5) && observed.mtime.getTime() === identity5.mtime)
47087
47315
  rmdirSync(path2);
47088
47316
  } catch {}
@@ -47174,12 +47402,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
47174
47402
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
47175
47403
  compromise();
47176
47404
  }
47177
- function schedule2(delay3 = UPDATE) {
47405
+ function schedule2(delay4 = UPDATE) {
47178
47406
  if (released)
47179
47407
  return;
47180
47408
  timer = setTimeout(() => {
47181
47409
  update();
47182
- }, delay3);
47410
+ }, delay4);
47183
47411
  timer.unref();
47184
47412
  }
47185
47413
  function retry(error) {
@@ -47196,7 +47424,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
47196
47424
  return;
47197
47425
  let observed;
47198
47426
  try {
47199
- observed = statSync6(path2);
47427
+ observed = statSync7(path2);
47200
47428
  } catch (error) {
47201
47429
  retry(error);
47202
47430
  return;
@@ -48498,7 +48726,7 @@ import {
48498
48726
  mkdir as mkdir19,
48499
48727
  readdir as readdir8,
48500
48728
  readFile as readFile18,
48501
- rename as rename15,
48729
+ rename as rename16,
48502
48730
  rm as rm11,
48503
48731
  stat as stat15,
48504
48732
  writeFile as writeFile7
@@ -48711,7 +48939,7 @@ class QuotaHeaderFeedRegistry {
48711
48939
  await writeFile7(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
48712
48940
  `, { mode: 384 });
48713
48941
  await chmod3(tempPath, 384);
48714
- await rename15(tempPath, this.filePath);
48942
+ await rename16(tempPath, this.filePath);
48715
48943
  } finally {
48716
48944
  await rm11(tempPath, { force: true });
48717
48945
  }
@@ -48937,7 +49165,7 @@ function buildClaudeQuotaSummary(input) {
48937
49165
  `).trimEnd();
48938
49166
  }
48939
49167
  // src/request-gzip.ts
48940
- import { mkdir as mkdir20, readFile as readFile19, rename as rename16, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
49168
+ import { mkdir as mkdir20, readFile as readFile19, rename as rename17, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
48941
49169
  import { basename as basename14, dirname as dirname26, join as join32 } from "node:path";
48942
49170
  import { promisify as promisify2 } from "node:util";
48943
49171
  import { gzip as gzip2 } from "node:zlib";
@@ -49065,7 +49293,7 @@ class RequestGzipLatch {
49065
49293
  await mkdir20(dirname26(this.path), { recursive: true });
49066
49294
  await writeFile8(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
49067
49295
  `, { mode: 384 });
49068
- await rename16(temporary, this.path);
49296
+ await rename17(temporary, this.path);
49069
49297
  } catch {
49070
49298
  await rm12(temporary, { force: true }).catch(() => {});
49071
49299
  }
@@ -49647,34 +49875,55 @@ function stamped(value) {
49647
49875
  const writer = value.writer;
49648
49876
  return typeof writer === "object" && writer !== null && writer.protocol === 1;
49649
49877
  }
49650
- async function readArtifact(path2, blockers) {
49878
+ function publisherPid(kind, name) {
49879
+ const match = kind === "rpc" ? /^port-(\d+)\.json$/.exec(name) : /^(\d+)-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/.exec(name);
49880
+ const pid = Number(match?.[1]);
49881
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
49882
+ }
49883
+ async function readArtifact(path2, blockers, malformedIsStale) {
49651
49884
  let text6;
49652
49885
  let mtimeMs;
49886
+ let regular;
49653
49887
  try {
49654
49888
  const file = await open15(path2, "r");
49655
49889
  try {
49656
49890
  text6 = await file.readFile("utf8");
49657
- mtimeMs = (await file.stat()).mtimeMs;
49891
+ const stat16 = await file.stat();
49892
+ mtimeMs = stat16.mtimeMs;
49893
+ regular = stat16.isFile();
49658
49894
  } finally {
49659
49895
  await file.close();
49660
49896
  }
49661
49897
  } catch (error) {
49662
49898
  if (errorCode5(error) === "ENOENT")
49663
49899
  return;
49664
- blockers.push({ kind: "artifact-scan", path: path2, reason: reasonOf(error) });
49900
+ if (!malformedIsStale())
49901
+ blockers.push({ kind: "artifact-scan", path: path2, reason: reasonOf(error) });
49665
49902
  return;
49666
49903
  }
49667
49904
  try {
49668
49905
  const value = JSON.parse(text6);
49669
49906
  const startedAt = typeof value === "object" && value !== null ? "startedAt" in value ? value.startedAt : ("registeredAt" in value) ? value.registeredAt : mtimeMs : mtimeMs;
49670
- return { value, startedAt };
49907
+ return { value, startedAt, regular };
49671
49908
  } catch {
49672
- blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49909
+ if (!malformedIsStale(regular ? mtimeMs : undefined))
49910
+ blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49673
49911
  return;
49674
49912
  }
49675
49913
  }
49676
49914
  async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidAlive, clock = {}, acceptsRelease) {
49677
49915
  const exempt = (value) => stamped(value) && (!acceptsRelease || acceptsRelease(value.writer.release));
49916
+ const malformedIsStale = (pid, startedAt) => {
49917
+ if (pid === undefined)
49918
+ return false;
49919
+ if (recordPredatesBoot(startedAt, clock))
49920
+ return true;
49921
+ try {
49922
+ return !pidAlive2(pid);
49923
+ } catch {
49924
+ return false;
49925
+ }
49926
+ };
49678
49927
  const blockers = [];
49679
49928
  const portDirs = [...locations.rpcDirs];
49680
49929
  for (const root of locations.rpcRoots)
@@ -49685,13 +49934,16 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
49685
49934
  if (!/^port-\d+\.json$/.test(name))
49686
49935
  continue;
49687
49936
  const path2 = join33(dir, name);
49688
- const record17 = await readArtifact(path2, blockers);
49937
+ const filenamePid = publisherPid("rpc", name);
49938
+ const isStale = (startedAt2) => malformedIsStale(filenamePid, startedAt2);
49939
+ const record17 = await readArtifact(path2, blockers, isStale);
49689
49940
  if (record17 === undefined || exempt(record17.value))
49690
49941
  continue;
49691
49942
  const { value, startedAt } = record17;
49692
- const pid = value.pid;
49943
+ const pid = value?.pid;
49693
49944
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
49694
- blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49945
+ if (!isStale(record17.regular ? startedAt : undefined))
49946
+ blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
49695
49947
  continue;
49696
49948
  }
49697
49949
  if (!recordPredatesBoot(startedAt, clock) && pidAlive2(pid))
@@ -49704,7 +49956,8 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
49704
49956
  if (!match)
49705
49957
  continue;
49706
49958
  const path2 = join33(dir, name);
49707
- const record17 = await readArtifact(path2, blockers);
49959
+ const filenamePid = publisherPid("cachekeep", name);
49960
+ const record17 = await readArtifact(path2, blockers, (startedAt) => malformedIsStale(filenamePid, startedAt));
49708
49961
  if (record17 === undefined || exempt(record17.value))
49709
49962
  continue;
49710
49963
  const pid = Number(match[1]);
@@ -50170,6 +50423,7 @@ async function prepareSettingsMoveSources(options) {
50170
50423
  }
50171
50424
 
50172
50425
  // src/settings-move-run.ts
50426
+ var loggedClosedFence = false;
50173
50427
  async function importSettingsHostStore(options, service, warn, retry) {
50174
50428
  const { host: host2, paths: paths2 } = options;
50175
50429
  const authority = { ...options, ...options.authority };
@@ -50222,6 +50476,17 @@ async function importSettingsHostStore(options, service, warn, retry) {
50222
50476
  async function runSettingsMoveAtStartup(options) {
50223
50477
  const paths2 = options.paths ?? await resolveSettingsPaths(options.host, options);
50224
50478
  const authority = { ...options, ...options.authority };
50479
+ let blockers = [];
50480
+ const noteClosedFence = () => {
50481
+ if (loggedClosedFence)
50482
+ return;
50483
+ loggedClosedFence = true;
50484
+ const message = `Settings move waits for a closed fence; keeping legacy settings. Blockers: ${JSON.stringify(blockers)}`;
50485
+ if (options.log?.info)
50486
+ options.log.info(message);
50487
+ else
50488
+ logger2.info("settings", message);
50489
+ };
50225
50490
  const logged3 = new Set;
50226
50491
  const warn = (message) => {
50227
50492
  const key = `${paths2.target}\x00${message}`;
@@ -50238,6 +50503,7 @@ async function runSettingsMoveAtStartup(options) {
50238
50503
  mode: mode2,
50239
50504
  mayOpenService: mode2 !== "separate" && outcome2 !== "import-refused",
50240
50505
  outcome: outcome2,
50506
+ ...blockers.length ? { blockers } : {},
50241
50507
  ...move2 ? { move: move2 } : {}
50242
50508
  });
50243
50509
  const startOnFile = async (outcome2, move2) => {
@@ -50305,16 +50571,30 @@ async function runSettingsMoveAtStartup(options) {
50305
50571
  const stores = [paths2.own.account];
50306
50572
  if (paths2.sourceRule === "default")
50307
50573
  stores.push(paths2.defaults.opencode.account, paths2.defaults.pi.account);
50308
- const fence = async () => (await checkSettingsMoveFence({ ...options, ...options.fence, stores })).open;
50574
+ const fence = async () => {
50575
+ const checked = await checkSettingsMoveFence({
50576
+ ...options,
50577
+ ...options.fence,
50578
+ stores
50579
+ });
50580
+ blockers = checked.blockers.map(settingsMoveBlockerIdentity);
50581
+ if (!checked.open)
50582
+ noteClosedFence();
50583
+ return checked.open;
50584
+ };
50309
50585
  if (!await fence())
50310
50586
  return result("legacy", "fence-closed");
50311
50587
  const prepared = await (options.dependencies?.prepareSources ?? prepareSettingsMoveSources)({ ...options, paths: paths2 });
50312
50588
  if (prepared.status !== "ready") {
50313
50589
  if (prepared.status === "unavailable")
50314
50590
  warn(`Settings move unavailable for ${prepared.host}: ${prepared.reason}; keeping legacy settings until the next start.`);
50315
- return result("legacy", "source-unavailable");
50591
+ return {
50592
+ ...result("legacy", "source-unavailable"),
50593
+ ...prepared.status === "unavailable" ? { sourceReason: prepared.reason } : {}
50594
+ };
50316
50595
  }
50317
50596
  let holderFiles;
50597
+ let holderFile;
50318
50598
  try {
50319
50599
  holderFiles = await settingsMoveHolderFiles({
50320
50600
  ...options,
@@ -50323,6 +50603,7 @@ async function runSettingsMoveAtStartup(options) {
50323
50603
  });
50324
50604
  const context = resolvePathOptions(options);
50325
50605
  for (const file of holderFiles) {
50606
+ holderFile = file;
50326
50607
  const folder = context.paths.dirname(file);
50327
50608
  if (options.authority?.fs?.mkdir)
50328
50609
  await options.authority.fs.mkdir(folder);
@@ -50333,6 +50614,10 @@ async function runSettingsMoveAtStartup(options) {
50333
50614
  });
50334
50615
  }
50335
50616
  } catch {
50617
+ blockers = [
50618
+ { kind: "holder-file", ...holderFile ? { path: holderFile } : {} }
50619
+ ];
50620
+ noteClosedFence();
50336
50621
  return result("legacy", "fence-closed");
50337
50622
  }
50338
50623
  const [first, ...rest] = prepared.sources;
@@ -50404,6 +50689,9 @@ async function startSettings(options) {
50404
50689
  };
50405
50690
  const move = options.start?.move ?? runSettingsMoveAtStartup;
50406
50691
  const open16 = options.start?.open ?? openSettingsService;
50692
+ const diagnostic = {
50693
+ outcome: refused2 ? "authority-refused" : "startup-failed"
50694
+ };
50407
50695
  let adopted = false;
50408
50696
  const serviceOptions = (file2) => ({
50409
50697
  file: file2,
@@ -50429,6 +50717,10 @@ async function startSettings(options) {
50429
50717
  };
50430
50718
  const adopt = async (service) => {
50431
50719
  const outcome2 = await importSettingsHostStore({ ...options, paths: await resolvePaths() }, service, warnOnce, "at its next settings check");
50720
+ if (outcome2 !== "adopt" && outcome2 !== "pending") {
50721
+ diagnostic.outcome = outcome2 === "refused" ? "import-refused" : outcome2 === "unknown" ? "import-unknown" : "import-pending";
50722
+ delete diagnostic.blockers;
50723
+ }
50432
50724
  if (outcome2 === "pending")
50433
50725
  return "pending";
50434
50726
  if (outcome2 !== "adopt")
@@ -50449,16 +50741,19 @@ async function startSettings(options) {
50449
50741
  const started = await move(options);
50450
50742
  file = started.paths.target;
50451
50743
  paths2 = started.paths;
50744
+ diagnostic.outcome = started.outcome;
50745
+ diagnostic.blockers = started.blockers;
50746
+ diagnostic.sourceReason = started.sourceReason;
50452
50747
  moved = started.mode === "user-file";
50453
50748
  adopted = moved && !started.importPending;
50454
50749
  if (!started.mayOpenService)
50455
- return { mode: started.mode, file };
50750
+ return { mode: started.mode, file, diagnostic };
50456
50751
  const service = track(await open16(serviceOptions(file)));
50457
50752
  if (!service)
50458
- return { mode: started.mode, file };
50753
+ return { mode: started.mode, file, diagnostic };
50459
50754
  if (started.importPending)
50460
50755
  markSettingsImportPending(service);
50461
- return { mode: started.mode, file, service };
50756
+ return { mode: started.mode, file, service, diagnostic };
50462
50757
  } catch {
50463
50758
  if (!warned3) {
50464
50759
  warned3 = true;
@@ -50510,7 +50805,7 @@ async function startSettings(options) {
50510
50805
  };
50511
50806
  if (refused2) {
50512
50807
  if (options.paths?.separate)
50513
- return { mode: "separate", file: options.paths.target };
50808
+ return { mode: "separate", file: options.paths.target, diagnostic };
50514
50809
  try {
50515
50810
  file = options.paths?.target ?? getSettingsFilePath(options);
50516
50811
  } catch {}
@@ -50530,7 +50825,7 @@ async function startSettings(options) {
50530
50825
  return;
50531
50826
  return openService();
50532
50827
  }, { retryDelaysMs: PREFLIGHT_RETRY_DELAYS_MS, separate: () => separate });
50533
- return { mode: "legacy", file, reopen: reopenAfterPreflight };
50828
+ return { mode: "legacy", file, reopen: reopenAfterPreflight, diagnostic };
50534
50829
  }
50535
50830
  let mode = "user-file";
50536
50831
  let unknown = false;
@@ -50548,13 +50843,14 @@ async function startSettings(options) {
50548
50843
  }
50549
50844
  }
50550
50845
  if (mode === "legacy")
50551
- return { mode, file, reopen: reopenLegacy };
50846
+ return { mode, file, reopen: reopenLegacy, diagnostic };
50552
50847
  if (mode !== "user-file")
50553
- return { mode, file };
50848
+ return { mode, file, diagnostic };
50554
50849
  const recovered = await recoverSettingsProtection(file, options.host, options.protection, file ? options.host : undefined);
50555
50850
  return {
50556
50851
  mode,
50557
50852
  file,
50853
+ diagnostic,
50558
50854
  fallback: {
50559
50855
  get file() {
50560
50856
  return file;
@@ -52738,6 +53034,7 @@ export {
52738
53034
  stickyRetryAfterWithJitter,
52739
53035
  stickyRetainRetryHeaders,
52740
53036
  stickyQuotaSnapshotIsFresh,
53037
+ stickyQuotaExhaustionInForce,
52741
53038
  stateSubfolderName,
52742
53039
  stateRefusalPublicMessage,
52743
53040
  stateRefusalCause,
@@ -52760,6 +53057,7 @@ export {
52760
53057
  settingsRecreationForWriter,
52761
53058
  settingsRecreationFloors,
52762
53059
  settingsMoveHolderFiles,
53060
+ settingsMoveBlockerIdentity,
52763
53061
  settingsImportRecordPath,
52764
53062
  settingsFileUnusableText,
52765
53063
  settingsFileSets,
@@ -52868,6 +53166,7 @@ export {
52868
53166
  quotaSnapshotHasStandardWindows,
52869
53167
  quotaSnapshotCheckedAt,
52870
53168
  quotaRefusalTiming,
53169
+ quotaRefusalRetryAfterSeconds,
52871
53170
  quotaRefusalDetails,
52872
53171
  quotaFieldSource,
52873
53172
  quotaExhaustionFromHeaders,
@@ -53091,6 +53390,7 @@ export {
53091
53390
  generateRelayToken,
53092
53391
  generatePKCE,
53093
53392
  gatewaySettingsFile,
53393
+ formatSettingsModeStatus,
53094
53394
  formatRefreshBackoffMessage,
53095
53395
  formatQuotaMoney,
53096
53396
  formatQuotaBackoffMessage,
@@ -53175,6 +53475,7 @@ export {
53175
53475
  createNativeLocalCredentialService,
53176
53476
  createNativeCustody,
53177
53477
  createNativeAccountRuntime,
53478
+ createExhaustedNoRouteResponse,
53178
53479
  createEmptyStorage,
53179
53480
  createDumpResponseObserver,
53180
53481
  createClaudeModelFetch,