@cortexkit/anthropic-auth-core 2.13.1 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7370,6 +7370,7 @@ function routingHandle(sessionId) {
7370
7370
  var CACHE_WARM_STOP_REASONS = [
7371
7371
  "cost-cap",
7372
7372
  "count-cap",
7373
+ "deadline-missed",
7373
7374
  "outside-hours",
7374
7375
  "session-ended",
7375
7376
  "unsupported"
@@ -8542,7 +8543,20 @@ import { setTimeout as delay } from "node:timers/promises";
8542
8543
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
8543
8544
 
8544
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";
8545
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
+ }
8546
8560
  var HOSTS = new Set(["opencode", "litecode", "opencode2", "pi"]);
8547
8561
  var RUNTIMES = new Set(["node", "bun"]);
8548
8562
  var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
@@ -8615,6 +8629,7 @@ function hostName(command) {
8615
8629
  class ProcessInspectionError extends Error {
8616
8630
  code = "process-inspection-failed";
8617
8631
  step;
8632
+ program;
8618
8633
  exitCode;
8619
8634
  signal;
8620
8635
  timedOut;
@@ -8623,6 +8638,7 @@ class ProcessInspectionError extends Error {
8623
8638
  super("Process inspection failed; setup cannot prove hosts are stopped.");
8624
8639
  this.name = "ProcessInspectionError";
8625
8640
  this.step = details.step;
8641
+ this.program = details.program;
8626
8642
  this.exitCode = details.exitCode;
8627
8643
  this.signal = details.signal;
8628
8644
  this.timedOut = details.timedOut;
@@ -8652,6 +8668,8 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
8652
8668
  }
8653
8669
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8654
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") : "";
8655
8673
  const selfPid = options.selfPid ?? process.pid;
8656
8674
  let inspection = {
8657
8675
  step: windows ? "tasklist" : "ps",
@@ -8660,10 +8678,11 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8660
8678
  timedOut: false,
8661
8679
  durationMs: 0
8662
8680
  };
8663
- const inspect = async (step, file, args, timeoutMs) => {
8681
+ const inspect = async (step, file, args, timeoutMs, program) => {
8664
8682
  const started = performance.now();
8665
8683
  inspection = {
8666
8684
  step,
8685
+ ...program && { program },
8667
8686
  exitCode: null,
8668
8687
  signal: null,
8669
8688
  timedOut: false,
@@ -8676,6 +8695,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8676
8695
  });
8677
8696
  inspection = {
8678
8697
  step,
8698
+ ...program && { program },
8679
8699
  exitCode: result.exitCode,
8680
8700
  signal: result.signal ?? null,
8681
8701
  timedOut: result.timedOut ?? false,
@@ -8688,9 +8708,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8688
8708
  options.onStep?.({ ...inspection });
8689
8709
  }
8690
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
+ };
8691
8720
  try {
8692
8721
  if (windows && options.hostImagesOnly) {
8693
- 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
+ ]);
8694
8728
  if (details.exitCode !== 0)
8695
8729
  throw new ProcessInspectionError(inspection);
8696
8730
  const value = JSON.parse(details.stdout);
@@ -8712,7 +8746,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8712
8746
  }
8713
8747
  return processes2;
8714
8748
  }
8715
- 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"]);
8716
8750
  if (result.exitCode !== 0)
8717
8751
  throw new ProcessInspectionError(inspection);
8718
8752
  const processes = [];
@@ -8746,12 +8780,12 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
8746
8780
  throw new ProcessInspectionError(inspection);
8747
8781
  const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
8748
8782
  if (windows && runtimes.length && options.inspectRuntimes !== false) {
8749
- const details = await inspect("CIM", "powershell.exe", [
8783
+ const details = await inspectCim([
8750
8784
  "-NoProfile",
8751
8785
  "-NonInteractive",
8752
8786
  "-Command",
8753
8787
  `$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`
8754
- ], WINDOWS_CIM_TIMEOUT_MS);
8788
+ ]);
8755
8789
  if (details.exitCode !== 0)
8756
8790
  throw new ProcessInspectionError(inspection);
8757
8791
  const value = JSON.parse(details.stdout || "null");
@@ -8807,6 +8841,35 @@ async function assertHostsStopped(fence, env) {
8807
8841
  throw new ProcessFenceViolationError(active);
8808
8842
  }
8809
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
+
8810
8873
  // ../../node_modules/@cortexkit/common-auth/dist/setup/enroll.js
8811
8874
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
8812
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.';
@@ -8836,7 +8899,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8836
8899
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
8837
8900
  const { name, displayName, requestedGrants, grantFallback, paths: input } = plugin.vault.hosts[host];
8838
8901
  const paths = hostEnrollmentPaths(input);
8839
- await fence();
8902
+ const guard = typeof fence === "function" ? new SetupProcessGuard(fence, io.now) : fence;
8903
+ await guard.check({ reuse: true });
8840
8904
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
8841
8905
  connectionFile: plugin.vault.connectionFile,
8842
8906
  handshakeTimeoutMs: 2000
@@ -8853,11 +8917,10 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8853
8917
  paths,
8854
8918
  client,
8855
8919
  writeTokenFile: async (path, file) => {
8856
- await fence();
8857
- await writeEnrollmentTokenFile2(path, file);
8920
+ await guard.check();
8921
+ await guard.step(() => writeEnrollmentTokenFile2(path, file));
8858
8922
  }
8859
8923
  });
8860
- await fence();
8861
8924
  const initial = await manager.status();
8862
8925
  if (initial.state === "approved") {
8863
8926
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
@@ -8874,7 +8937,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8874
8937
  let reportedCode;
8875
8938
  let failedProposals = 0;
8876
8939
  for (;; ) {
8877
- const status = await manager.reconcile();
8940
+ await guard.check({ reuse: true });
8941
+ const status = await guard.step(() => manager.reconcile());
8878
8942
  if (status.state === "approved") {
8879
8943
  printLine(terminal, `Connected ${host} to Claustrum.`);
8880
8944
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
@@ -8922,8 +8986,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8922
8986
  const remaining = deadline - now();
8923
8987
  if (remaining <= 0)
8924
8988
  break;
8925
- await wait(Math.min(pause, remaining));
8926
- await fence();
8989
+ await guard.step(() => wait(Math.min(pause, remaining)));
8990
+ await guard.check();
8927
8991
  }
8928
8992
  if (printedRequest)
8929
8993
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -9083,6 +9147,8 @@ async function selectSetupHosts(terminal, found) {
9083
9147
  }
9084
9148
 
9085
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";
9086
9152
  import { domainToUnicode } from "node:url";
9087
9153
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2, parseTree } from "jsonc-parser";
9088
9154
 
@@ -9294,12 +9360,14 @@ function planOpenCodeRegistration(plugin, generation, io = {}) {
9294
9360
  });
9295
9361
  }
9296
9362
  async function registerOpenCode(writes, beforeWrite) {
9363
+ const guard = typeof beforeWrite === "function" ? new SetupProcessGuard(beforeWrite) : beforeWrite;
9297
9364
  for (const write of writes) {
9298
9365
  if (!write.changed)
9299
9366
  continue;
9300
- await beforeWrite?.();
9301
9367
  await writeHostConfigAtomic(write.path, write.content, {
9302
- 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
9303
9371
  });
9304
9372
  }
9305
9373
  }
@@ -9400,7 +9468,11 @@ async function runSetup(plugin, argv = [], io = {}) {
9400
9468
  return { hosts, dryRun: options.dryRun, mode: "local", detection };
9401
9469
  }
9402
9470
  const { env, platform } = setupPaths(io);
9403
- 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
+ });
9404
9476
  const stopped = async () => {
9405
9477
  try {
9406
9478
  await assertHostsStopped(fence, env);
@@ -9410,6 +9482,7 @@ async function runSetup(plugin, argv = [], io = {}) {
9410
9482
  throw error;
9411
9483
  }
9412
9484
  };
9485
+ const guard = new SetupProcessGuard(stopped, io.now);
9413
9486
  printLine(terminal, "Checking that OpenCode and Pi are not running…");
9414
9487
  if (options.dryRun) {
9415
9488
  try {
@@ -9425,16 +9498,17 @@ async function runSetup(plugin, argv = [], io = {}) {
9425
9498
  if (error instanceof ProcessInspectionError)
9426
9499
  printLine(terminal, error.refusalText);
9427
9500
  }
9428
- } else
9429
- await stopped();
9501
+ } else {
9502
+ await guard.check();
9503
+ }
9430
9504
  if ((options.claustrum || options.enrollOnly) && !detection.claustrum.available)
9431
9505
  throw new Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");
9432
9506
  let useVault = options.claustrum || options.enrollOnly;
9433
9507
  if (!useVault && !options.login && !options.noClaustrum && !assumeYes && detection.claustrum.available && isInteractive(terminal)) {
9434
- const choice = await select(terminal, [
9508
+ const choice = await guard.step(() => select(terminal, [
9435
9509
  { label: "No", value: false },
9436
9510
  { label: "Yes", value: true }
9437
- ], { message: "Connect these hosts to the Claustrum vault?" });
9511
+ ], { message: "Connect these hosts to the Claustrum vault?" }));
9438
9512
  if (choice === null) {
9439
9513
  printLine(terminal, "Setup cancelled. Nothing was changed.");
9440
9514
  return { hosts: [], dryRun: options.dryRun, mode: "local", detection };
@@ -9485,13 +9559,14 @@ ${write.content}`);
9485
9559
  const enrollmentAccess = new Map;
9486
9560
  try {
9487
9561
  for (const host of hosts) {
9488
- await stopped();
9489
- await plugin.beforeSignIn?.(host, context);
9490
- await stopped();
9562
+ if (plugin.beforeSignIn) {
9563
+ await guard.check({ reuse: true });
9564
+ await guard.step(() => plugin.beforeSignIn?.(host, context));
9565
+ }
9491
9566
  if (useVault) {
9492
9567
  enrollment.set(host, "unknown");
9493
9568
  try {
9494
- const access = await connectSetupHost(plugin, host, io, terminal, stopped);
9569
+ const access = await connectSetupHost(plugin, host, io, terminal, guard);
9495
9570
  if (access)
9496
9571
  enrollmentAccess.set(host, access);
9497
9572
  } catch (error) {
@@ -9500,19 +9575,26 @@ ${write.content}`);
9500
9575
  throw error;
9501
9576
  }
9502
9577
  enrollment.set(host, "enrolled");
9503
- } else
9504
- await plugin.signInLocal(host, context);
9505
- await stopped();
9578
+ } else {
9579
+ await guard.check({ reuse: true });
9580
+ await guard.step(() => plugin.signInLocal(host, context));
9581
+ }
9506
9582
  if (options.enrollOnly)
9507
9583
  continue;
9508
- await plugin.beforeRegister?.(host, mode, context);
9509
- await stopped();
9584
+ if (plugin.beforeRegister) {
9585
+ await guard.check({ reuse: true });
9586
+ await guard.step(() => plugin.beforeRegister?.(host, mode, context));
9587
+ }
9510
9588
  if (host === "opencode")
9511
- await registerOpenCode(writes, stopped);
9512
- else
9513
- await registerPi(plugin, detection.pi.executable, io);
9514
- await stopped();
9515
- 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
+ }
9516
9598
  }
9517
9599
  } catch (error) {
9518
9600
  if (enrollment.size === 0)
@@ -9536,12 +9618,12 @@ ${write.content}`);
9536
9618
  }
9537
9619
  // src/accounts.ts
9538
9620
  import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
9539
- 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";
9540
9622
  import { homedir as homedir3 } from "node:os";
9541
9623
  import { join as join13 } from "node:path";
9542
9624
 
9543
9625
  // src/claustrum.ts
9544
- import { readdirSync, statSync as statSync3 } from "node:fs";
9626
+ import { readdirSync, statSync as statSync4 } from "node:fs";
9545
9627
  import * as fs from "node:fs/promises";
9546
9628
  import { tmpdir as tmpdir3, userInfo } from "node:os";
9547
9629
  import { join as join9 } from "node:path";
@@ -9553,7 +9635,7 @@ var CLAUSTRUM_TEMP_PREFIX = "subc-";
9553
9635
  var CLAUSTRUM_TEMP_SUFFIX = ".connection.json";
9554
9636
  function safeIsFile(path) {
9555
9637
  try {
9556
- return statSync3(path).isFile();
9638
+ return statSync4(path).isFile();
9557
9639
  } catch {
9558
9640
  return false;
9559
9641
  }
@@ -10322,8 +10404,8 @@ async function refreshClaudeOAuthToken(input) {
10322
10404
  for (let attempt = 0;attempt <= maxRetries; attempt++) {
10323
10405
  try {
10324
10406
  if (attempt > 0) {
10325
- const delay3 = baseDelayMs * 2 ** (attempt - 1);
10326
- await new Promise((resolve12) => setTimeoutImpl(resolve12, delay3));
10407
+ const delay4 = baseDelayMs * 2 ** (attempt - 1);
10408
+ await new Promise((resolve12) => setTimeoutImpl(resolve12, delay4));
10327
10409
  }
10328
10410
  const signal = auxiliaryRequestSignal();
10329
10411
  const response = await raceWithSignal(signal, () => fetchImpl(TOKEN_URL, {
@@ -10496,7 +10578,7 @@ function hostRetryResponse(response, now = Date.now()) {
10496
10578
  // src/path-options.ts
10497
10579
  import { realpath as realpath3 } from "node:fs/promises";
10498
10580
  import { homedir as homedir2 } from "node:os";
10499
- import { posix as posix3, win32 as win323 } from "node:path";
10581
+ import { posix as posix3, win32 as win324 } from "node:path";
10500
10582
 
10501
10583
  // ../../node_modules/@cortexkit/common-auth/dist/settings/descriptors.js
10502
10584
  function boolean() {
@@ -10610,7 +10692,7 @@ function isOverrideKeyAllowed(overrides, key) {
10610
10692
  import { join as join11, resolve as resolve13 } from "node:path";
10611
10693
 
10612
10694
  // ../../node_modules/@cortexkit/common-auth/dist/tui-prefs/watcher.js
10613
- 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";
10614
10696
  import { readFile as readFile5, stat as stat8 } from "node:fs/promises";
10615
10697
  import { basename as basename5, dirname as dirname9, join as join10, resolve as resolve12 } from "node:path";
10616
10698
  import { clearTimeout as clearTimeout2, setTimeout as setTimeout2 } from "node:timers";
@@ -10654,7 +10736,7 @@ function watchFile(file, onChange, options, settings) {
10654
10736
  let lastSeen = null;
10655
10737
  if (settings || !windowsPrivateFiles)
10656
10738
  try {
10657
- const metadata = identity2((options.fs?.statSync ?? statSync4)(path), settings);
10739
+ const metadata = identity2((options.fs?.statSync ?? statSync5)(path), settings);
10658
10740
  lastSeen = (options.fs?.readFileSync ?? ((file2) => readFileSync2(file2, "utf8")))(path);
10659
10741
  lastMetadata = metadata;
10660
10742
  } catch {}
@@ -12095,7 +12177,7 @@ async function moveSettingsOnce(options) {
12095
12177
  }
12096
12178
  }
12097
12179
  // ../../node_modules/@cortexkit/common-auth/dist/settings/paths.js
12098
- import { posix as posix2, win32 as win322 } from "node:path";
12180
+ import { posix as posix2, win32 as win323 } from "node:path";
12099
12181
  function isAbsoluteForPlatform(path, platform) {
12100
12182
  if (platform !== "win32")
12101
12183
  return path.startsWith("/");
@@ -12106,7 +12188,7 @@ function isAbsoluteForPlatform(path, platform) {
12106
12188
  return /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(path);
12107
12189
  }
12108
12190
  function cortexkitConfigDir({ env, platform, homedir: homedir2 }) {
12109
- const paths = platform === "win32" ? win322 : posix2;
12191
+ const paths = platform === "win32" ? win323 : posix2;
12110
12192
  const absolute = (value) => value !== undefined && isAbsoluteForPlatform(value, platform);
12111
12193
  let base;
12112
12194
  if (absolute(env.XDG_CONFIG_HOME)) {
@@ -12129,7 +12211,7 @@ function settingsFilePath({ plugin, override, ...options }) {
12129
12211
  if (override && isAbsoluteForPlatform(override, options.platform)) {
12130
12212
  return override;
12131
12213
  }
12132
- const paths = options.platform === "win32" ? win322 : posix2;
12214
+ const paths = options.platform === "win32" ? win323 : posix2;
12133
12215
  return paths.join(cortexkitConfigDir(options), `${plugin}.jsonc`);
12134
12216
  }
12135
12217
  // src/path-options.ts
@@ -12143,7 +12225,7 @@ function resolvePathOptions(options = {}) {
12143
12225
  home,
12144
12226
  platform,
12145
12227
  realpath: options.realpath ?? realpath3,
12146
- paths: platform === "win32" ? win323 : posix3
12228
+ paths: platform === "win32" ? win324 : posix3
12147
12229
  };
12148
12230
  }
12149
12231
 
@@ -12590,7 +12672,7 @@ async function acquireRefreshFileLock2(options) {
12590
12672
  await options.onStep?.("stale-marker-stat");
12591
12673
  const claimedPath = `${evictPath}.${randomUUID8()}`;
12592
12674
  try {
12593
- await rename7(evictPath, claimedPath);
12675
+ await rename8(evictPath, claimedPath);
12594
12676
  } catch (renameError) {
12595
12677
  if (renameError.code === "ENOENT") {
12596
12678
  await backoff();
@@ -12719,15 +12801,15 @@ function buildRefreshOperationError(input) {
12719
12801
  const previousRetryCount = input.previous?.accountIdentity === input.accountIdentity && input.previous?.refreshTokenFingerprint === input.refreshTokenFingerprint ? input.previous?.retryCount ?? 0 : 0;
12720
12802
  const retryCount = previousRetryCount + 1;
12721
12803
  const retryAfterFromError = input.error.retryAfter;
12722
- let delay3;
12804
+ let delay4;
12723
12805
  if (typeof retryAfterFromError === "number" && retryAfterFromError > 0) {
12724
- delay3 = retryAfterFromError * 1000;
12806
+ delay4 = retryAfterFromError * 1000;
12725
12807
  } else if (isTransientNetworkError(input.error)) {
12726
- delay3 = MIN_REFRESH_RETRY_DELAY_MS;
12808
+ delay4 = MIN_REFRESH_RETRY_DELAY_MS;
12727
12809
  } else if (isTransientRefreshError(input.error)) {
12728
- 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));
12729
12811
  } else {
12730
- delay3 = NON_TRANSIENT_REFRESH_RETRY_DELAY_MS;
12812
+ delay4 = NON_TRANSIENT_REFRESH_RETRY_DELAY_MS;
12731
12813
  }
12732
12814
  const statusFromError = input.error.status;
12733
12815
  const status = typeof statusFromError === "number" && Number.isFinite(statusFromError) ? statusFromError : undefined;
@@ -12737,7 +12819,7 @@ function buildRefreshOperationError(input) {
12737
12819
  return {
12738
12820
  message,
12739
12821
  checkedAt: input.now,
12740
- nextRetryAt: input.now + delay3,
12822
+ nextRetryAt: input.now + delay4,
12741
12823
  retryCount,
12742
12824
  accountIdentity: input.accountIdentity,
12743
12825
  refreshTokenFingerprint: input.refreshTokenFingerprint,
@@ -12799,11 +12881,11 @@ function isQuotaPolicyAuthError(error) {
12799
12881
  function buildQuotaOperationError(input) {
12800
12882
  const previousRetryCount = input.previous?.accountIdentity === input.accountIdentity ? input.previous?.retryCount ?? 0 : 0;
12801
12883
  const retryCount = previousRetryCount + 1;
12802
- 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;
12803
12885
  return {
12804
12886
  message: formatErrorMessage(input.error),
12805
12887
  checkedAt: input.now,
12806
- nextRetryAt: input.now + delay3,
12888
+ nextRetryAt: input.now + delay4,
12807
12889
  retryCount,
12808
12890
  ...input.accountIdentity !== undefined && {
12809
12891
  accountIdentity: input.accountIdentity
@@ -14258,6 +14340,7 @@ function executeCache1hCommand(input) {
14258
14340
  `);
14259
14341
  }
14260
14342
  // src/cachekeep.ts
14343
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
14261
14344
  import { createHash as createHash9 } from "node:crypto";
14262
14345
 
14263
14346
  // ../../node_modules/@cortexkit/common-auth/dist/cachekeep/decision.js
@@ -14274,7 +14357,7 @@ function withinHours(hours, at) {
14274
14357
  return hours.from < hours.to ? time >= hours.from && time < hours.to : time >= hours.from || time < hours.to;
14275
14358
  }
14276
14359
  function decideCacheKeep(input) {
14277
- const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost } = input;
14360
+ const { mode, now, ttlMs, leadMs = 30000, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost } = input;
14278
14361
  if (mode === "off")
14279
14362
  return { action: "stop", reason: "unsupported" };
14280
14363
  if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
@@ -14286,10 +14369,11 @@ function decideCacheKeep(input) {
14286
14369
  return { action: "stop", reason: "cost-cap" };
14287
14370
  const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
14288
14371
  const expiresAt = last + ttlMs;
14289
- const due = expiresAt - Math.min(30000, ttlMs / 2);
14372
+ const lead = Math.min(Number.isFinite(leadMs) && leadMs > 0 ? leadMs : 30000, ttlMs / 2);
14373
+ const due = expiresAt - lead;
14290
14374
  const at = Math.max(now, due);
14291
14375
  if (at >= expiresAt - Math.min(5000, ttlMs / 10)) {
14292
- return { action: "stop", reason: "cost-cap" };
14376
+ return { action: "stop", reason: "deadline-missed" };
14293
14377
  }
14294
14378
  if (mode === "hours" && (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
14295
14379
  return { action: "stop", reason: "outside-hours" };
@@ -14383,6 +14467,7 @@ class CacheKeepManager {
14383
14467
  log;
14384
14468
  ttlMs;
14385
14469
  leadMs;
14470
+ planLeadMs;
14386
14471
  maxIdleWarmMs;
14387
14472
  maxSubagentIdleMs;
14388
14473
  tickIntervalMs;
@@ -14408,6 +14493,7 @@ class CacheKeepManager {
14408
14493
  this.ttlMs = positive(options.ttlMs, DEFAULT_TTL_MS);
14409
14494
  this.tickIntervalMs = positive(options.tickIntervalMs, DEFAULT_TICK_INTERVAL_MS);
14410
14495
  this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15000);
14496
+ this.planLeadMs = options.planLeadMs;
14411
14497
  this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
14412
14498
  this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
14413
14499
  this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
@@ -14628,7 +14714,7 @@ class CacheKeepManager {
14628
14714
  cacheExpiresAt: target.cacheExpiresAt,
14629
14715
  failures: target.failures
14630
14716
  });
14631
- this.drop(sessionKey, target.plan ? "cost-cap" : "expired");
14717
+ this.drop(sessionKey, target.plan ? "deadline-missed" : "expired");
14632
14718
  return true;
14633
14719
  }
14634
14720
  isCurrent(sessionKey, target) {
@@ -14689,6 +14775,7 @@ class CacheKeepManager {
14689
14775
  ...plan.mode === "hours" ? { mode: plan.mode, hours: plan.hours } : { mode: plan.mode },
14690
14776
  now: this.now(),
14691
14777
  ttlMs: target.ttlMs,
14778
+ ...this.planLeadMs !== undefined ? { leadMs: this.planLeadMs } : {},
14692
14779
  lastRealRequestAt: target.lastRealRequestAt,
14693
14780
  lastWarmAt: target.lastWarmedAt,
14694
14781
  warmsSinceLastRealRequest: target.warmCount,
@@ -14746,16 +14833,16 @@ class CacheKeepManager {
14746
14833
  return;
14747
14834
  target.failures += 1;
14748
14835
  const now = this.now();
14749
- let delay3 = typeof this.backoff === "function" ? this.backoff({ sessionKey, failures: target.failures }) : this.backoff ?? DEFAULT_BACKOFF_MS;
14836
+ let delay4 = typeof this.backoff === "function" ? this.backoff({ sessionKey, failures: target.failures }) : this.backoff ?? DEFAULT_BACKOFF_MS;
14750
14837
  const deadline = this.lastRetryStart(target);
14751
14838
  const fastRetry = this.backoff === undefined && transient && now < deadline;
14752
14839
  if (fastRetry) {
14753
- delay3 = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
14840
+ delay4 = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
14754
14841
  }
14755
- target.backoffUntil = now + (Number.isFinite(delay3) && delay3 > 0 ? delay3 : 0);
14842
+ target.backoffUntil = now + (Number.isFinite(delay4) && delay4 > 0 ? delay4 : 0);
14756
14843
  this.clearRetry(target);
14757
14844
  if (fastRetry)
14758
- this.scheduleRetry(sessionKey, target, delay3);
14845
+ this.scheduleRetry(sessionKey, target, delay4);
14759
14846
  else if (target.plan) {
14760
14847
  this.schedulePlan(sessionKey, target, target.backoffUntil);
14761
14848
  }
@@ -14780,7 +14867,7 @@ class CacheKeepManager {
14780
14867
  this.clearIntervalImpl(target.retryTimer);
14781
14868
  target.retryTimer = undefined;
14782
14869
  }
14783
- scheduleRetry(sessionKey, target, delay3) {
14870
+ scheduleRetry(sessionKey, target, delay4) {
14784
14871
  target.retryTimer = this.setIntervalImpl(() => {
14785
14872
  this.clearRetry(target);
14786
14873
  return (async () => {
@@ -14790,7 +14877,7 @@ class CacheKeepManager {
14790
14877
  })().catch((error) => {
14791
14878
  this.log?.warn("cachekeep tick failed", classifyFailure(error, "send"));
14792
14879
  });
14793
- }, delay3);
14880
+ }, delay4);
14794
14881
  if (typeof target.retryTimer === "object" && "unref" in target.retryTimer) {
14795
14882
  target.retryTimer.unref();
14796
14883
  }
@@ -14978,7 +15065,7 @@ import {
14978
15065
  mkdir as mkdir7,
14979
15066
  open as open8,
14980
15067
  realpath as realpath4,
14981
- rename as rename8,
15068
+ rename as rename9,
14982
15069
  stat as stat11,
14983
15070
  unlink as unlink6
14984
15071
  } from "node:fs/promises";
@@ -15571,7 +15658,7 @@ async function writeStateAtomic2(path2, state, beforeRename) {
15571
15658
  descriptor = undefined;
15572
15659
  await chmod2(temporary, 384);
15573
15660
  await beforeRename();
15574
- await rename8(temporary, path2);
15661
+ await rename9(temporary, path2);
15575
15662
  } finally {
15576
15663
  await descriptor?.close().catch(() => {});
15577
15664
  await unlink6(temporary).catch(() => {});
@@ -15582,7 +15669,7 @@ async function writeTokenAtomic(path2, value, writeTokenFile, beforeRename) {
15582
15669
  try {
15583
15670
  await writeTokenFile(staged, value);
15584
15671
  await beforeRename();
15585
- await rename8(staged, path2);
15672
+ await rename9(staged, path2);
15586
15673
  } finally {
15587
15674
  await unlink6(staged).catch(() => {});
15588
15675
  }
@@ -16043,14 +16130,14 @@ function createNativeCustody(options) {
16043
16130
  let probe;
16044
16131
  const setTimer = options.setTimeout ?? setTimeout;
16045
16132
  const clearTimer = options.clearTimeout ?? clearTimeout;
16046
- const guardedTimer = (callback, delay3, ...args) => setTimer(() => {
16133
+ const guardedTimer = (callback, delay4, ...args) => setTimer(() => {
16047
16134
  try {
16048
16135
  check();
16049
16136
  } catch {
16050
16137
  return;
16051
16138
  }
16052
16139
  callback(...args);
16053
- }, delay3);
16140
+ }, delay4);
16054
16141
  function closeProbe(held) {
16055
16142
  if (held.closed || held.promoted)
16056
16143
  return;
@@ -17148,7 +17235,7 @@ import {
17148
17235
  mkdir as mkdir8,
17149
17236
  readdir as readdir4,
17150
17237
  readFile as readFile9,
17151
- rename as rename9,
17238
+ rename as rename10,
17152
17239
  unlink as unlink7,
17153
17240
  writeFile as writeFile2
17154
17241
  } from "node:fs/promises";
@@ -17158,7 +17245,7 @@ import { join as join17, resolve as resolve17 } from "node:path";
17158
17245
  // src/gateway.ts
17159
17246
  import { execFile } from "node:child_process";
17160
17247
  import { readFile as readFile8, realpath as realpath5 } from "node:fs/promises";
17161
- import { posix as posix4, resolve as resolve16, win32 as win324 } from "node:path";
17248
+ import { posix as posix4, resolve as resolve16, win32 as win325 } from "node:path";
17162
17249
 
17163
17250
  // src/custom-headers.ts
17164
17251
  var ANTHROPIC_CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
@@ -17489,7 +17576,7 @@ async function posixAccountHome(dependencies) {
17489
17576
  return passwdHome(await dependencies.readFile("/etc/passwd"), uid);
17490
17577
  }
17491
17578
  async function windowsAppData(dependencies) {
17492
- const output = await dependencies.run(win324.join(WINDOWS_ROOT, "System32", "reg.exe"), ["query", WINDOWS_SHELL_FOLDERS, "/v", "AppData"], { SystemRoot: WINDOWS_ROOT });
17579
+ const output = await dependencies.run(win325.join(WINDOWS_ROOT, "System32", "reg.exe"), ["query", WINDOWS_SHELL_FOLDERS, "/v", "AppData"], { SystemRoot: WINDOWS_ROOT });
17493
17580
  const value = /^\s*AppData\s+REG_SZ\s+(.+?)\s*$/im.exec(output)?.[1];
17494
17581
  return value && !value.includes("%") ? value : undefined;
17495
17582
  }
@@ -17497,7 +17584,7 @@ async function lookupGatewaySettingsFile(dependencies) {
17497
17584
  try {
17498
17585
  if (dependencies.platform === "win32") {
17499
17586
  const appData = await windowsAppData(dependencies);
17500
- return appData && win324.isAbsolute(appData) ? win324.join(appData, "cortexkit", "anthropic-auth.jsonc") : undefined;
17587
+ return appData && win325.isAbsolute(appData) ? win325.join(appData, "cortexkit", "anthropic-auth.jsonc") : undefined;
17501
17588
  }
17502
17589
  const home = await posixAccountHome(dependencies);
17503
17590
  return home && posix4.isAbsolute(home) ? posix4.join(home, ".config", "cortexkit", "anthropic-auth.jsonc") : undefined;
@@ -17512,11 +17599,11 @@ function registryPath(output, name) {
17512
17599
  return value && !value.includes("%") ? value : undefined;
17513
17600
  }
17514
17601
  async function windowsAccountSid(dependencies) {
17515
- const output = await dependencies.run(win324.join(WINDOWS_ROOT, "System32", "whoami.exe"), ["/user", "/fo", "csv", "/nh"], { SystemRoot: WINDOWS_ROOT });
17602
+ const output = await dependencies.run(win325.join(WINDOWS_ROOT, "System32", "whoami.exe"), ["/user", "/fo", "csv", "/nh"], { SystemRoot: WINDOWS_ROOT });
17516
17603
  return /"(S-1-\d+(?:-\d+)+)"\s*$/m.exec(output)?.[1];
17517
17604
  }
17518
17605
  async function windowsProfile(dependencies) {
17519
- const reg = win324.join(WINDOWS_ROOT, "System32", "reg.exe");
17606
+ const reg = win325.join(WINDOWS_ROOT, "System32", "reg.exe");
17520
17607
  const env = { SystemRoot: WINDOWS_ROOT };
17521
17608
  const fromProfileList = await windowsAccountSid(dependencies).then(async (sid) => sid ? registryPath(await dependencies.run(reg, [
17522
17609
  "query",
@@ -17534,7 +17621,7 @@ async function lookupAccountHome(dependencies) {
17534
17621
  try {
17535
17622
  if (dependencies.platform === "win32") {
17536
17623
  const profile = await windowsProfile(dependencies);
17537
- return profile && win324.isAbsolute(profile) ? profile : undefined;
17624
+ return profile && win325.isAbsolute(profile) ? profile : undefined;
17538
17625
  }
17539
17626
  const home = await posixAccountHome(dependencies);
17540
17627
  return home && posix4.isAbsolute(home) ? home : undefined;
@@ -17681,7 +17768,7 @@ async function writeDumpFile(path2, contents) {
17681
17768
  try {
17682
17769
  await writeFile2(partialPath, contents, { encoding: "utf8", flag: "wx" });
17683
17770
  created = true;
17684
- await rename9(partialPath, path2);
17771
+ await rename10(partialPath, path2);
17685
17772
  return true;
17686
17773
  } catch (error) {
17687
17774
  if (error.code === "EEXIST")
@@ -19786,6 +19873,9 @@ function withSessionCacheReportHandoff(work) {
19786
19873
  function reportSessionCacheTouch(sessionId, input) {
19787
19874
  detachReport2(() => reportCacheTouch(sessionId, input), input.source === "response", input.source === "warm");
19788
19875
  }
19876
+ function isSessionCacheWarmStopReason(value) {
19877
+ return isCacheWarmStopReason(value);
19878
+ }
19789
19879
  function reportSessionCacheWarmStopped(sessionId, input) {
19790
19880
  return detachReport2(() => reportCacheWarmStopped(sessionId, input));
19791
19881
  }
@@ -19874,7 +19964,9 @@ var CLAUDE_CACHE_KEEP_COMMAND_NAME = "claude-cachekeep";
19874
19964
  var CACHE_KEEP_TTL_MS = 60 * 60000;
19875
19965
  var CACHE_KEEP_PREWARM_LEAD_MS = 5 * 60000;
19876
19966
  function replayPrewarmLeadMs(ttlMs, planned) {
19877
- if (!planned && ttlMs === CACHE_KEEP_TTL_MS)
19967
+ if (planned)
19968
+ return Math.min(CACHE_KEEP_PREWARM_LEAD_MS, ttlMs / 2);
19969
+ if (ttlMs === CACHE_KEEP_TTL_MS)
19878
19970
  return CACHE_KEEP_PREWARM_LEAD_MS;
19879
19971
  return Math.min(30000, ttlMs / 2);
19880
19972
  }
@@ -20139,6 +20231,7 @@ function stopReason(reason) {
20139
20231
  case "schedule-period-ended":
20140
20232
  return "schedule";
20141
20233
  case "retry-window-ended":
20234
+ case "deadline-missed":
20142
20235
  return "retries-exhausted";
20143
20236
  case "cachekeep-hybrid-inactive":
20144
20237
  return "disabled";
@@ -20151,34 +20244,22 @@ function stopReason(reason) {
20151
20244
  }
20152
20245
  }
20153
20246
  function reportStopReason(reason) {
20247
+ if (isSessionCacheWarmStopReason(reason))
20248
+ return reason;
20154
20249
  switch (reason) {
20155
- case "cost-cap":
20156
- case "count-cap":
20157
- case "outside-hours":
20158
- case "session-ended":
20159
- case "unsupported":
20160
- case "evicted":
20161
- case "stopped":
20162
- case "account-changed":
20163
- case "routing-moved":
20164
- case "expired":
20165
- case "idle":
20166
- return reason;
20167
- case "budget":
20168
- case "count":
20169
- return "evicted";
20170
20250
  case "schedule":
20171
20251
  case "schedule-period-ended":
20172
20252
  return "outside-hours";
20253
+ case "stopped":
20173
20254
  case "session-forgotten":
20174
20255
  return "session-ended";
20175
20256
  case "retry-window-ended":
20176
- return "expired";
20257
+ case "retries-exhausted":
20258
+ case "expired":
20259
+ return "deadline-missed";
20260
+ case "idle":
20177
20261
  case "source-warm-idle-cap":
20178
20262
  return "cost-cap";
20179
- case "credential-changed":
20180
- case "account-unavailable":
20181
- return "account-changed";
20182
20263
  default:
20183
20264
  return "unsupported";
20184
20265
  }
@@ -20271,6 +20352,23 @@ class CacheKeepWarmRefusal extends Error {
20271
20352
  this.reason = reason;
20272
20353
  }
20273
20354
  }
20355
+ var CACHE_KEEP_WARM_WAIT = Symbol.for("cortexkit.anthropic-auth.cachekeep.wait");
20356
+
20357
+ class CacheKeepWarmWait extends Error {
20358
+ [CACHE_KEEP_WARM_WAIT] = true;
20359
+ }
20360
+ function isCacheKeepWarmWait(error) {
20361
+ try {
20362
+ return typeof error === "object" && error !== null && Object.getOwnPropertyDescriptor(error, CACHE_KEEP_WARM_WAIT)?.value === true;
20363
+ } catch {
20364
+ return false;
20365
+ }
20366
+ }
20367
+ var realTurnContext = new AsyncLocalStorage3;
20368
+ var currentCacheKeepRealTurn = () => realTurnContext.getStore();
20369
+ function withCacheKeepRealTurn(turn, run) {
20370
+ return realTurnContext.run(turn, run);
20371
+ }
20274
20372
 
20275
20373
  class CacheKeepManager2 {
20276
20374
  options;
@@ -20281,8 +20379,19 @@ class CacheKeepManager2 {
20281
20379
  timer = null;
20282
20380
  dueTimer = null;
20283
20381
  tickPromise = null;
20382
+ lifetime = 0;
20383
+ schedulerGeneration = 0;
20384
+ nextRealTurn = 0;
20385
+ realTurns = new Map;
20386
+ turnTimers = new Set;
20387
+ ticks = new Set;
20388
+ warmRuns = new Set;
20389
+ warmControllers = new Map;
20284
20390
  nextPrewarmAttemptId = 0;
20285
20391
  reportedStops = new WeakSet;
20392
+ restoredTargets = new WeakSet;
20393
+ restoringPolicies = new WeakSet;
20394
+ sessionWarms = new Map;
20286
20395
  admittedWarmCosts = new WeakMap;
20287
20396
  constructor(options) {
20288
20397
  this.options = options;
@@ -20292,7 +20401,7 @@ class CacheKeepManager2 {
20292
20401
  return;
20293
20402
  logger2.debug("cachekeep", "started");
20294
20403
  this.timer = (this.options.setIntervalImpl ?? globalThis.setInterval)(() => {
20295
- this.tick().catch(() => {
20404
+ return this.tick().catch(() => {
20296
20405
  logger2.warn("cachekeep", "tick failed");
20297
20406
  });
20298
20407
  }, CACHE_KEEP_TICK_MS);
@@ -20301,10 +20410,9 @@ class CacheKeepManager2 {
20301
20410
  this.scheduleDueTimer();
20302
20411
  }
20303
20412
  stop() {
20413
+ this.schedulerGeneration++;
20414
+ this.tickPromise = null;
20304
20415
  this.immediateTargets.clear();
20305
- const now = this.options.now?.() ?? Date.now();
20306
- for (const target of this.targets.values())
20307
- this.reportStop(target, "stopped", now);
20308
20416
  if (this.dueTimer) {
20309
20417
  (this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
20310
20418
  this.dueTimer = null;
@@ -20316,6 +20424,172 @@ class CacheKeepManager2 {
20316
20424
  clearIntervalImpl(this.timer);
20317
20425
  this.timer = null;
20318
20426
  }
20427
+ dispose() {
20428
+ this.lifetime++;
20429
+ this.stop();
20430
+ this.abortWarms();
20431
+ for (const timer of this.turnTimers) {
20432
+ try {
20433
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
20434
+ } catch {}
20435
+ }
20436
+ this.turnTimers.clear();
20437
+ this.realTurns.clear();
20438
+ this.targets.clear();
20439
+ this.immediateTargets.clear();
20440
+ this.stoppedSessions.clear();
20441
+ this.warmingRecords.clear();
20442
+ this.sessionWarms.clear();
20443
+ this.tickPromise = null;
20444
+ return this.drain();
20445
+ }
20446
+ abortWarms() {
20447
+ for (const controller of this.warmControllers.keys())
20448
+ controller.abort();
20449
+ }
20450
+ async drain() {
20451
+ await Promise.allSettled([...this.ticks, ...this.warmRuns]);
20452
+ }
20453
+ beginRealTurn(sessionId) {
20454
+ let active = true;
20455
+ let busy = true;
20456
+ let tracked = false;
20457
+ const lifetime = this.lifetime;
20458
+ const id = ++this.nextRealTurn;
20459
+ let now = Date.now();
20460
+ try {
20461
+ now = this.options.now?.() ?? now;
20462
+ } catch {}
20463
+ const ownerExpiry = Math.min(...[...this.targets.values()].filter((target) => target.policyState?.ownerSessionId === sessionId).map((target) => target.cacheExpiresAt));
20464
+ const expiresAt = this.targets.get(sessionId)?.cacheExpiresAt ?? (Number.isFinite(ownerExpiry) ? ownerExpiry : now + CACHE_KEEP_TTL_MS);
20465
+ const turns = this.realTurns.get(sessionId) ?? {
20466
+ latest: id,
20467
+ pending: 0,
20468
+ leases: new Set
20469
+ };
20470
+ turns.latest = id;
20471
+ turns.pending++;
20472
+ this.realTurns.set(sessionId, turns);
20473
+ let timer;
20474
+ const currentTime = () => {
20475
+ try {
20476
+ return this.options.now?.() ?? Date.now();
20477
+ } catch {
20478
+ return Date.now();
20479
+ }
20480
+ };
20481
+ const clearTimer = () => {
20482
+ if (timer) {
20483
+ this.turnTimers.delete(timer);
20484
+ try {
20485
+ (this.options.clearTimeoutImpl ?? clearTimeout)(timer);
20486
+ } catch {}
20487
+ timer = undefined;
20488
+ }
20489
+ };
20490
+ const releaseBusy = () => {
20491
+ if (!busy)
20492
+ return;
20493
+ busy = false;
20494
+ turns.leases.delete(record6);
20495
+ clearTimer();
20496
+ };
20497
+ const release = (silent = false) => {
20498
+ if (!active)
20499
+ return;
20500
+ active = false;
20501
+ releaseBusy();
20502
+ clearTimer();
20503
+ turns.pending--;
20504
+ try {
20505
+ if (!silent && lifetime === this.lifetime && turns.latest === id && currentTime() < expiresAt + CACHE_KEEP_TTL_MS)
20506
+ this.finishSessionTargets(sessionId, tracked ? this.targets.get(sessionId) : undefined);
20507
+ } catch {} finally {
20508
+ if (turns.pending === 0 && this.realTurns.get(sessionId) === turns)
20509
+ this.realTurns.delete(sessionId);
20510
+ try {
20511
+ if (lifetime === this.lifetime)
20512
+ this.scheduleDueTimer();
20513
+ } catch {}
20514
+ }
20515
+ };
20516
+ const record6 = {
20517
+ id,
20518
+ expiresAt,
20519
+ expire: () => {
20520
+ if (!active || lifetime !== this.lifetime) {
20521
+ release(true);
20522
+ return;
20523
+ }
20524
+ if (!busy)
20525
+ return;
20526
+ releaseBusy();
20527
+ const remaining = expiresAt + CACHE_KEEP_TTL_MS - currentTime();
20528
+ if (remaining <= 0)
20529
+ release(true);
20530
+ else {
20531
+ try {
20532
+ timer = (this.options.setTimeoutImpl ?? setTimeout)(() => release(true), remaining);
20533
+ timer.unref?.();
20534
+ this.turnTimers.add(timer);
20535
+ if (lifetime === this.lifetime)
20536
+ this.scheduleDueTimer();
20537
+ } catch {}
20538
+ }
20539
+ }
20540
+ };
20541
+ turns.leases.add(record6);
20542
+ try {
20543
+ timer = (this.options.setTimeoutImpl ?? setTimeout)(record6.expire, Math.max(0, expiresAt - now));
20544
+ timer.unref?.();
20545
+ this.turnTimers.add(timer);
20546
+ for (const [controller, session] of this.warmControllers)
20547
+ if (session === sessionId)
20548
+ controller.abort();
20549
+ this.scheduleDueTimer();
20550
+ } catch {}
20551
+ const thisManager = this;
20552
+ return {
20553
+ get active() {
20554
+ try {
20555
+ return active && busy && lifetime === thisManager.lifetime && (thisManager.options.now?.() ?? Date.now()) < expiresAt;
20556
+ } catch {
20557
+ return false;
20558
+ }
20559
+ },
20560
+ track: (input) => {
20561
+ if (turns.latest !== id) {
20562
+ release();
20563
+ return { tracked: false, reason: "superseded real turn" };
20564
+ }
20565
+ if (!active || lifetime !== this.lifetime || currentTime() >= expiresAt + CACHE_KEEP_TTL_MS) {
20566
+ release(true);
20567
+ return { tracked: false, reason: "real turn ended" };
20568
+ }
20569
+ try {
20570
+ const result = this.track({ ...input, sessionId });
20571
+ tracked = result.tracked;
20572
+ return result;
20573
+ } catch {
20574
+ return { tracked: false, reason: "real turn tracking failed" };
20575
+ } finally {
20576
+ release();
20577
+ }
20578
+ },
20579
+ finish: () => release(),
20580
+ pause: () => release(true)
20581
+ };
20582
+ }
20583
+ realTurnBusy(sessionId) {
20584
+ const turns = this.realTurns.get(sessionId);
20585
+ if (!turns)
20586
+ return false;
20587
+ let now = Date.now();
20588
+ try {
20589
+ now = this.options.now?.() ?? now;
20590
+ } catch {}
20591
+ return [...turns.leases].some((turn) => turn.expiresAt > now);
20592
+ }
20319
20593
  stats(window, now = this.options.now?.() ?? Date.now(), always = false) {
20320
20594
  const today = always ? "always" : localWindowKey(window, new Date(now));
20321
20595
  const targets = [...this.targets.values()].filter((target) => target.dayKey === today);
@@ -20393,7 +20667,10 @@ class CacheKeepManager2 {
20393
20667
  const record6 = this.warmingRecords.get(id);
20394
20668
  if (!record6)
20395
20669
  return;
20396
- return isCacheWarmStopReason(record6.stopReason) ? { on: false, stopReason: record6.stopReason } : { on: false };
20670
+ return isSessionCacheWarmStopReason(record6.stopReason) ? {
20671
+ on: false,
20672
+ stopReason: record6.stopReason
20673
+ } : { on: false };
20397
20674
  }
20398
20675
  recordWarmingOff(id) {
20399
20676
  this.setWarmingRecord(id, {});
@@ -20423,7 +20700,7 @@ class CacheKeepManager2 {
20423
20700
  this.options.onTargetChanged?.(target);
20424
20701
  this.scheduleDueTimer();
20425
20702
  }
20426
- costs(target) {
20703
+ costs(target, ownReservation = false) {
20427
20704
  const state = target.policyState;
20428
20705
  if (state?.prefixTokens === undefined)
20429
20706
  return;
@@ -20451,14 +20728,22 @@ class CacheKeepManager2 {
20451
20728
  return {
20452
20729
  nextWarmCost: read * state.prefixTokens,
20453
20730
  rewriteCost: write * state.prefixTokens,
20454
- warmCostSoFar: state.warmCostSoFar
20731
+ warmCostSoFar: state.warmCostSoFar + Math.max(0, (state.pendingWarmCost ?? 0) - (ownReservation ? this.admittedWarmCosts.get(state) ?? 0 : 0))
20455
20732
  };
20456
20733
  }
20457
20734
  policyDecision(target, now, ownReservation = false) {
20458
20735
  const state = target.policyState;
20459
20736
  if (!state)
20460
20737
  return;
20461
- const policy = readSessionCachePolicy(state.ownerSessionId, true);
20738
+ const freshPolicy = readSessionCachePolicy(state.ownerSessionId, true);
20739
+ if (freshPolicy) {
20740
+ if (JSON.stringify(state.policy) !== JSON.stringify(freshPolicy)) {
20741
+ state.policy = structuredClone(freshPolicy);
20742
+ this.options.onTargetChanged?.(target);
20743
+ }
20744
+ this.restoringPolicies.delete(state);
20745
+ }
20746
+ const policy = freshPolicy ?? (this.restoringPolicies.has(state) ? state.policy : undefined);
20462
20747
  if (!policy && state.planned)
20463
20748
  return { action: "stop", reason: "session-ended" };
20464
20749
  if (!policy)
@@ -20476,13 +20761,14 @@ class CacheKeepManager2 {
20476
20761
  const plan = mode === "hours" ? policy.hours && { mode, hours: policy.hours } : { mode };
20477
20762
  if (!plan)
20478
20763
  return { action: "stop", reason: "unsupported" };
20479
- const costs = this.costs(target);
20764
+ const costs = this.costs(target, ownReservation);
20480
20765
  if (mode === "auto" && !costs && state.lastRealRequestAt < now - (target.isSubagent ? PLANNED_UNPRICED_SUBAGENT_IDLE_MS : PLANNED_UNPRICED_MAIN_IDLE_MS))
20481
20766
  return { action: "stop", reason: "idle" };
20482
20767
  return decideCacheKeep({
20483
20768
  ...plan,
20484
20769
  now,
20485
20770
  ttlMs: target.ttlMs ?? 0,
20771
+ leadMs: CACHE_KEEP_PREWARM_LEAD_MS,
20486
20772
  lastRealRequestAt: state.lastRealRequestAt,
20487
20773
  lastWarmAt: state.lastWarmAt,
20488
20774
  warmsSinceLastRealRequest: state.warmsSinceLastRealRequest - Number(ownReservation),
@@ -20497,26 +20783,34 @@ class CacheKeepManager2 {
20497
20783
  mode: "always",
20498
20784
  now: state.lastRealRequestAt,
20499
20785
  ttlMs: CACHE_KEEP_TTL_MS,
20786
+ ...state.planned && { leadMs: CACHE_KEEP_PREWARM_LEAD_MS },
20500
20787
  lastRealRequestAt: state.lastRealRequestAt,
20501
20788
  warmsSinceLastRealRequest: state.warmsSinceLastRealRequest
20502
20789
  });
20503
20790
  return result.action === "stop" && result.reason === "count-cap" ? result : undefined;
20504
20791
  }
20505
20792
  async reserveWarmDispatch(target) {
20793
+ const generation = this.schedulerGeneration;
20506
20794
  const current = this.targets.get(target.id);
20507
20795
  if (!current || !this.isCurrentTarget(target))
20508
20796
  throw new CacheKeepWarmRefusal("stopped");
20509
20797
  const state = current.policyState;
20798
+ if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
20799
+ throw new CacheKeepWarmWait;
20510
20800
  const loaded = await this.options.loadStorage();
20801
+ if (generation !== this.schedulerGeneration)
20802
+ throw new CacheKeepWarmWait;
20511
20803
  const storage = loaded && this.options.resolveSettings ? this.targetSettings(this.options.resolveSettings(loaded), target.bodyText) : loaded;
20512
20804
  if (!this.isCurrentTarget(target))
20513
20805
  throw new CacheKeepWarmRefusal("stopped");
20806
+ if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
20807
+ throw new CacheKeepWarmWait;
20514
20808
  const now = this.options.now?.() ?? Date.now();
20515
20809
  const decision = this.policyDecision(current, now) ?? (isCacheKeepAlways(storage) ? this.countDecision(current) : undefined);
20516
20810
  if (decision?.action === "stop")
20517
20811
  throw new CacheKeepWarmRefusal(decision.reason);
20518
20812
  if (decision?.action === "wait")
20519
- throw new CacheKeepWarmRefusal("stopped");
20813
+ throw new CacheKeepWarmWait;
20520
20814
  const admittedCost = this.costs(current)?.nextWarmCost ?? 0;
20521
20815
  const pendingCost = state?.pendingWarmCost;
20522
20816
  if (state) {
@@ -20528,6 +20822,8 @@ class CacheKeepManager2 {
20528
20822
  try {
20529
20823
  committed = await this.options.reserveWarm(current);
20530
20824
  } catch {}
20825
+ if (generation !== this.schedulerGeneration)
20826
+ throw new CacheKeepWarmWait;
20531
20827
  if (!committed && (state?.planned || isCacheKeepAlways(storage))) {
20532
20828
  if (state) {
20533
20829
  state.warmsSinceLastRealRequest--;
@@ -20540,19 +20836,29 @@ class CacheKeepManager2 {
20540
20836
  this.admittedWarmCosts.set(state, admittedCost);
20541
20837
  if (!this.isCurrentTarget(target))
20542
20838
  throw new CacheKeepWarmRefusal("stopped");
20543
- const fresh = this.policyDecision(current, this.options.now?.() ?? Date.now(), true);
20839
+ const fresh = this.realTurnBusy(state?.ownerSessionId ?? target.id) ? { action: "wait", until: 0 } : this.policyDecision(current, this.options.now?.() ?? Date.now(), true);
20544
20840
  if (fresh?.action === "stop")
20545
20841
  throw new CacheKeepWarmRefusal(fresh.reason);
20546
- if (fresh?.action === "wait")
20547
- throw new CacheKeepWarmRefusal("stopped");
20842
+ if (fresh?.action === "wait") {
20843
+ if (state) {
20844
+ state.warmsSinceLastRealRequest--;
20845
+ state.pendingWarmCost = pendingCost;
20846
+ this.admittedWarmCosts.delete(state);
20847
+ await this.options.settleWarm?.(current);
20848
+ }
20849
+ throw new CacheKeepWarmWait;
20850
+ }
20548
20851
  }
20549
20852
  scheduleDueTimer() {
20550
20853
  if (this.dueTimer)
20551
20854
  (this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
20552
20855
  this.dueTimer = null;
20856
+ if (!this.timer)
20857
+ return;
20553
20858
  let due = Infinity;
20554
20859
  for (const target of this.targets.values())
20555
- due = Math.min(due, target.nextPrewarmAt);
20860
+ if (!this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
20861
+ due = Math.min(due, target.nextPrewarmAt);
20556
20862
  if (!Number.isFinite(due))
20557
20863
  return;
20558
20864
  this.dueTimer = (this.options.setTimeoutImpl ?? setTimeout)(() => {
@@ -20587,19 +20893,18 @@ class CacheKeepManager2 {
20587
20893
  if (this.targets.get(target.id) !== target)
20588
20894
  return;
20589
20895
  this.reportStop(target, reason, now);
20590
- if (now < target.cacheExpiresAt)
20591
- logger2[reason === "count-cap" ? "debug" : "warn"]("cachekeep", "stopped warming session", {
20592
- session: target.id,
20593
- reason,
20594
- bodyBytes: target.bodyBytes,
20595
- totalBodyBytes: this.totalBodyBytes(),
20596
- budgetBytes: CACHE_KEEP_MAX_BODY_BYTES,
20597
- targets: this.targets.size,
20598
- maxTargets: CACHE_KEEP_MAX_TARGETS,
20599
- cacheExpiresAt: target.cacheExpiresAt,
20600
- nextPrewarmAt: target.nextPrewarmAt,
20601
- ...details
20602
- });
20896
+ logger2[now >= target.cacheExpiresAt ? "info" : reason === "count-cap" ? "debug" : "warn"]("cachekeep", "stopped warming session", {
20897
+ session: target.id,
20898
+ reason,
20899
+ bodyBytes: target.bodyBytes,
20900
+ totalBodyBytes: this.totalBodyBytes(),
20901
+ budgetBytes: CACHE_KEEP_MAX_BODY_BYTES,
20902
+ targets: this.targets.size,
20903
+ maxTargets: CACHE_KEEP_MAX_TARGETS,
20904
+ cacheExpiresAt: target.cacheExpiresAt,
20905
+ nextPrewarmAt: target.nextPrewarmAt,
20906
+ ...details
20907
+ });
20603
20908
  this.retainStopped(target, stopReason(reason), now);
20604
20909
  this.targets.delete(target.id);
20605
20910
  this.options.onTargetRemoved?.(target.id);
@@ -20612,17 +20917,28 @@ class CacheKeepManager2 {
20612
20917
  warmStopped: { at: now, reason }
20613
20918
  });
20614
20919
  }
20920
+ finishSessionTargets(sessionId, keep) {
20921
+ for (const target of [...this.targets.values()])
20922
+ if (target !== keep && (target.id === sessionId || target.policyState?.ownerSessionId === sessionId))
20923
+ try {
20924
+ this.untrack(target.id);
20925
+ } catch {}
20926
+ }
20615
20927
  reportStop(target, reason, at) {
20928
+ if (this.targets.get(target.id) !== target)
20929
+ return;
20616
20930
  const state = target.policyState;
20617
20931
  if (!target.sourceWarm)
20618
- this.setWarmingRecord(target.id, { stopReason: reportStopReason(reason) });
20619
- if (target.sourceWarm || !state?.hasWarmed || this.reportedStops.has(state))
20932
+ this.setWarmingRecord(target.id, {
20933
+ stopReason: reportStopReason(reason)
20934
+ });
20935
+ if (target.sourceWarm || !state || !state.hasWarmed && !this.restoredTargets.has(target) || this.reportedStops.has(state))
20620
20936
  return;
20621
- if (reportSessionCacheWarmStopped(state.ownerSessionId, {
20937
+ this.reportedStops.add(state);
20938
+ reportSessionCacheWarmStopped(state.ownerSessionId, {
20622
20939
  at,
20623
20940
  reason: reportStopReason(reason)
20624
- }))
20625
- this.reportedStops.add(state);
20941
+ });
20626
20942
  }
20627
20943
  evictOldestTarget(now, reason) {
20628
20944
  const oldest = this.targets.values().next().value;
@@ -20641,7 +20957,16 @@ class CacheKeepManager2 {
20641
20957
  continue;
20642
20958
  }
20643
20959
  if (now >= target.cacheExpiresAt) {
20644
- this.reportStop(target, target.policyState?.planned ? "cost-cap" : "expired", now);
20960
+ const reason = target.policyState?.planned ? "retry-window-ended" : "expired";
20961
+ logger2.info("cachekeep", "stopped warming session", {
20962
+ session: target.id,
20963
+ reason,
20964
+ stage: "prune",
20965
+ cacheExpiresAt: target.cacheExpiresAt,
20966
+ nextPrewarmAt: target.nextPrewarmAt,
20967
+ overdueMs: now - target.cacheExpiresAt
20968
+ });
20969
+ this.reportStop(target, reason, now);
20645
20970
  this.targets.delete(id);
20646
20971
  this.options.onTargetRemoved?.(id);
20647
20972
  }
@@ -20667,10 +20992,10 @@ class CacheKeepManager2 {
20667
20992
  }
20668
20993
  const now = this.options.now?.() ?? Date.now();
20669
20994
  const acceptedAt = input.acceptedAt ?? input.retained?.lastTouchAt ?? now;
20670
- if (input.retained && input.retained.cacheExpiresAt <= now)
20671
- return { tracked: false, reason: "cache expired" };
20672
20995
  let bodyBytes;
20673
20996
  const refuse = (reason, reasonCode) => {
20997
+ if (input.sessionId && !input.retained && !input.sourceWarm)
20998
+ this.finishSessionTargets(input.sessionId);
20674
20999
  if (reasonCode === "body-budget")
20675
21000
  logger2.warn("cachekeep", "tracking skipped", {
20676
21001
  session: input.sessionId ?? null,
@@ -20699,18 +21024,27 @@ class CacheKeepManager2 {
20699
21024
  previous = undefined;
20700
21025
  }
20701
21026
  const ownerSessionId = input.ownerSessionId ?? input.retained?.policyState?.ownerSessionId ?? input.sessionId;
20702
- const policy = readSessionCachePolicy(ownerSessionId, true);
21027
+ const freshPolicy = readSessionCachePolicy(ownerSessionId, true);
21028
+ const restoredPlan = input.retained?.policyState?.planned === true;
21029
+ const policy = freshPolicy ?? (restoredPlan ? input.retained?.policyState?.policy ?? {
21030
+ keep_warm: "auto"
21031
+ } : null);
20703
21032
  const planned = policy?.keep_warm !== undefined;
21033
+ const sessionId = input.sessionId;
20704
21034
  const retire = (reason) => {
20705
21035
  if (previous)
20706
21036
  this.removeTarget(previous, reason, now);
20707
21037
  return refuse(reason, reason);
20708
21038
  };
21039
+ if (input.retained && input.retained.cacheExpiresAt <= now) {
21040
+ return { tracked: false, reason: "cache expired" };
21041
+ }
21042
+ if (restoredPlan && freshPolicy && freshPolicy.keep_warm === undefined)
21043
+ return retire("session-ended");
20709
21044
  if (input.retained && (planned || isCacheKeepAlways(input.storage)) && input.retained.policyState?.needsRealRequest)
20710
21045
  return retire("unsupported");
20711
- if (!policy && (input.retained?.policyState?.planned || previous?.policyState?.planned))
21046
+ if (!input.retained && !policy && previous?.policyState?.planned)
20712
21047
  return retire("session-ended");
20713
- const sessionId = input.sessionId;
20714
21048
  const keptOff = () => {
20715
21049
  if (!previous && !input.sourceWarm)
20716
21050
  this.recordWarmingOff(sessionId);
@@ -20763,6 +21097,7 @@ class CacheKeepManager2 {
20763
21097
  }
20764
21098
  const today = cacheKeepPeriodKey(input.storage, window, new Date(now));
20765
21099
  this.pruneTargets(now, today);
21100
+ previous = this.targets.get(input.sessionId);
20766
21101
  if (this.targets.has(input.sessionId))
20767
21102
  this.targets.delete(input.sessionId);
20768
21103
  this.stoppedSessions.delete(input.sessionId);
@@ -20792,15 +21127,18 @@ class CacheKeepManager2 {
20792
21127
  dayKey: today,
20793
21128
  oauthAccountId: input.oauthAccountId,
20794
21129
  oauthAccountIdentity: input.oauthAccountIdentity,
21130
+ hostMetadata: input.hostMetadata,
20795
21131
  accountStoragePath: input.accountStoragePath,
20796
21132
  isSubagent: input.isSubagent ?? false,
20797
21133
  policyState: input.retained?.policyState ? {
20798
21134
  ...input.retained.policyState,
20799
21135
  warmCostSoFar: input.retained.policyState.warmCostSoFar + (input.retained.policyState.pendingWarmCost ?? 0),
20800
- pendingWarmCost: undefined
21136
+ pendingWarmCost: undefined,
21137
+ ...policy && { policy: structuredClone(policy) }
20801
21138
  } : {
20802
21139
  ownerSessionId,
20803
21140
  planned,
21141
+ ...policy && { policy: structuredClone(policy) },
20804
21142
  lastRealRequestAt: acceptedAt,
20805
21143
  warmsSinceLastRealRequest: 0,
20806
21144
  warmCostSoFar: 0,
@@ -20808,11 +21146,23 @@ class CacheKeepManager2 {
20808
21146
  },
20809
21147
  ...input.sourceWarm === true && { sourceWarm: true }
20810
21148
  });
20811
- this.pruneTargets(now, today);
20812
- this.publishTrackedSessions();
20813
21149
  const target = this.targets.get(input.sessionId);
20814
21150
  if (!target)
20815
21151
  return { tracked: false, reason: "evicted by cachekeep limits" };
21152
+ if (input.retained) {
21153
+ this.restoredTargets.add(target);
21154
+ if (restoredPlan && !freshPolicy && target.policyState) {
21155
+ this.restoringPolicies.add(target.policyState);
21156
+ if (!input.retained.policyState?.policy)
21157
+ logger2.info("cachekeep", "restored legacy planned policy as auto", {
21158
+ session: target.id
21159
+ });
21160
+ }
21161
+ }
21162
+ this.pruneTargets(now, today);
21163
+ this.publishTrackedSessions();
21164
+ if (this.targets.get(input.sessionId) !== target)
21165
+ return { tracked: false, reason: "evicted by cachekeep limits" };
20816
21166
  if (input.acceptedUsage)
20817
21167
  updateAcceptedUsage(target, input.bodyText, input.acceptedUsage);
20818
21168
  if (planned) {
@@ -20859,15 +21209,12 @@ class CacheKeepManager2 {
20859
21209
  if (!current)
20860
21210
  this.immediateTargets.set(target.id, target);
20861
21211
  try {
20862
- let acceptedAt;
20863
- const result = await this.sendPrewarm(target, (receivedAt) => {
20864
- acceptedAt = receivedAt;
21212
+ return await this.sendPrewarm(target, (receivedAt, result) => {
21213
+ if (current && this.isCurrentTarget(target)) {
21214
+ this.acceptWarm(current, result, receivedAt);
21215
+ this.scheduleDueTimer();
21216
+ }
20865
21217
  });
20866
- if (result.ok && current && this.isCurrentTarget(target)) {
20867
- this.acceptWarm(current, result, acceptedAt ?? this.options.now?.() ?? Date.now());
20868
- this.scheduleDueTimer();
20869
- }
20870
- return result;
20871
21218
  } finally {
20872
21219
  if (this.immediateTargets.get(target.id) === target)
20873
21220
  this.immediateTargets.delete(target.id);
@@ -20876,17 +21223,25 @@ class CacheKeepManager2 {
20876
21223
  tick() {
20877
21224
  if (this.tickPromise)
20878
21225
  return this.tickPromise;
21226
+ const lifetime = this.lifetime;
21227
+ const generation = this.schedulerGeneration;
20879
21228
  let run;
20880
- run = this.runTick().finally(() => {
21229
+ run = this.runTick(lifetime).finally(() => {
21230
+ this.ticks.delete(run);
20881
21231
  if (this.tickPromise === run)
20882
21232
  this.tickPromise = null;
20883
- this.scheduleDueTimer();
21233
+ if (lifetime === this.lifetime && generation === this.schedulerGeneration)
21234
+ this.scheduleDueTimer();
20884
21235
  });
20885
21236
  this.tickPromise = run;
21237
+ this.ticks.add(run);
20886
21238
  return run;
20887
21239
  }
20888
- async runTick() {
21240
+ async runTick(lifetime) {
21241
+ const generation = this.schedulerGeneration;
20889
21242
  const loaded = await this.options.loadStorage();
21243
+ if (lifetime !== this.lifetime || generation !== this.schedulerGeneration)
21244
+ return;
20890
21245
  const storage = loaded && this.options.resolveSettings ? this.options.resolveSettings(loaded) : loaded;
20891
21246
  const window = getCacheKeepWindow(storage);
20892
21247
  const now = this.options.now?.() ?? Date.now();
@@ -20904,49 +21259,58 @@ class CacheKeepManager2 {
20904
21259
  }
20905
21260
  logger2.debug("cachekeep", "fired", { targets: this.targets.size });
20906
21261
  const targets = [...this.targets.values()].sort((a, b) => this.lastPrewarmStart(a) - this.lastPrewarmStart(b));
20907
- for (const target of targets) {
21262
+ const warm = async (target) => {
21263
+ if (generation !== this.schedulerGeneration)
21264
+ return;
20908
21265
  if (this.targets.get(target.id) !== target)
20909
- continue;
21266
+ return;
21267
+ if (this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
21268
+ return;
20910
21269
  const attemptAt = this.options.now?.() ?? Date.now();
20911
21270
  const decision = this.policyDecision(target, attemptAt);
20912
21271
  if (decision?.action === "stop") {
20913
21272
  this.removeTarget(target, decision.reason, attemptAt);
20914
- continue;
21273
+ return;
20915
21274
  }
20916
21275
  if (decision?.action === "wait") {
20917
21276
  target.nextPrewarmAt = Math.max(target.nextPrewarmAt, decision.until);
20918
- continue;
21277
+ return;
20919
21278
  }
20920
21279
  if (!target.policyState?.planned) {
20921
21280
  const targetStorage = storage ? this.targetSettings(storage, target.bodyText) : storage;
20922
21281
  if (!isCacheKeepHybridActive(targetStorage)) {
20923
21282
  this.removeTarget(target, "cachekeep-hybrid-inactive", attemptAt);
20924
- continue;
21283
+ return;
20925
21284
  }
20926
21285
  const targetToday = cacheKeepPeriodKey(targetStorage, window, new Date(attemptAt));
20927
21286
  if (isCacheKeepAlways(targetStorage))
20928
21287
  target.dayKey = "always";
20929
21288
  if (!isCacheKeepActiveNow(targetStorage, new Date(attemptAt)) || target.dayKey !== targetToday) {
20930
21289
  this.removeTarget(target, "schedule-period-ended", attemptAt);
20931
- continue;
21290
+ return;
20932
21291
  }
20933
21292
  if (isCacheKeepAlways(targetStorage)) {
20934
21293
  const count2 = this.countDecision(target);
20935
21294
  if (count2?.action === "stop") {
20936
21295
  this.removeTarget(target, count2.reason, attemptAt);
20937
- continue;
21296
+ return;
20938
21297
  }
20939
21298
  }
20940
21299
  }
20941
21300
  if (target.nextPrewarmAt > attemptAt)
20942
- continue;
21301
+ return;
20943
21302
  if (attemptAt > this.lastPrewarmStart(target)) {
20944
- this.removeTarget(target, target.policyState?.planned ? "cost-cap" : "retry-window-ended", attemptAt);
20945
- continue;
21303
+ this.removeTarget(target, "retry-window-ended", attemptAt, {
21304
+ stage: "dispatch",
21305
+ overdueMs: attemptAt - this.lastPrewarmStart(target)
21306
+ });
21307
+ return;
20946
21308
  }
20947
21309
  try {
20948
21310
  await this.prewarm(target, attemptAt);
20949
21311
  } catch (error) {
21312
+ if (generation !== this.schedulerGeneration)
21313
+ return;
20950
21314
  logger2.warn("cachekeep", "prewarm failed", {
20951
21315
  session: target.id,
20952
21316
  ...classifyCacheKeepFailure(error, "send"),
@@ -20955,11 +21319,20 @@ class CacheKeepManager2 {
20955
21319
  });
20956
21320
  this.scheduleRetry(target, true);
20957
21321
  } finally {
20958
- if (this.targets.get(target.id) === target)
21322
+ if (generation === this.schedulerGeneration && this.targets.get(target.id) === target)
20959
21323
  this.options.onTargetChanged?.(target);
20960
21324
  }
20961
- }
20962
- this.publishTrackedSessions();
21325
+ };
21326
+ let index = 0;
21327
+ await Promise.all(Array.from({ length: Math.min(4, targets.length) }, async () => {
21328
+ while (index < targets.length) {
21329
+ const target = targets[index++];
21330
+ if (target)
21331
+ await warm(target);
21332
+ }
21333
+ }));
21334
+ if (lifetime === this.lifetime && generation === this.schedulerGeneration)
21335
+ this.publishTrackedSessions();
20963
21336
  }
20964
21337
  targetSettings(storage, bodyText) {
20965
21338
  if (!this.options.resolveSettings)
@@ -20984,22 +21357,90 @@ class CacheKeepManager2 {
20984
21357
  const now = this.options.now?.() ?? Date.now();
20985
21358
  const deadline = this.lastPrewarmStart(target);
20986
21359
  if (now >= deadline) {
20987
- this.removeTarget(target, target.policyState?.planned ? "cost-cap" : "retry-window-ended", now);
21360
+ this.removeTarget(target, "retry-window-ended", now, {
21361
+ stage: "retry",
21362
+ overdueMs: now - deadline
21363
+ });
20988
21364
  return;
20989
21365
  }
20990
21366
  target.consecutiveFailures += 1;
20991
21367
  const backoff = cacheKeepRetryDelayMs(target.id, target.consecutiveFailures);
20992
- const delay3 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
20993
- target.nextPrewarmAt = Math.min(now + delay3, deadline);
21368
+ const delay4 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
21369
+ target.nextPrewarmAt = Math.min(now + delay4, deadline);
20994
21370
  }
20995
21371
  async sendPrewarm(target, onAccepted) {
21372
+ const generation = this.schedulerGeneration;
21373
+ const session = target.policyState?.ownerSessionId ?? target.id;
21374
+ if (this.realTurnBusy(session))
21375
+ return { ok: false, skipped: true, reason: "real-turn-in-flight" };
21376
+ let queued = false;
21377
+ while (this.sessionWarms.has(session)) {
21378
+ queued = true;
21379
+ await this.sessionWarms.get(session);
21380
+ if (generation !== this.schedulerGeneration)
21381
+ return { ok: false, skipped: true, reason: "scheduler-paused" };
21382
+ }
21383
+ if (!this.isCurrentTarget(target))
21384
+ return { ok: false, skipped: true, reason: "target-replaced" };
21385
+ if (this.realTurnBusy(session))
21386
+ return { ok: false, skipped: true, reason: "real-turn-in-flight" };
21387
+ const current = this.targets.get(target.id);
21388
+ if (queued && current && current.nextPrewarmAt > (this.options.now?.() ?? Date.now()))
21389
+ return { ok: false, skipped: true, reason: "already-warmed" };
21390
+ let acceptedAt;
21391
+ const sending = this.sendPrewarmAttempt(target, (receivedAt) => {
21392
+ acceptedAt = receivedAt;
21393
+ }).then((result) => {
21394
+ if (generation !== this.schedulerGeneration)
21395
+ return {
21396
+ ok: false,
21397
+ skipped: true,
21398
+ reason: "scheduler-paused"
21399
+ };
21400
+ if (result.ok && this.realTurnBusy(session))
21401
+ return {
21402
+ ok: false,
21403
+ skipped: true,
21404
+ reason: "real-turn-in-flight"
21405
+ };
21406
+ if (result.ok)
21407
+ onAccepted?.(acceptedAt ?? this.options.now?.() ?? Date.now(), result);
21408
+ return result;
21409
+ });
21410
+ this.sessionWarms.set(session, sending);
21411
+ this.warmRuns.add(sending);
21412
+ try {
21413
+ return await sending;
21414
+ } finally {
21415
+ this.warmRuns.delete(sending);
21416
+ if (this.sessionWarms.get(session) === sending)
21417
+ this.sessionWarms.delete(session);
21418
+ }
21419
+ }
21420
+ async sendPrewarmAttempt(target, onAccepted) {
21421
+ const generation = this.schedulerGeneration;
20996
21422
  const remaining = target.cacheExpiresAt - (this.options.now?.() ?? Date.now()) - CACHE_KEEP_EXPIRY_SAFETY_MS;
20997
21423
  const timeout = Math.min(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS, target.policyState?.planned || target.sourceWarm ? remaining : Infinity);
20998
21424
  if (timeout <= 0)
20999
- return { ok: false, refused: true, reason: "cost-cap" };
21425
+ return { ok: false, refused: true, reason: "retry-window-ended" };
21426
+ const startedAt = this.options.now?.() ?? Date.now();
21427
+ const controller = new AbortController;
21428
+ this.warmControllers.set(controller, target.policyState?.ownerSessionId ?? target.id);
21429
+ let headersMs = null;
21000
21430
  const attempt = {
21001
21431
  id: ++this.nextPrewarmAttemptId,
21002
- signal: AbortSignal.timeout(timeout)
21432
+ signal: AbortSignal.any([
21433
+ AbortSignal.timeout(timeout),
21434
+ controller.signal
21435
+ ]),
21436
+ onResponseHeaders: () => {
21437
+ headersMs ??= (this.options.now?.() ?? Date.now()) - startedAt;
21438
+ }
21439
+ };
21440
+ const ensureActive = () => {
21441
+ if (generation !== this.schedulerGeneration || controller.signal.aborted)
21442
+ throw new CacheKeepWarmWait;
21443
+ attempt.signal.throwIfAborted();
21003
21444
  };
21004
21445
  let stage = "authorization";
21005
21446
  let responseStatus;
@@ -21024,21 +21465,25 @@ class CacheKeepManager2 {
21024
21465
  throw new CacheKeepWarmRefusal("routing-moved");
21025
21466
  };
21026
21467
  try {
21468
+ ensureActive();
21027
21469
  checkRouting();
21028
21470
  let bodyText = target.bodyText;
21029
21471
  if (this.options.prepareBody) {
21030
21472
  try {
21031
21473
  bodyText = await this.options.prepareBody(bodyText, target);
21032
21474
  } catch {
21475
+ ensureActive();
21033
21476
  logger2.warn("cachekeep", "prepare body failed", {
21034
21477
  session: target.id
21035
21478
  });
21036
21479
  }
21480
+ ensureActive();
21037
21481
  }
21038
21482
  const preparedTarget = { ...target, bodyText };
21039
21483
  const prewarm = await buildCacheKeepPrewarmBody(bodyText, {
21040
21484
  stripServerFallback: target.sourceWarm === true
21041
21485
  });
21486
+ ensureActive();
21042
21487
  if (!prewarm.ok)
21043
21488
  return prewarm;
21044
21489
  if (this.options.validatePrewarm) {
@@ -21051,6 +21496,7 @@ class CacheKeepManager2 {
21051
21496
  } catch {
21052
21497
  verdict = undefined;
21053
21498
  }
21499
+ ensureActive();
21054
21500
  if (!verdict?.ok) {
21055
21501
  return {
21056
21502
  ok: false,
@@ -21061,7 +21507,9 @@ class CacheKeepManager2 {
21061
21507
  }
21062
21508
  const fetchImpl = this.options.fetchForTarget?.(target) ?? this.options.fetchImpl ?? fetch;
21063
21509
  const prewarmTarget = { ...preparedTarget, bodyText: prewarm.bodyText };
21510
+ ensureActive();
21064
21511
  let headers = this.options.prepareHeaders ? await this.options.prepareHeaders(new Headers(target.headers), prewarmTarget, attempt) : new Headers(target.headers);
21512
+ ensureActive();
21065
21513
  if (!headers) {
21066
21514
  const summary2 = summarizePrewarmProviderError({
21067
21515
  failure: "credential_unavailable"
@@ -21079,6 +21527,7 @@ class CacheKeepManager2 {
21079
21527
  stage = "send";
21080
21528
  let response;
21081
21529
  const send = async (attemptHeaders) => {
21530
+ ensureActive();
21082
21531
  if (!this.isCurrentTarget(target))
21083
21532
  throw new CacheKeepWarmRefusal("stopped");
21084
21533
  checkRouting();
@@ -21086,30 +21535,41 @@ class CacheKeepManager2 {
21086
21535
  if (!this.options.deferWarmReservation)
21087
21536
  await this.reserveWarmDispatch(target);
21088
21537
  }
21089
- attempt.signal.throwIfAborted();
21538
+ ensureActive();
21090
21539
  const scope = createProviderErrorResponseScope(cacheKeepSentCredentials(attemptHeaders), "http");
21091
21540
  try {
21092
- const dispatch = () => fetchImpl(target.url, {
21093
- method: "POST",
21094
- headers: attemptHeaders,
21095
- body: prewarm.bodyText,
21096
- signal: attempt.signal
21097
- });
21541
+ const dispatch = () => {
21542
+ ensureActive();
21543
+ return fetchImpl(target.url, {
21544
+ method: "POST",
21545
+ headers: attemptHeaders,
21546
+ body: prewarm.bodyText,
21547
+ signal: attempt.signal
21548
+ });
21549
+ };
21098
21550
  let billing;
21099
21551
  try {
21100
21552
  billing = this.options.billingRequest?.(prewarmTarget, attempt);
21101
21553
  } catch {}
21102
21554
  const sent = await (billing ? withAnthropicBilling(billing, dispatch) : dispatch());
21555
+ try {
21556
+ ensureActive();
21557
+ } catch (error) {
21558
+ await sent.body?.cancel().catch(() => {});
21559
+ throw error;
21560
+ }
21561
+ headersMs ??= (this.options.now?.() ?? Date.now()) - startedAt;
21103
21562
  if (!sent.ok && this.isCurrentTarget(target) && target.policyState) {
21104
21563
  const state = target.policyState;
21105
21564
  const cost = this.admittedWarmCosts.get(state) ?? 0;
21106
21565
  target.policyState.pendingWarmCost = Math.max(0, (target.policyState.pendingWarmCost ?? 0) - cost) || undefined;
21107
21566
  this.admittedWarmCosts.delete(state);
21108
21567
  await this.options.settleWarm?.(target);
21568
+ ensureActive();
21109
21569
  }
21110
21570
  return scope.redactResponse(sent);
21111
21571
  } catch (error) {
21112
- if (error instanceof CacheKeepWarmRefusal || nativeAccountRefusal(error)) {
21572
+ if (error instanceof CacheKeepWarmRefusal || isCacheKeepWarmWait(error) || nativeAccountRefusal(error)) {
21113
21573
  scope.dispose();
21114
21574
  throw error;
21115
21575
  }
@@ -21118,6 +21578,7 @@ class CacheKeepManager2 {
21118
21578
  }
21119
21579
  };
21120
21580
  response = await send(headers);
21581
+ ensureActive();
21121
21582
  if (response.status === 401 && !attempt.signal?.aborted && this.options.retryOnUnauthorized) {
21122
21583
  let rotatedHeaders;
21123
21584
  try {
@@ -21128,28 +21589,34 @@ class CacheKeepManager2 {
21128
21589
  attempt
21129
21590
  });
21130
21591
  } catch (error) {
21592
+ ensureActive();
21131
21593
  if (error instanceof NativeAccountRefusal) {
21132
21594
  await response.body?.cancel().catch(() => {});
21595
+ ensureActive();
21133
21596
  throw error;
21134
21597
  }
21135
21598
  }
21599
+ ensureActive();
21136
21600
  if (rotatedHeaders && !attempt.signal?.aborted) {
21137
21601
  rotatedHeaders.delete("content-length");
21138
21602
  rotatedHeaders.delete("transfer-encoding");
21139
21603
  await response.body?.cancel().catch(() => {});
21604
+ ensureActive();
21140
21605
  headers = rotatedHeaders;
21141
21606
  response = await send(headers);
21607
+ ensureActive();
21142
21608
  }
21143
21609
  }
21144
21610
  stage = "response";
21145
21611
  responseStatus = response.status;
21146
21612
  const receivedAt = this.options.now?.() ?? Date.now();
21147
21613
  const raw = await response.text();
21148
- attempt.signal.throwIfAborted();
21614
+ ensureActive();
21149
21615
  let data = null;
21150
21616
  try {
21151
21617
  data = raw ? JSON.parse(raw) : null;
21152
21618
  } catch {}
21619
+ ensureActive();
21153
21620
  const summary = response.ok ? undefined : summarizePrewarmProviderError({ status: response.status, body: raw });
21154
21621
  try {
21155
21622
  await this.options.onResponse?.({
@@ -21161,6 +21628,7 @@ class CacheKeepManager2 {
21161
21628
  attempt
21162
21629
  });
21163
21630
  } catch {}
21631
+ ensureActive();
21164
21632
  try {
21165
21633
  const dumpHandle = await dumpDirectRequest({
21166
21634
  affinity: target.id,
@@ -21172,14 +21640,17 @@ class CacheKeepManager2 {
21172
21640
  headers,
21173
21641
  tag: "cachekeep"
21174
21642
  });
21643
+ ensureActive();
21175
21644
  await dumpResponseArtifact(dumpHandle, {
21176
21645
  status: response.status,
21177
21646
  message: data,
21178
21647
  ...summary && { provider_error: summary.provider_error }
21179
21648
  });
21180
21649
  } catch {
21650
+ ensureActive();
21181
21651
  logger2.debug("cachekeep", "dump failed", { session: target.id });
21182
21652
  }
21653
+ ensureActive();
21183
21654
  if (summary) {
21184
21655
  return {
21185
21656
  ok: false,
@@ -21197,6 +21668,10 @@ class CacheKeepManager2 {
21197
21668
  ...usage && { usage }
21198
21669
  };
21199
21670
  } catch (error) {
21671
+ if (controller.signal.aborted || generation !== this.schedulerGeneration)
21672
+ return { ok: false, skipped: true, reason: "warm-cancelled" };
21673
+ if (isCacheKeepWarmWait(error))
21674
+ return { ok: false, skipped: true, reason: "wait" };
21200
21675
  if (error instanceof CacheKeepWarmRefusal)
21201
21676
  return { ok: false, refused: true, reason: error.reason };
21202
21677
  const failure = classifyCacheKeepFailure(error, stage, responseStatus);
@@ -21217,17 +21692,31 @@ class CacheKeepManager2 {
21217
21692
  transient: true
21218
21693
  };
21219
21694
  } finally {
21695
+ this.warmControllers.delete(controller);
21696
+ try {
21697
+ logger2.info("cachekeep", "prewarm timing", {
21698
+ session: target.id,
21699
+ stage,
21700
+ headersMs,
21701
+ totalMs: (this.options.now?.() ?? Date.now()) - startedAt
21702
+ });
21703
+ } catch {}
21220
21704
  try {
21221
21705
  await this.options.onComplete?.({ target, attempt });
21222
21706
  } catch {}
21223
21707
  }
21224
21708
  }
21225
21709
  async prewarm(target, now) {
21226
- let acceptedAt;
21227
- const result = await this.sendPrewarm(target, (receivedAt) => {
21228
- acceptedAt = receivedAt;
21710
+ const generation = this.schedulerGeneration;
21711
+ const result = await this.sendPrewarm(target, (receivedAt, accepted) => {
21712
+ if (this.targets.get(target.id) === target)
21713
+ this.acceptWarm(target, accepted, receivedAt);
21229
21714
  });
21715
+ if (generation !== this.schedulerGeneration)
21716
+ return;
21230
21717
  if (!result.ok) {
21718
+ if (result.refused !== true && result.skipped)
21719
+ return;
21231
21720
  if (result.refused === true) {
21232
21721
  this.removeTarget(target, result.reason, now, {
21233
21722
  detail: "prewarm refused before send"
@@ -21256,10 +21745,6 @@ class CacheKeepManager2 {
21256
21745
  }
21257
21746
  return;
21258
21747
  }
21259
- if (this.targets.get(target.id) !== target)
21260
- return;
21261
- acceptedAt ??= this.options.now?.() ?? Date.now();
21262
- this.acceptWarm(target, result, acceptedAt);
21263
21748
  }
21264
21749
  acceptWarm(target, result, acceptedAt) {
21265
21750
  const state = target.policyState;
@@ -21301,7 +21786,7 @@ import {
21301
21786
  mkdir as mkdir12,
21302
21787
  readdir as readdir5,
21303
21788
  readFile as readFile15,
21304
- rename as rename13,
21789
+ rename as rename14,
21305
21790
  rm as rm7,
21306
21791
  writeFile as writeFile4
21307
21792
  } from "node:fs/promises";
@@ -21318,8 +21803,8 @@ import { uptime } from "node:os";
21318
21803
  import { basename as basename13, dirname as dirname20, join as join25 } from "node:path";
21319
21804
 
21320
21805
  // src/native-lock-observer.ts
21321
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
21322
- var detachedLocks = new AsyncLocalStorage3;
21806
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
21807
+ var detachedLocks = new AsyncLocalStorage4;
21323
21808
  function withDetachedNativeLocks(work) {
21324
21809
  return detachedLocks.run(true, work);
21325
21810
  }
@@ -21367,7 +21852,7 @@ import { basename as basename11, dirname as dirname17, join as join21 } from "no
21367
21852
 
21368
21853
  // src/sticky-routing.ts
21369
21854
  import { createHash as createHash17, randomUUID as randomUUID15 } from "node:crypto";
21370
- import { mkdir as mkdir10, readFile as readFile11, rename as rename12, rm as rm6, stat as stat12, writeFile as writeFile3 } from "node:fs/promises";
21855
+ import { mkdir as mkdir10, readFile as readFile11, rename as rename13, rm as rm6, stat as stat12, writeFile as writeFile3 } from "node:fs/promises";
21371
21856
  import { basename as basename10, dirname as dirname16, join as join20 } from "node:path";
21372
21857
 
21373
21858
  // src/native-vault-seed.ts
@@ -21448,9 +21933,9 @@ function recordIdentityIn(tx, id, identity4) {
21448
21933
  return disableIdentityDuplicates(tx, identity4);
21449
21934
  }
21450
21935
  // ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
21451
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
21452
- var insideHook = new AsyncLocalStorage4;
21453
- var insideCodec = new AsyncLocalStorage4;
21936
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
21937
+ var insideHook = new AsyncLocalStorage5;
21938
+ var insideCodec = new AsyncLocalStorage5;
21454
21939
  function assertNotInsideHook(operation) {
21455
21940
  if (insideHook.getStore() !== undefined)
21456
21941
  throw new PoolReentryError(operation);
@@ -24152,11 +24637,11 @@ class PoolQuotaWriter {
24152
24637
  overlay(rows) {
24153
24638
  return rows.map((row) => this.overlayRow(row));
24154
24639
  }
24155
- schedule(delay3) {
24640
+ schedule(delay4) {
24156
24641
  if (this.running || this.timer || !this.pending.size || this.stopped)
24157
24642
  return;
24158
24643
  const remaining = this.closed ? 0 : (this.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - this.clock.now();
24159
- this.timer = this.clock.schedule(Math.max(delay3, remaining), () => {
24644
+ this.timer = this.clock.schedule(Math.max(delay4, remaining), () => {
24160
24645
  this.timer = undefined;
24161
24646
  return this.flush();
24162
24647
  });
@@ -24254,8 +24739,8 @@ class PoolQuotaWriter {
24254
24739
  this.running = undefined;
24255
24740
  for (const wake of this.wake)
24256
24741
  wake();
24257
- const delay3 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24258
- this.schedule(delay3);
24742
+ const delay4 = this.failures ? Math.min(5000, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
24743
+ this.schedule(delay4);
24259
24744
  }
24260
24745
  })();
24261
24746
  return this.running;
@@ -25251,7 +25736,7 @@ var nativeQuotaCodec = {
25251
25736
  // src/native-runtime.ts
25252
25737
  import { randomUUID as randomUUID14 } from "node:crypto";
25253
25738
  import { constants as constants2 } from "node:fs";
25254
- import { lstat as lstat8, mkdir as mkdir9, open as open9, rename as rename11, rm as rm5 } from "node:fs/promises";
25739
+ import { lstat as lstat8, mkdir as mkdir9, open as open9, rename as rename12, rm as rm5 } from "node:fs/promises";
25255
25740
  import { basename as basename9, dirname as dirname15, isAbsolute as isAbsolute4, join as join19 } from "node:path";
25256
25741
  import { types as utilTypes5 } from "node:util";
25257
25742
 
@@ -25427,7 +25912,7 @@ function openNativePoolStore(options) {
25427
25912
  }
25428
25913
 
25429
25914
  // src/publication-rename.ts
25430
- import { rename as rename10 } from "node:fs/promises";
25915
+ import { rename as rename11 } from "node:fs/promises";
25431
25916
  import { types as utilTypes4 } from "node:util";
25432
25917
  function capturePublicationOptions(options = {}) {
25433
25918
  return {
@@ -25450,7 +25935,7 @@ function sharingViolation(error) {
25450
25935
  return fields2.win32Code !== undefined ? fields2.win32Code === 32 || fields2.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(fields2.code) && !fields2.reason;
25451
25936
  }
25452
25937
  async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry) {
25453
- const move = options.rename ?? rename10;
25938
+ const move = options.rename ?? rename11;
25454
25939
  if ((options.platform ?? process.platform) !== "win32") {
25455
25940
  await move(from, to);
25456
25941
  return "published";
@@ -25467,11 +25952,11 @@ async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry
25467
25952
  throw error;
25468
25953
  original = error;
25469
25954
  }
25470
- for (const delay3 of [10, 20, 40, 80, 100]) {
25955
+ for (const delay4 of [10, 20, 40, 80, 100]) {
25471
25956
  const remaining = 500 - (now() - start);
25472
25957
  if (remaining <= 0)
25473
25958
  break;
25474
- await sleep(Math.min(delay3, remaining));
25959
+ await sleep(Math.min(delay4, remaining));
25475
25960
  if (now() - start >= 500)
25476
25961
  break;
25477
25962
  if (await beforeRetry?.() === "skip")
@@ -27663,7 +28148,7 @@ async function writeNativeRuntimeOutcome(path2, storageId, change, hooks, firstI
27663
28148
  } catch {
27664
28149
  throw new NativeRuntimeError("publication-refused");
27665
28150
  }
27666
- return (publication2.rename ?? rename11)(from, to);
28151
+ return (publication2.rename ?? rename12)(from, to);
27667
28152
  };
27668
28153
  try {
27669
28154
  await mkdir9(dirname15(path2), { recursive: true, mode: 448 });
@@ -29437,7 +29922,7 @@ class StickySessionRouter {
29437
29922
  await writeFile3(tempPath, `${JSON.stringify(state)}
29438
29923
  `, { mode: 384 });
29439
29924
  await beforeRename();
29440
- await rename12(tempPath, this.options.path);
29925
+ await rename13(tempPath, this.options.path);
29441
29926
  } finally {
29442
29927
  await rm6(tempPath, { force: true }).catch(() => {});
29443
29928
  }
@@ -31270,7 +31755,7 @@ class CacheKeepSessionRegistry {
31270
31755
  }
31271
31756
  const sweptPath = `${recordPath}.${randomUUID18()}.sweep`;
31272
31757
  try {
31273
- await rename13(recordPath, sweptPath);
31758
+ await rename14(recordPath, sweptPath);
31274
31759
  } catch {
31275
31760
  return;
31276
31761
  }
@@ -31359,6 +31844,7 @@ function record12(target, pluginVersion) {
31359
31844
  policyState: {
31360
31845
  ownerSessionId: target.policyState.ownerSessionId,
31361
31846
  planned: target.policyState.planned,
31847
+ policy: target.policyState.policy,
31362
31848
  lastRealRequestAt: target.policyState.lastRealRequestAt,
31363
31849
  lastWarmAt: target.policyState.lastWarmAt,
31364
31850
  warmsSinceLastRealRequest: target.policyState.warmsSinceLastRealRequest,
@@ -31392,13 +31878,39 @@ function invalidReason(value, name, now) {
31392
31878
  return "format";
31393
31879
  if (typeof value.id !== "string" || !value.id || `${hash3(value.id)}.json.gz` !== name || typeof value.bodyText !== "string" || Buffer.byteLength(value.bodyText) > CACHE_KEEP_MAX_BODY_BYTES || typeof value.url !== "string" || typeof value.oauthAccountIdentity !== "string" || !value.oauthAccountIdentity || typeof value.isSubagent !== "boolean" || !Number.isFinite(value.cacheExpiresAt) || !Number.isFinite(value.nextPrewarmAt))
31394
31880
  return "invalid";
31395
- if (value.cacheExpiresAt <= now)
31396
- return "expired";
31397
31881
  const state = value.policyState;
31398
31882
  if (state !== undefined && (!state || typeof state !== "object" || Array.isArray(state) || typeof state.ownerSessionId !== "string" || !state.ownerSessionId || typeof state.planned !== "boolean" || typeof state.hasWarmed !== "boolean" || state.needsRealRequest !== undefined && typeof state.needsRealRequest !== "boolean" || !Number.isFinite(state.lastRealRequestAt) || state.lastRealRequestAt > now || state.lastWarmAt !== undefined && (!Number.isFinite(state.lastWarmAt) || state.lastWarmAt > now) || !Number.isSafeInteger(state.warmsSinceLastRealRequest) || state.warmsSinceLastRealRequest < 0 || !Number.isFinite(state.warmCostSoFar) || state.warmCostSoFar < 0 || state.pendingWarmCost !== undefined && (!Number.isFinite(state.pendingWarmCost) || state.pendingWarmCost < 0) || [state.prefixTokens, state.inputTokens].some((tokens) => tokens !== undefined && (!Number.isFinite(tokens) || tokens < 0))))
31399
31883
  return "invalid";
31884
+ if (state?.policy !== undefined && !validSavedPolicy(state.policy))
31885
+ return "invalid";
31400
31886
  if (sanitizedBody(value.bodyText) !== value.bodyText)
31401
31887
  return "invalid";
31888
+ if (value.cacheExpiresAt <= now)
31889
+ return "expired";
31890
+ }
31891
+ function validSavedPolicy(value) {
31892
+ if (!value || typeof value !== "object" || Array.isArray(value))
31893
+ return false;
31894
+ const policy = value;
31895
+ if (policy.ttl !== undefined && !["none", "short", "long"].includes(String(policy.ttl)))
31896
+ return false;
31897
+ if (policy.keep_warm !== undefined && !["off", "auto", "always", "hours"].includes(String(policy.keep_warm)))
31898
+ return false;
31899
+ if (policy.keep_warm !== "hours")
31900
+ return policy.hours === undefined;
31901
+ const hours = policy.hours;
31902
+ if (!hours || typeof hours !== "object" || Array.isArray(hours))
31903
+ return false;
31904
+ if (![hours.from, hours.to].every((time4) => typeof time4 === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(time4)))
31905
+ return false;
31906
+ if (typeof hours.tz !== "string" || !hours.tz)
31907
+ return false;
31908
+ try {
31909
+ new Intl.DateTimeFormat("en-GB", { timeZone: hours.tz });
31910
+ return true;
31911
+ } catch {
31912
+ return false;
31913
+ }
31402
31914
  }
31403
31915
 
31404
31916
  class CacheKeepStore {
@@ -31469,7 +31981,7 @@ class CacheKeepStore {
31469
31981
  await action();
31470
31982
  }).catch(() => this.writeFailed());
31471
31983
  }
31472
- async load(now, accept, claim) {
31984
+ async load(now, accept, claim, guard) {
31473
31985
  await this.chain;
31474
31986
  if (!await this.directoryReady())
31475
31987
  return;
@@ -31498,7 +32010,17 @@ class CacheKeepStore {
31498
32010
  continue;
31499
32011
  const path2 = join27(directory, name);
31500
32012
  let reason = "unreadable";
32013
+ let entry2;
32014
+ const permitted = async () => {
32015
+ try {
32016
+ return (!guard || await guard(name.slice(0, 64))) && (!release2?.canRemove || await release2.canRemove());
32017
+ } catch {
32018
+ return false;
32019
+ }
32020
+ };
31501
32021
  try {
32022
+ if (!await permitted())
32023
+ continue;
31502
32024
  if (TEMP.test(name)) {
31503
32025
  reason = "unfinished-write";
31504
32026
  throw new Error("Unfinished write");
@@ -31521,9 +32043,16 @@ class CacheKeepStore {
31521
32043
  maxOutputLength: MAX_RECORD_BYTES
31522
32044
  });
31523
32045
  reason = "invalid";
31524
- const entry2 = JSON.parse(raw.toString("utf8"));
32046
+ entry2 = JSON.parse(raw.toString("utf8"));
31525
32047
  const invalid3 = invalidReason(entry2, name, now);
31526
- const accepted = invalid3 ?? accept(entry2);
32048
+ if (invalid3 && invalid3 !== "expired") {
32049
+ reason = invalid3;
32050
+ throw new Error("Invalid restart file");
32051
+ }
32052
+ const acceptance = accept(entry2);
32053
+ if (acceptance === undefined)
32054
+ continue;
32055
+ const accepted = invalid3 ?? acceptance;
31527
32056
  if (accepted !== true && accepted !== undefined) {
31528
32057
  reason = accepted || "invalid";
31529
32058
  throw new Error("Stale restart file");
@@ -31531,7 +32060,10 @@ class CacheKeepStore {
31531
32060
  if (accepted === true) {
31532
32061
  if (directory !== this.directory) {
31533
32062
  try {
31534
- await this.writeEntry(entry2);
32063
+ const adopted = entry2;
32064
+ const migrating = this.chain.then(() => this.writeEntry(adopted));
32065
+ this.chain = migrating.catch(() => this.writeFailed());
32066
+ await migrating;
31535
32067
  } catch {
31536
32068
  this.refuse();
31537
32069
  return;
@@ -31541,12 +32073,17 @@ class CacheKeepStore {
31541
32073
  restored++;
31542
32074
  }
31543
32075
  } catch {
31544
- logger2.debug("cachekeep", "restart record dropped", {
31545
- file: name,
31546
- reason
31547
- });
31548
- dropped++;
31549
- await rm8(path2, { force: true });
32076
+ this.chain = this.chain.then(async () => {
32077
+ if (!await permitted())
32078
+ return;
32079
+ await rm8(path2, { force: true });
32080
+ logger2.debug("cachekeep", "restart record dropped", {
32081
+ file: name,
32082
+ reason
32083
+ });
32084
+ dropped++;
32085
+ }).catch(() => this.writeFailed());
32086
+ await this.chain;
31550
32087
  } finally {
31551
32088
  await release2?.();
31552
32089
  }
@@ -31572,8 +32109,8 @@ class CacheKeepStore {
31572
32109
  this.pending.set(entry2.id, entry2);
31573
32110
  if (this.timers.has(entry2.id))
31574
32111
  return;
31575
- const delay3 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
31576
- const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay3);
32112
+ const delay4 = Math.max(250, (this.lastWrite.get(entry2.id) ?? 0) + 5000 - (this.options.now?.() ?? Date.now()));
32113
+ const timer = (this.options.setTimeoutImpl ?? setTimeout)(() => this.flush(entry2.id), delay4);
31577
32114
  timer.unref?.();
31578
32115
  this.timers.set(entry2.id, timer);
31579
32116
  }
@@ -35923,7 +36460,7 @@ async function beginNativeEmptyInit(paths, hooks = {}) {
35923
36460
  host: "opencode",
35924
36461
  phase: "committed"
35925
36462
  };
35926
- await hooks.assertOwned?.();
36463
+ await (hooks.validate ?? hooks.assertOwned)?.();
35927
36464
  await writeJournal(paths, initial, () => lock.assertOwned(), hooks);
35928
36465
  return initial;
35929
36466
  });
@@ -42818,7 +43355,7 @@ function relayGeneration(input) {
42818
43355
  }
42819
43356
  // src/native-host-auth-write.ts
42820
43357
  import { randomUUID as randomUUID24 } from "node:crypto";
42821
- import { lstat as lstat19, open as open13, rename as rename14, unlink as unlink9 } from "node:fs/promises";
43358
+ import { lstat as lstat19, open as open13, rename as rename15, unlink as unlink9 } from "node:fs/promises";
42822
43359
  import { dirname as dirname22, isAbsolute as isAbsolute6, join as join28 } from "node:path";
42823
43360
  class NativeHostAuthWriteError extends Error {
42824
43361
  code;
@@ -42915,7 +43452,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
42915
43452
  return "publish";
42916
43453
  });
42917
43454
  } else
42918
- await (publication2.rename ?? rename14)(stage, authPath);
43455
+ await (publication2.rename ?? rename15)(stage, authPath);
42919
43456
  ownedStage = undefined;
42920
43457
  effect = outcome;
42921
43458
  await barrier(afterRename, "hook-failed", effect);
@@ -43011,7 +43548,8 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43011
43548
  const env = { ...input.env };
43012
43549
  const routingDestinationPath = input.routingDestinationPath;
43013
43550
  const processFence = input.processFence;
43014
- await processFence();
43551
+ const validate = input.validate ?? processFence;
43552
+ await validate();
43015
43553
  requireNoSupervisedAuthContentSnapshot(env);
43016
43554
  return withLock(paths2.journal, {
43017
43555
  name: "native-migration",
@@ -43020,9 +43558,9 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43020
43558
  ...hooks.lockOptions,
43021
43559
  renew: true
43022
43560
  }, async (lease) => {
43023
- await processFence();
43024
- const checkDestinations = async () => {
43025
- await processFence();
43561
+ await validate();
43562
+ const checkDestinations = async (publication2 = true) => {
43563
+ await (publication2 ? processFence : validate)();
43026
43564
  try {
43027
43565
  await lease.assertOwned();
43028
43566
  } catch {
@@ -43063,6 +43601,7 @@ async function publishNativeEmptyInit(input, hooks = {}) {
43063
43601
  return beginNativeEmptyInit(paths2, {
43064
43602
  lockOptions: hooks.lockOptions,
43065
43603
  assertOwned: checkDestinations,
43604
+ validate: () => checkDestinations(false),
43066
43605
  onWriteStep: async (step) => hooks.onStep?.(`${step}:journal:committed`)
43067
43606
  });
43068
43607
  });
@@ -43081,7 +43620,7 @@ function releaseNativeMigrationPreflight(token2) {
43081
43620
  }
43082
43621
  async function capture2(input, checkPool = false) {
43083
43622
  requireNoSupervisedAuthContentSnapshot(input.env);
43084
- await input.processFence();
43623
+ await (input.validate ?? input.processFence)();
43085
43624
  const resolved = await resolveNativePoolPaths(input.paths.legacyConfig, input.paths.legacyState, processStateLayout(input.paths.legacyConfig));
43086
43625
  for (const key of Object.keys(resolved))
43087
43626
  if (input.paths[key] !== resolved[key])
@@ -43535,13 +44074,13 @@ async function runNativeMigration(input, hooks = {}) {
43535
44074
  const projection = captured.projection;
43536
44075
  if (!projection)
43537
44076
  refuse3();
43538
- const beforeMutator = async () => {
44077
+ const beforeMutator = async (publication2 = true) => {
43539
44078
  await checkPaths(operation, captured);
43540
44079
  await checkLegacy(captured);
43541
- await operation.processFence();
44080
+ await (publication2 ? operation.processFence : operation.validate ?? operation.processFence)();
43542
44081
  await assertMigration();
43543
44082
  };
43544
- await beforeMutator();
44083
+ await beforeMutator(false);
43545
44084
  await store.initialize();
43546
44085
  for (const account of [...projection.accounts].filter((account2) => account2.credential).sort((a, b) => Number(a.enabled) - Number(b.enabled))) {
43547
44086
  const current = (await publicRows(store)).find((row) => row.id === account.id);
@@ -43557,7 +44096,7 @@ async function runNativeMigration(input, hooks = {}) {
43557
44096
  ]
43558
44097
  }, [current], false);
43559
44098
  else {
43560
- await beforeMutator();
44099
+ await beforeMutator(false);
43561
44100
  if (!account.credential)
43562
44101
  refuse3();
43563
44102
  const result = await store.add({
@@ -43570,7 +44109,7 @@ async function runNativeMigration(input, hooks = {}) {
43570
44109
  refuse3();
43571
44110
  await step(`after:add:${account.id}`);
43572
44111
  }
43573
- await beforeMutator();
44112
+ await beforeMutator(false);
43574
44113
  if (!account.enabled)
43575
44114
  await store.disable(account.id, "user-disabled");
43576
44115
  else
@@ -43579,21 +44118,21 @@ async function runNativeMigration(input, hooks = {}) {
43579
44118
  const row = (await publicRows(store)).find((row2) => row2.id === account.id);
43580
44119
  if (!row?.credentialEpoch)
43581
44120
  refuse3();
43582
- await beforeMutator();
44121
+ await beforeMutator(false);
43583
44122
  await store.recordQuota(account.id, {
43584
44123
  credentialEpoch: row.credentialEpoch,
43585
44124
  ...row.identity !== undefined ? { identity: row.identity } : {}
43586
44125
  }, account.quota);
43587
44126
  }
43588
44127
  }
43589
- await beforeMutator();
44128
+ await beforeMutator(false);
43590
44129
  await store.reorder(projection.accounts.filter((account) => account.credential).map((account) => account.id));
43591
44130
  if (journal.kind !== "legacy-import") {
43592
- await beforeMutator();
44131
+ await beforeMutator(false);
43593
44132
  await store.updateSettings(() => projection.settings);
43594
44133
  }
43595
44134
  if (captured.seedInput) {
43596
- await beforeMutator();
44135
+ await beforeMutator(false);
43597
44136
  await step("before:roster");
43598
44137
  if (!operation.custody)
43599
44138
  refuse3();
@@ -43606,7 +44145,7 @@ async function runNativeMigration(input, hooks = {}) {
43606
44145
  const rows = await publicRows(store);
43607
44146
  requireNativeMigrationSourceRows(projection, rows);
43608
44147
  const projected = projectNativeMigrationRuntime(paths2, projection, rows, seed);
43609
- await beforeMutator();
44148
+ await beforeMutator(false);
43610
44149
  await step("before:runtime");
43611
44150
  if (captured.seedInput) {
43612
44151
  if (!operation.custody)
@@ -43688,13 +44227,13 @@ async function runNativeMigration(input, hooks = {}) {
43688
44227
  }
43689
44228
  requireNativeMigrationPreparedProof(journal.preparedProof, rows, runtime2);
43690
44229
  const authoritative = journal;
43691
- const recheck = async () => {
44230
+ const recheck = async (publication2 = true) => {
43692
44231
  await checkPaths(operation, captured);
43693
44232
  await checkLegacy(captured);
43694
44233
  rows = await publicRows(store);
43695
44234
  runtime2 = await importedRuntimeProjection(paths2, store, rows);
43696
44235
  requireNativeMigrationPreparedProof(authoritative.preparedProof, rows, runtime2);
43697
- await operation.processFence();
44236
+ await (publication2 ? operation.processFence : operation.validate ?? operation.processFence)();
43698
44237
  await assertOwned();
43699
44238
  };
43700
44239
  await withLock(operation.routingDestinationPath, { name: "write", ttlMs: 30000, timeoutMs: 15000, renew: true }, async (routingLease) => {
@@ -43725,7 +44264,7 @@ async function runNativeMigration(input, hooks = {}) {
43725
44264
  if (authoritative.phase === "activation-installed" && entry2.digest !== authoritative.expectedHostAuth)
43726
44265
  refuse3();
43727
44266
  await step("before:host");
43728
- await recheck();
44267
+ await recheck(false);
43729
44268
  await mkdir15(dirname23(operation.hostAuthPath), {
43730
44269
  recursive: true,
43731
44270
  mode: 448
@@ -43744,7 +44283,7 @@ async function runNativeMigration(input, hooks = {}) {
43744
44283
  }
43745
44284
  }, hooks.hostWrite);
43746
44285
  await step("after:host");
43747
- await recheck();
44286
+ await recheck(false);
43748
44287
  const effect = await readNativeMigrationSource("hostAuth", operation.hostAuthPath);
43749
44288
  if (inspectNativeHostAuthEntry(operation.host, effect.data).digest !== authoritative.expectedHostAuth)
43750
44289
  refuse3();
@@ -46614,7 +47153,7 @@ import { dirname as dirname24, resolve as resolve23 } from "node:path";
46614
47153
  import { setTimeout as sleep } from "node:timers/promises";
46615
47154
 
46616
47155
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
46617
- import { rmdirSync, statSync as statSync6, utimesSync } from "node:fs";
47156
+ import { rmdirSync, statSync as statSync7, utimesSync } from "node:fs";
46618
47157
  import { mkdir as mkdir16, rmdir, stat as stat13, utimes } from "node:fs/promises";
46619
47158
  var STALE = 30000;
46620
47159
  var RENEWAL_STALE = 1e4;
@@ -46626,7 +47165,7 @@ process.once("exit", () => {
46626
47165
  try {
46627
47166
  if (identity5.renewedAt + RENEWAL_STALE < Date.now())
46628
47167
  continue;
46629
- const observed = statSync6(path2);
47168
+ const observed = statSync7(path2);
46630
47169
  if (sameDirectory(observed, identity5) && observed.mtime.getTime() === identity5.mtime)
46631
47170
  rmdirSync(path2);
46632
47171
  } catch {}
@@ -46718,12 +47257,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
46718
47257
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
46719
47258
  compromise();
46720
47259
  }
46721
- function schedule2(delay3 = UPDATE) {
47260
+ function schedule2(delay4 = UPDATE) {
46722
47261
  if (released)
46723
47262
  return;
46724
47263
  timer = setTimeout(() => {
46725
47264
  update();
46726
- }, delay3);
47265
+ }, delay4);
46727
47266
  timer.unref();
46728
47267
  }
46729
47268
  function retry(error) {
@@ -46740,7 +47279,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
46740
47279
  return;
46741
47280
  let observed;
46742
47281
  try {
46743
- observed = statSync6(path2);
47282
+ observed = statSync7(path2);
46744
47283
  } catch (error) {
46745
47284
  retry(error);
46746
47285
  return;
@@ -48042,7 +48581,7 @@ import {
48042
48581
  mkdir as mkdir19,
48043
48582
  readdir as readdir8,
48044
48583
  readFile as readFile18,
48045
- rename as rename15,
48584
+ rename as rename16,
48046
48585
  rm as rm11,
48047
48586
  stat as stat15,
48048
48587
  writeFile as writeFile7
@@ -48255,7 +48794,7 @@ class QuotaHeaderFeedRegistry {
48255
48794
  await writeFile7(tempPath, `${JSON.stringify({ version: QUOTA_HEADER_FEED_SCHEMA_VERSION, lease_horizon_ms: this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS, entries })}
48256
48795
  `, { mode: 384 });
48257
48796
  await chmod3(tempPath, 384);
48258
- await rename15(tempPath, this.filePath);
48797
+ await rename16(tempPath, this.filePath);
48259
48798
  } finally {
48260
48799
  await rm11(tempPath, { force: true });
48261
48800
  }
@@ -48481,7 +49020,7 @@ function buildClaudeQuotaSummary(input) {
48481
49020
  `).trimEnd();
48482
49021
  }
48483
49022
  // src/request-gzip.ts
48484
- import { mkdir as mkdir20, readFile as readFile19, rename as rename16, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
49023
+ import { mkdir as mkdir20, readFile as readFile19, rename as rename17, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
48485
49024
  import { basename as basename14, dirname as dirname26, join as join32 } from "node:path";
48486
49025
  import { promisify as promisify2 } from "node:util";
48487
49026
  import { gzip as gzip2 } from "node:zlib";
@@ -48609,7 +49148,7 @@ class RequestGzipLatch {
48609
49148
  await mkdir20(dirname26(this.path), { recursive: true });
48610
49149
  await writeFile8(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
48611
49150
  `, { mode: 384 });
48612
- await rename16(temporary, this.path);
49151
+ await rename17(temporary, this.path);
48613
49152
  } catch {
48614
49153
  await rm12(temporary, { force: true }).catch(() => {});
48615
49154
  }
@@ -52255,6 +52794,7 @@ export {
52255
52794
  writeDumpFile,
52256
52795
  withSessionCacheReportHandoff,
52257
52796
  withNativeLock,
52797
+ withCacheKeepRealTurn,
52258
52798
  withAnthropicBilling,
52259
52799
  withAbortableFetch,
52260
52800
  warnRelayProxyRefused,
@@ -52519,6 +53059,7 @@ export {
52519
53059
  isStateLayoutRefusalCode,
52520
53060
  isSseCandidateFrame,
52521
53061
  isSettingsImportPending,
53062
+ isSessionCacheWarmStopReason,
52522
53063
  isServerFallbackUsageMarker,
52523
53064
  isSeparateSettingsInstall,
52524
53065
  isSecretKey,
@@ -52555,6 +53096,7 @@ export {
52555
53096
  isClaudeFableOrMythos5Model,
52556
53097
  isClaudeFableOrMythos51Model,
52557
53098
  isClaudeFable51Model,
53099
+ isCacheKeepWarmWait,
52558
53100
  isCacheKeepSubagentsEnabled,
52559
53101
  isCacheKeepPersistentlyEnabled,
52560
53102
  isCacheKeepHybridActive,
@@ -52692,6 +53234,7 @@ export {
52692
53234
  custodyTombstoneOAuth,
52693
53235
  custodyTombstoneKey,
52694
53236
  custodyStatusLabel,
53237
+ currentCacheKeepRealTurn,
52695
53238
  createWindowsOwnerOnly,
52696
53239
  createStringPatch,
52697
53240
  createStickyNoRouteResponse,