@cortexkit/anthropic-auth-core 2.13.0 → 2.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cachekeep-store.d.ts +6 -2
- package/dist/cachekeep.d.ts +50 -5
- package/dist/index.js +616 -152
- package/dist/internal-types/routing-accessor/cache-policy.d.ts +2 -2
- package/dist/internal-types/store/index.d.ts +1 -1
- package/dist/internal-types/store/settings.d.ts +8 -0
- package/dist/pool-store.d.ts +0 -7
- package/dist/session-cache-policy.d.ts +10 -2
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1486,6 +1486,9 @@ async function syncJsonFile(path) {
|
|
|
1486
1486
|
// ../../node_modules/@cortexkit/common-auth/dist/fs/canonical-file-path.js
|
|
1487
1487
|
import { basename, dirname as dirname4, join as join2, resolve as resolve5 } from "node:path";
|
|
1488
1488
|
var maxSymlinkHops = 40;
|
|
1489
|
+
function symlinkLoop(file) {
|
|
1490
|
+
return Object.assign(new Error(`ELOOP: too many symbolic links encountered, realpath '${file}'`), { code: "ELOOP", syscall: "realpath", path: file });
|
|
1491
|
+
}
|
|
1489
1492
|
async function canonicalFilePath(file, fs) {
|
|
1490
1493
|
let target = file;
|
|
1491
1494
|
for (let hops = 0;; hops++) {
|
|
@@ -1501,7 +1504,7 @@ async function canonicalFilePath(file, fs) {
|
|
|
1501
1504
|
if (!isSymlink)
|
|
1502
1505
|
return target;
|
|
1503
1506
|
if (hops >= maxSymlinkHops)
|
|
1504
|
-
throw
|
|
1507
|
+
throw symlinkLoop(file);
|
|
1505
1508
|
target = resolve5(dirname4(target), await fs.readlink(target));
|
|
1506
1509
|
}
|
|
1507
1510
|
}
|
|
@@ -1520,7 +1523,7 @@ function canonicalFilePathSync(file, fs) {
|
|
|
1520
1523
|
if (!isSymlink)
|
|
1521
1524
|
return target;
|
|
1522
1525
|
if (hops >= maxSymlinkHops)
|
|
1523
|
-
throw
|
|
1526
|
+
throw symlinkLoop(file);
|
|
1524
1527
|
target = resolve5(dirname4(target), fs.readlinkSync(target));
|
|
1525
1528
|
}
|
|
1526
1529
|
}
|
|
@@ -7367,6 +7370,7 @@ function routingHandle(sessionId) {
|
|
|
7367
7370
|
var CACHE_WARM_STOP_REASONS = [
|
|
7368
7371
|
"cost-cap",
|
|
7369
7372
|
"count-cap",
|
|
7373
|
+
"deadline-missed",
|
|
7370
7374
|
"outside-hours",
|
|
7371
7375
|
"session-ended",
|
|
7372
7376
|
"unsupported"
|
|
@@ -14255,6 +14259,7 @@ function executeCache1hCommand(input) {
|
|
|
14255
14259
|
`);
|
|
14256
14260
|
}
|
|
14257
14261
|
// src/cachekeep.ts
|
|
14262
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
14258
14263
|
import { createHash as createHash9 } from "node:crypto";
|
|
14259
14264
|
|
|
14260
14265
|
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/decision.js
|
|
@@ -14271,7 +14276,7 @@ function withinHours(hours, at) {
|
|
|
14271
14276
|
return hours.from < hours.to ? time >= hours.from && time < hours.to : time >= hours.from || time < hours.to;
|
|
14272
14277
|
}
|
|
14273
14278
|
function decideCacheKeep(input) {
|
|
14274
|
-
const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost } = input;
|
|
14279
|
+
const { mode, now, ttlMs, leadMs = 30000, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost } = input;
|
|
14275
14280
|
if (mode === "off")
|
|
14276
14281
|
return { action: "stop", reason: "unsupported" };
|
|
14277
14282
|
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
@@ -14283,10 +14288,11 @@ function decideCacheKeep(input) {
|
|
|
14283
14288
|
return { action: "stop", reason: "cost-cap" };
|
|
14284
14289
|
const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
|
|
14285
14290
|
const expiresAt = last + ttlMs;
|
|
14286
|
-
const
|
|
14291
|
+
const lead = Math.min(Number.isFinite(leadMs) && leadMs > 0 ? leadMs : 30000, ttlMs / 2);
|
|
14292
|
+
const due = expiresAt - lead;
|
|
14287
14293
|
const at = Math.max(now, due);
|
|
14288
14294
|
if (at >= expiresAt - Math.min(5000, ttlMs / 10)) {
|
|
14289
|
-
return { action: "stop", reason: "
|
|
14295
|
+
return { action: "stop", reason: "deadline-missed" };
|
|
14290
14296
|
}
|
|
14291
14297
|
if (mode === "hours" && (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
|
|
14292
14298
|
return { action: "stop", reason: "outside-hours" };
|
|
@@ -14380,6 +14386,7 @@ class CacheKeepManager {
|
|
|
14380
14386
|
log;
|
|
14381
14387
|
ttlMs;
|
|
14382
14388
|
leadMs;
|
|
14389
|
+
planLeadMs;
|
|
14383
14390
|
maxIdleWarmMs;
|
|
14384
14391
|
maxSubagentIdleMs;
|
|
14385
14392
|
tickIntervalMs;
|
|
@@ -14405,6 +14412,7 @@ class CacheKeepManager {
|
|
|
14405
14412
|
this.ttlMs = positive(options.ttlMs, DEFAULT_TTL_MS);
|
|
14406
14413
|
this.tickIntervalMs = positive(options.tickIntervalMs, DEFAULT_TICK_INTERVAL_MS);
|
|
14407
14414
|
this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15000);
|
|
14415
|
+
this.planLeadMs = options.planLeadMs;
|
|
14408
14416
|
this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
|
|
14409
14417
|
this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
|
|
14410
14418
|
this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
|
|
@@ -14625,7 +14633,7 @@ class CacheKeepManager {
|
|
|
14625
14633
|
cacheExpiresAt: target.cacheExpiresAt,
|
|
14626
14634
|
failures: target.failures
|
|
14627
14635
|
});
|
|
14628
|
-
this.drop(sessionKey, target.plan ? "
|
|
14636
|
+
this.drop(sessionKey, target.plan ? "deadline-missed" : "expired");
|
|
14629
14637
|
return true;
|
|
14630
14638
|
}
|
|
14631
14639
|
isCurrent(sessionKey, target) {
|
|
@@ -14686,6 +14694,7 @@ class CacheKeepManager {
|
|
|
14686
14694
|
...plan.mode === "hours" ? { mode: plan.mode, hours: plan.hours } : { mode: plan.mode },
|
|
14687
14695
|
now: this.now(),
|
|
14688
14696
|
ttlMs: target.ttlMs,
|
|
14697
|
+
...this.planLeadMs !== undefined ? { leadMs: this.planLeadMs } : {},
|
|
14689
14698
|
lastRealRequestAt: target.lastRealRequestAt,
|
|
14690
14699
|
lastWarmAt: target.lastWarmedAt,
|
|
14691
14700
|
warmsSinceLastRealRequest: target.warmCount,
|
|
@@ -19783,6 +19792,9 @@ function withSessionCacheReportHandoff(work) {
|
|
|
19783
19792
|
function reportSessionCacheTouch(sessionId, input) {
|
|
19784
19793
|
detachReport2(() => reportCacheTouch(sessionId, input), input.source === "response", input.source === "warm");
|
|
19785
19794
|
}
|
|
19795
|
+
function isSessionCacheWarmStopReason(value) {
|
|
19796
|
+
return isCacheWarmStopReason(value);
|
|
19797
|
+
}
|
|
19786
19798
|
function reportSessionCacheWarmStopped(sessionId, input) {
|
|
19787
19799
|
return detachReport2(() => reportCacheWarmStopped(sessionId, input));
|
|
19788
19800
|
}
|
|
@@ -19831,35 +19843,49 @@ function applySessionCacheTtl(body, ttl) {
|
|
|
19831
19843
|
delete control.ttl;
|
|
19832
19844
|
});
|
|
19833
19845
|
}
|
|
19834
|
-
function
|
|
19846
|
+
function visitRequestCacheLifetimes(input, visit) {
|
|
19835
19847
|
let body = input;
|
|
19836
19848
|
if (typeof input === "string") {
|
|
19837
19849
|
try {
|
|
19838
19850
|
body = JSON.parse(input);
|
|
19839
19851
|
} catch {
|
|
19840
|
-
return
|
|
19852
|
+
return;
|
|
19841
19853
|
}
|
|
19842
19854
|
}
|
|
19843
19855
|
if (!record5(body))
|
|
19844
|
-
return
|
|
19845
|
-
let ttlMs = 0;
|
|
19856
|
+
return;
|
|
19846
19857
|
cacheHolders(body, (holder) => {
|
|
19847
19858
|
for (const key of ["cache_control", "cacheControl"]) {
|
|
19848
19859
|
const control = holder[key];
|
|
19849
19860
|
if (!record5(control) || control.type !== "ephemeral")
|
|
19850
19861
|
continue;
|
|
19851
|
-
|
|
19862
|
+
visit(control.ttl === "1h" ? PROMPT_CACHE_1H_TTL_MS : PROMPT_CACHE_DEFAULT_TTL_MS);
|
|
19852
19863
|
}
|
|
19853
19864
|
});
|
|
19865
|
+
}
|
|
19866
|
+
function requestCacheLifetimeMs(input) {
|
|
19867
|
+
let ttlMs = 0;
|
|
19868
|
+
visitRequestCacheLifetimes(input, (lifetime) => {
|
|
19869
|
+
ttlMs = Math.max(ttlMs, lifetime);
|
|
19870
|
+
});
|
|
19854
19871
|
return ttlMs;
|
|
19855
19872
|
}
|
|
19873
|
+
function requestShortestCacheLifetimeMs(input) {
|
|
19874
|
+
let ttlMs = Infinity;
|
|
19875
|
+
visitRequestCacheLifetimes(input, (lifetime) => {
|
|
19876
|
+
ttlMs = Math.min(ttlMs, lifetime);
|
|
19877
|
+
});
|
|
19878
|
+
return ttlMs === Infinity ? 0 : ttlMs;
|
|
19879
|
+
}
|
|
19856
19880
|
|
|
19857
19881
|
// src/cachekeep.ts
|
|
19858
19882
|
var CLAUDE_CACHE_KEEP_COMMAND_NAME = "claude-cachekeep";
|
|
19859
19883
|
var CACHE_KEEP_TTL_MS = 60 * 60000;
|
|
19860
19884
|
var CACHE_KEEP_PREWARM_LEAD_MS = 5 * 60000;
|
|
19861
19885
|
function replayPrewarmLeadMs(ttlMs, planned) {
|
|
19862
|
-
if (
|
|
19886
|
+
if (planned)
|
|
19887
|
+
return Math.min(CACHE_KEEP_PREWARM_LEAD_MS, ttlMs / 2);
|
|
19888
|
+
if (ttlMs === CACHE_KEEP_TTL_MS)
|
|
19863
19889
|
return CACHE_KEEP_PREWARM_LEAD_MS;
|
|
19864
19890
|
return Math.min(30000, ttlMs / 2);
|
|
19865
19891
|
}
|
|
@@ -20124,6 +20150,7 @@ function stopReason(reason) {
|
|
|
20124
20150
|
case "schedule-period-ended":
|
|
20125
20151
|
return "schedule";
|
|
20126
20152
|
case "retry-window-ended":
|
|
20153
|
+
case "deadline-missed":
|
|
20127
20154
|
return "retries-exhausted";
|
|
20128
20155
|
case "cachekeep-hybrid-inactive":
|
|
20129
20156
|
return "disabled";
|
|
@@ -20136,34 +20163,22 @@ function stopReason(reason) {
|
|
|
20136
20163
|
}
|
|
20137
20164
|
}
|
|
20138
20165
|
function reportStopReason(reason) {
|
|
20166
|
+
if (isSessionCacheWarmStopReason(reason))
|
|
20167
|
+
return reason;
|
|
20139
20168
|
switch (reason) {
|
|
20140
|
-
case "cost-cap":
|
|
20141
|
-
case "count-cap":
|
|
20142
|
-
case "outside-hours":
|
|
20143
|
-
case "session-ended":
|
|
20144
|
-
case "unsupported":
|
|
20145
|
-
case "evicted":
|
|
20146
|
-
case "stopped":
|
|
20147
|
-
case "account-changed":
|
|
20148
|
-
case "routing-moved":
|
|
20149
|
-
case "expired":
|
|
20150
|
-
case "idle":
|
|
20151
|
-
return reason;
|
|
20152
|
-
case "budget":
|
|
20153
|
-
case "count":
|
|
20154
|
-
return "evicted";
|
|
20155
20169
|
case "schedule":
|
|
20156
20170
|
case "schedule-period-ended":
|
|
20157
20171
|
return "outside-hours";
|
|
20172
|
+
case "stopped":
|
|
20158
20173
|
case "session-forgotten":
|
|
20159
20174
|
return "session-ended";
|
|
20160
20175
|
case "retry-window-ended":
|
|
20161
|
-
|
|
20176
|
+
case "retries-exhausted":
|
|
20177
|
+
case "expired":
|
|
20178
|
+
return "deadline-missed";
|
|
20179
|
+
case "idle":
|
|
20162
20180
|
case "source-warm-idle-cap":
|
|
20163
20181
|
return "cost-cap";
|
|
20164
|
-
case "credential-changed":
|
|
20165
|
-
case "account-unavailable":
|
|
20166
|
-
return "account-changed";
|
|
20167
20182
|
default:
|
|
20168
20183
|
return "unsupported";
|
|
20169
20184
|
}
|
|
@@ -20256,6 +20271,23 @@ class CacheKeepWarmRefusal extends Error {
|
|
|
20256
20271
|
this.reason = reason;
|
|
20257
20272
|
}
|
|
20258
20273
|
}
|
|
20274
|
+
var CACHE_KEEP_WARM_WAIT = Symbol.for("cortexkit.anthropic-auth.cachekeep.wait");
|
|
20275
|
+
|
|
20276
|
+
class CacheKeepWarmWait extends Error {
|
|
20277
|
+
[CACHE_KEEP_WARM_WAIT] = true;
|
|
20278
|
+
}
|
|
20279
|
+
function isCacheKeepWarmWait(error) {
|
|
20280
|
+
try {
|
|
20281
|
+
return typeof error === "object" && error !== null && Object.getOwnPropertyDescriptor(error, CACHE_KEEP_WARM_WAIT)?.value === true;
|
|
20282
|
+
} catch {
|
|
20283
|
+
return false;
|
|
20284
|
+
}
|
|
20285
|
+
}
|
|
20286
|
+
var realTurnContext = new AsyncLocalStorage3;
|
|
20287
|
+
var currentCacheKeepRealTurn = () => realTurnContext.getStore();
|
|
20288
|
+
function withCacheKeepRealTurn(turn, run) {
|
|
20289
|
+
return realTurnContext.run(turn, run);
|
|
20290
|
+
}
|
|
20259
20291
|
|
|
20260
20292
|
class CacheKeepManager2 {
|
|
20261
20293
|
options;
|
|
@@ -20266,8 +20298,19 @@ class CacheKeepManager2 {
|
|
|
20266
20298
|
timer = null;
|
|
20267
20299
|
dueTimer = null;
|
|
20268
20300
|
tickPromise = null;
|
|
20301
|
+
lifetime = 0;
|
|
20302
|
+
schedulerGeneration = 0;
|
|
20303
|
+
nextRealTurn = 0;
|
|
20304
|
+
realTurns = new Map;
|
|
20305
|
+
turnTimers = new Set;
|
|
20306
|
+
ticks = new Set;
|
|
20307
|
+
warmRuns = new Set;
|
|
20308
|
+
warmControllers = new Map;
|
|
20269
20309
|
nextPrewarmAttemptId = 0;
|
|
20270
20310
|
reportedStops = new WeakSet;
|
|
20311
|
+
restoredTargets = new WeakSet;
|
|
20312
|
+
restoringPolicies = new WeakSet;
|
|
20313
|
+
sessionWarms = new Map;
|
|
20271
20314
|
admittedWarmCosts = new WeakMap;
|
|
20272
20315
|
constructor(options) {
|
|
20273
20316
|
this.options = options;
|
|
@@ -20277,7 +20320,7 @@ class CacheKeepManager2 {
|
|
|
20277
20320
|
return;
|
|
20278
20321
|
logger2.debug("cachekeep", "started");
|
|
20279
20322
|
this.timer = (this.options.setIntervalImpl ?? globalThis.setInterval)(() => {
|
|
20280
|
-
this.tick().catch(() => {
|
|
20323
|
+
return this.tick().catch(() => {
|
|
20281
20324
|
logger2.warn("cachekeep", "tick failed");
|
|
20282
20325
|
});
|
|
20283
20326
|
}, CACHE_KEEP_TICK_MS);
|
|
@@ -20286,10 +20329,9 @@ class CacheKeepManager2 {
|
|
|
20286
20329
|
this.scheduleDueTimer();
|
|
20287
20330
|
}
|
|
20288
20331
|
stop() {
|
|
20332
|
+
this.schedulerGeneration++;
|
|
20333
|
+
this.tickPromise = null;
|
|
20289
20334
|
this.immediateTargets.clear();
|
|
20290
|
-
const now = this.options.now?.() ?? Date.now();
|
|
20291
|
-
for (const target of this.targets.values())
|
|
20292
|
-
this.reportStop(target, "stopped", now);
|
|
20293
20335
|
if (this.dueTimer) {
|
|
20294
20336
|
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
20295
20337
|
this.dueTimer = null;
|
|
@@ -20301,6 +20343,172 @@ class CacheKeepManager2 {
|
|
|
20301
20343
|
clearIntervalImpl(this.timer);
|
|
20302
20344
|
this.timer = null;
|
|
20303
20345
|
}
|
|
20346
|
+
dispose() {
|
|
20347
|
+
this.lifetime++;
|
|
20348
|
+
this.stop();
|
|
20349
|
+
this.abortWarms();
|
|
20350
|
+
for (const timer of this.turnTimers) {
|
|
20351
|
+
try {
|
|
20352
|
+
(this.options.clearTimeoutImpl ?? clearTimeout)(timer);
|
|
20353
|
+
} catch {}
|
|
20354
|
+
}
|
|
20355
|
+
this.turnTimers.clear();
|
|
20356
|
+
this.realTurns.clear();
|
|
20357
|
+
this.targets.clear();
|
|
20358
|
+
this.immediateTargets.clear();
|
|
20359
|
+
this.stoppedSessions.clear();
|
|
20360
|
+
this.warmingRecords.clear();
|
|
20361
|
+
this.sessionWarms.clear();
|
|
20362
|
+
this.tickPromise = null;
|
|
20363
|
+
return this.drain();
|
|
20364
|
+
}
|
|
20365
|
+
abortWarms() {
|
|
20366
|
+
for (const controller of this.warmControllers.keys())
|
|
20367
|
+
controller.abort();
|
|
20368
|
+
}
|
|
20369
|
+
async drain() {
|
|
20370
|
+
await Promise.allSettled([...this.ticks, ...this.warmRuns]);
|
|
20371
|
+
}
|
|
20372
|
+
beginRealTurn(sessionId) {
|
|
20373
|
+
let active = true;
|
|
20374
|
+
let busy = true;
|
|
20375
|
+
let tracked = false;
|
|
20376
|
+
const lifetime = this.lifetime;
|
|
20377
|
+
const id = ++this.nextRealTurn;
|
|
20378
|
+
let now = Date.now();
|
|
20379
|
+
try {
|
|
20380
|
+
now = this.options.now?.() ?? now;
|
|
20381
|
+
} catch {}
|
|
20382
|
+
const ownerExpiry = Math.min(...[...this.targets.values()].filter((target) => target.policyState?.ownerSessionId === sessionId).map((target) => target.cacheExpiresAt));
|
|
20383
|
+
const expiresAt = this.targets.get(sessionId)?.cacheExpiresAt ?? (Number.isFinite(ownerExpiry) ? ownerExpiry : now + CACHE_KEEP_TTL_MS);
|
|
20384
|
+
const turns = this.realTurns.get(sessionId) ?? {
|
|
20385
|
+
latest: id,
|
|
20386
|
+
pending: 0,
|
|
20387
|
+
leases: new Set
|
|
20388
|
+
};
|
|
20389
|
+
turns.latest = id;
|
|
20390
|
+
turns.pending++;
|
|
20391
|
+
this.realTurns.set(sessionId, turns);
|
|
20392
|
+
let timer;
|
|
20393
|
+
const currentTime = () => {
|
|
20394
|
+
try {
|
|
20395
|
+
return this.options.now?.() ?? Date.now();
|
|
20396
|
+
} catch {
|
|
20397
|
+
return Date.now();
|
|
20398
|
+
}
|
|
20399
|
+
};
|
|
20400
|
+
const clearTimer = () => {
|
|
20401
|
+
if (timer) {
|
|
20402
|
+
this.turnTimers.delete(timer);
|
|
20403
|
+
try {
|
|
20404
|
+
(this.options.clearTimeoutImpl ?? clearTimeout)(timer);
|
|
20405
|
+
} catch {}
|
|
20406
|
+
timer = undefined;
|
|
20407
|
+
}
|
|
20408
|
+
};
|
|
20409
|
+
const releaseBusy = () => {
|
|
20410
|
+
if (!busy)
|
|
20411
|
+
return;
|
|
20412
|
+
busy = false;
|
|
20413
|
+
turns.leases.delete(record6);
|
|
20414
|
+
clearTimer();
|
|
20415
|
+
};
|
|
20416
|
+
const release = (silent = false) => {
|
|
20417
|
+
if (!active)
|
|
20418
|
+
return;
|
|
20419
|
+
active = false;
|
|
20420
|
+
releaseBusy();
|
|
20421
|
+
clearTimer();
|
|
20422
|
+
turns.pending--;
|
|
20423
|
+
try {
|
|
20424
|
+
if (!silent && lifetime === this.lifetime && turns.latest === id && currentTime() < expiresAt + CACHE_KEEP_TTL_MS)
|
|
20425
|
+
this.finishSessionTargets(sessionId, tracked ? this.targets.get(sessionId) : undefined);
|
|
20426
|
+
} catch {} finally {
|
|
20427
|
+
if (turns.pending === 0 && this.realTurns.get(sessionId) === turns)
|
|
20428
|
+
this.realTurns.delete(sessionId);
|
|
20429
|
+
try {
|
|
20430
|
+
if (lifetime === this.lifetime)
|
|
20431
|
+
this.scheduleDueTimer();
|
|
20432
|
+
} catch {}
|
|
20433
|
+
}
|
|
20434
|
+
};
|
|
20435
|
+
const record6 = {
|
|
20436
|
+
id,
|
|
20437
|
+
expiresAt,
|
|
20438
|
+
expire: () => {
|
|
20439
|
+
if (!active || lifetime !== this.lifetime) {
|
|
20440
|
+
release(true);
|
|
20441
|
+
return;
|
|
20442
|
+
}
|
|
20443
|
+
if (!busy)
|
|
20444
|
+
return;
|
|
20445
|
+
releaseBusy();
|
|
20446
|
+
const remaining = expiresAt + CACHE_KEEP_TTL_MS - currentTime();
|
|
20447
|
+
if (remaining <= 0)
|
|
20448
|
+
release(true);
|
|
20449
|
+
else {
|
|
20450
|
+
try {
|
|
20451
|
+
timer = (this.options.setTimeoutImpl ?? setTimeout)(() => release(true), remaining);
|
|
20452
|
+
timer.unref?.();
|
|
20453
|
+
this.turnTimers.add(timer);
|
|
20454
|
+
if (lifetime === this.lifetime)
|
|
20455
|
+
this.scheduleDueTimer();
|
|
20456
|
+
} catch {}
|
|
20457
|
+
}
|
|
20458
|
+
}
|
|
20459
|
+
};
|
|
20460
|
+
turns.leases.add(record6);
|
|
20461
|
+
try {
|
|
20462
|
+
timer = (this.options.setTimeoutImpl ?? setTimeout)(record6.expire, Math.max(0, expiresAt - now));
|
|
20463
|
+
timer.unref?.();
|
|
20464
|
+
this.turnTimers.add(timer);
|
|
20465
|
+
for (const [controller, session] of this.warmControllers)
|
|
20466
|
+
if (session === sessionId)
|
|
20467
|
+
controller.abort();
|
|
20468
|
+
this.scheduleDueTimer();
|
|
20469
|
+
} catch {}
|
|
20470
|
+
const thisManager = this;
|
|
20471
|
+
return {
|
|
20472
|
+
get active() {
|
|
20473
|
+
try {
|
|
20474
|
+
return active && busy && lifetime === thisManager.lifetime && (thisManager.options.now?.() ?? Date.now()) < expiresAt;
|
|
20475
|
+
} catch {
|
|
20476
|
+
return false;
|
|
20477
|
+
}
|
|
20478
|
+
},
|
|
20479
|
+
track: (input) => {
|
|
20480
|
+
if (turns.latest !== id) {
|
|
20481
|
+
release();
|
|
20482
|
+
return { tracked: false, reason: "superseded real turn" };
|
|
20483
|
+
}
|
|
20484
|
+
if (!active || lifetime !== this.lifetime || currentTime() >= expiresAt + CACHE_KEEP_TTL_MS) {
|
|
20485
|
+
release(true);
|
|
20486
|
+
return { tracked: false, reason: "real turn ended" };
|
|
20487
|
+
}
|
|
20488
|
+
try {
|
|
20489
|
+
const result = this.track({ ...input, sessionId });
|
|
20490
|
+
tracked = result.tracked;
|
|
20491
|
+
return result;
|
|
20492
|
+
} catch {
|
|
20493
|
+
return { tracked: false, reason: "real turn tracking failed" };
|
|
20494
|
+
} finally {
|
|
20495
|
+
release();
|
|
20496
|
+
}
|
|
20497
|
+
},
|
|
20498
|
+
finish: () => release(),
|
|
20499
|
+
pause: () => release(true)
|
|
20500
|
+
};
|
|
20501
|
+
}
|
|
20502
|
+
realTurnBusy(sessionId) {
|
|
20503
|
+
const turns = this.realTurns.get(sessionId);
|
|
20504
|
+
if (!turns)
|
|
20505
|
+
return false;
|
|
20506
|
+
let now = Date.now();
|
|
20507
|
+
try {
|
|
20508
|
+
now = this.options.now?.() ?? now;
|
|
20509
|
+
} catch {}
|
|
20510
|
+
return [...turns.leases].some((turn) => turn.expiresAt > now);
|
|
20511
|
+
}
|
|
20304
20512
|
stats(window, now = this.options.now?.() ?? Date.now(), always = false) {
|
|
20305
20513
|
const today = always ? "always" : localWindowKey(window, new Date(now));
|
|
20306
20514
|
const targets = [...this.targets.values()].filter((target) => target.dayKey === today);
|
|
@@ -20378,7 +20586,10 @@ class CacheKeepManager2 {
|
|
|
20378
20586
|
const record6 = this.warmingRecords.get(id);
|
|
20379
20587
|
if (!record6)
|
|
20380
20588
|
return;
|
|
20381
|
-
return
|
|
20589
|
+
return isSessionCacheWarmStopReason(record6.stopReason) ? {
|
|
20590
|
+
on: false,
|
|
20591
|
+
stopReason: record6.stopReason
|
|
20592
|
+
} : { on: false };
|
|
20382
20593
|
}
|
|
20383
20594
|
recordWarmingOff(id) {
|
|
20384
20595
|
this.setWarmingRecord(id, {});
|
|
@@ -20408,7 +20619,7 @@ class CacheKeepManager2 {
|
|
|
20408
20619
|
this.options.onTargetChanged?.(target);
|
|
20409
20620
|
this.scheduleDueTimer();
|
|
20410
20621
|
}
|
|
20411
|
-
costs(target) {
|
|
20622
|
+
costs(target, ownReservation = false) {
|
|
20412
20623
|
const state = target.policyState;
|
|
20413
20624
|
if (state?.prefixTokens === undefined)
|
|
20414
20625
|
return;
|
|
@@ -20436,14 +20647,22 @@ class CacheKeepManager2 {
|
|
|
20436
20647
|
return {
|
|
20437
20648
|
nextWarmCost: read * state.prefixTokens,
|
|
20438
20649
|
rewriteCost: write * state.prefixTokens,
|
|
20439
|
-
warmCostSoFar: state.warmCostSoFar
|
|
20650
|
+
warmCostSoFar: state.warmCostSoFar + Math.max(0, (state.pendingWarmCost ?? 0) - (ownReservation ? this.admittedWarmCosts.get(state) ?? 0 : 0))
|
|
20440
20651
|
};
|
|
20441
20652
|
}
|
|
20442
20653
|
policyDecision(target, now, ownReservation = false) {
|
|
20443
20654
|
const state = target.policyState;
|
|
20444
20655
|
if (!state)
|
|
20445
20656
|
return;
|
|
20446
|
-
const
|
|
20657
|
+
const freshPolicy = readSessionCachePolicy(state.ownerSessionId, true);
|
|
20658
|
+
if (freshPolicy) {
|
|
20659
|
+
if (JSON.stringify(state.policy) !== JSON.stringify(freshPolicy)) {
|
|
20660
|
+
state.policy = structuredClone(freshPolicy);
|
|
20661
|
+
this.options.onTargetChanged?.(target);
|
|
20662
|
+
}
|
|
20663
|
+
this.restoringPolicies.delete(state);
|
|
20664
|
+
}
|
|
20665
|
+
const policy = freshPolicy ?? (this.restoringPolicies.has(state) ? state.policy : undefined);
|
|
20447
20666
|
if (!policy && state.planned)
|
|
20448
20667
|
return { action: "stop", reason: "session-ended" };
|
|
20449
20668
|
if (!policy)
|
|
@@ -20461,13 +20680,14 @@ class CacheKeepManager2 {
|
|
|
20461
20680
|
const plan = mode === "hours" ? policy.hours && { mode, hours: policy.hours } : { mode };
|
|
20462
20681
|
if (!plan)
|
|
20463
20682
|
return { action: "stop", reason: "unsupported" };
|
|
20464
|
-
const costs = this.costs(target);
|
|
20683
|
+
const costs = this.costs(target, ownReservation);
|
|
20465
20684
|
if (mode === "auto" && !costs && state.lastRealRequestAt < now - (target.isSubagent ? PLANNED_UNPRICED_SUBAGENT_IDLE_MS : PLANNED_UNPRICED_MAIN_IDLE_MS))
|
|
20466
20685
|
return { action: "stop", reason: "idle" };
|
|
20467
20686
|
return decideCacheKeep({
|
|
20468
20687
|
...plan,
|
|
20469
20688
|
now,
|
|
20470
20689
|
ttlMs: target.ttlMs ?? 0,
|
|
20690
|
+
leadMs: CACHE_KEEP_PREWARM_LEAD_MS,
|
|
20471
20691
|
lastRealRequestAt: state.lastRealRequestAt,
|
|
20472
20692
|
lastWarmAt: state.lastWarmAt,
|
|
20473
20693
|
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest - Number(ownReservation),
|
|
@@ -20482,26 +20702,34 @@ class CacheKeepManager2 {
|
|
|
20482
20702
|
mode: "always",
|
|
20483
20703
|
now: state.lastRealRequestAt,
|
|
20484
20704
|
ttlMs: CACHE_KEEP_TTL_MS,
|
|
20705
|
+
...state.planned && { leadMs: CACHE_KEEP_PREWARM_LEAD_MS },
|
|
20485
20706
|
lastRealRequestAt: state.lastRealRequestAt,
|
|
20486
20707
|
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest
|
|
20487
20708
|
});
|
|
20488
20709
|
return result.action === "stop" && result.reason === "count-cap" ? result : undefined;
|
|
20489
20710
|
}
|
|
20490
20711
|
async reserveWarmDispatch(target) {
|
|
20712
|
+
const generation = this.schedulerGeneration;
|
|
20491
20713
|
const current = this.targets.get(target.id);
|
|
20492
20714
|
if (!current || !this.isCurrentTarget(target))
|
|
20493
20715
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20494
20716
|
const state = current.policyState;
|
|
20717
|
+
if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
|
|
20718
|
+
throw new CacheKeepWarmWait;
|
|
20495
20719
|
const loaded = await this.options.loadStorage();
|
|
20720
|
+
if (generation !== this.schedulerGeneration)
|
|
20721
|
+
throw new CacheKeepWarmWait;
|
|
20496
20722
|
const storage = loaded && this.options.resolveSettings ? this.targetSettings(this.options.resolveSettings(loaded), target.bodyText) : loaded;
|
|
20497
20723
|
if (!this.isCurrentTarget(target))
|
|
20498
20724
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20725
|
+
if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
|
|
20726
|
+
throw new CacheKeepWarmWait;
|
|
20499
20727
|
const now = this.options.now?.() ?? Date.now();
|
|
20500
20728
|
const decision = this.policyDecision(current, now) ?? (isCacheKeepAlways(storage) ? this.countDecision(current) : undefined);
|
|
20501
20729
|
if (decision?.action === "stop")
|
|
20502
20730
|
throw new CacheKeepWarmRefusal(decision.reason);
|
|
20503
20731
|
if (decision?.action === "wait")
|
|
20504
|
-
throw new
|
|
20732
|
+
throw new CacheKeepWarmWait;
|
|
20505
20733
|
const admittedCost = this.costs(current)?.nextWarmCost ?? 0;
|
|
20506
20734
|
const pendingCost = state?.pendingWarmCost;
|
|
20507
20735
|
if (state) {
|
|
@@ -20513,6 +20741,8 @@ class CacheKeepManager2 {
|
|
|
20513
20741
|
try {
|
|
20514
20742
|
committed = await this.options.reserveWarm(current);
|
|
20515
20743
|
} catch {}
|
|
20744
|
+
if (generation !== this.schedulerGeneration)
|
|
20745
|
+
throw new CacheKeepWarmWait;
|
|
20516
20746
|
if (!committed && (state?.planned || isCacheKeepAlways(storage))) {
|
|
20517
20747
|
if (state) {
|
|
20518
20748
|
state.warmsSinceLastRealRequest--;
|
|
@@ -20525,19 +20755,29 @@ class CacheKeepManager2 {
|
|
|
20525
20755
|
this.admittedWarmCosts.set(state, admittedCost);
|
|
20526
20756
|
if (!this.isCurrentTarget(target))
|
|
20527
20757
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20528
|
-
const fresh = this.policyDecision(current, this.options.now?.() ?? Date.now(), true);
|
|
20758
|
+
const fresh = this.realTurnBusy(state?.ownerSessionId ?? target.id) ? { action: "wait", until: 0 } : this.policyDecision(current, this.options.now?.() ?? Date.now(), true);
|
|
20529
20759
|
if (fresh?.action === "stop")
|
|
20530
20760
|
throw new CacheKeepWarmRefusal(fresh.reason);
|
|
20531
|
-
if (fresh?.action === "wait")
|
|
20532
|
-
|
|
20761
|
+
if (fresh?.action === "wait") {
|
|
20762
|
+
if (state) {
|
|
20763
|
+
state.warmsSinceLastRealRequest--;
|
|
20764
|
+
state.pendingWarmCost = pendingCost;
|
|
20765
|
+
this.admittedWarmCosts.delete(state);
|
|
20766
|
+
await this.options.settleWarm?.(current);
|
|
20767
|
+
}
|
|
20768
|
+
throw new CacheKeepWarmWait;
|
|
20769
|
+
}
|
|
20533
20770
|
}
|
|
20534
20771
|
scheduleDueTimer() {
|
|
20535
20772
|
if (this.dueTimer)
|
|
20536
20773
|
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
20537
20774
|
this.dueTimer = null;
|
|
20775
|
+
if (!this.timer)
|
|
20776
|
+
return;
|
|
20538
20777
|
let due = Infinity;
|
|
20539
20778
|
for (const target of this.targets.values())
|
|
20540
|
-
|
|
20779
|
+
if (!this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
|
|
20780
|
+
due = Math.min(due, target.nextPrewarmAt);
|
|
20541
20781
|
if (!Number.isFinite(due))
|
|
20542
20782
|
return;
|
|
20543
20783
|
this.dueTimer = (this.options.setTimeoutImpl ?? setTimeout)(() => {
|
|
@@ -20572,19 +20812,18 @@ class CacheKeepManager2 {
|
|
|
20572
20812
|
if (this.targets.get(target.id) !== target)
|
|
20573
20813
|
return;
|
|
20574
20814
|
this.reportStop(target, reason, now);
|
|
20575
|
-
|
|
20576
|
-
|
|
20577
|
-
|
|
20578
|
-
|
|
20579
|
-
|
|
20580
|
-
|
|
20581
|
-
|
|
20582
|
-
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
20586
|
-
|
|
20587
|
-
});
|
|
20815
|
+
logger2[now >= target.cacheExpiresAt ? "info" : reason === "count-cap" ? "debug" : "warn"]("cachekeep", "stopped warming session", {
|
|
20816
|
+
session: target.id,
|
|
20817
|
+
reason,
|
|
20818
|
+
bodyBytes: target.bodyBytes,
|
|
20819
|
+
totalBodyBytes: this.totalBodyBytes(),
|
|
20820
|
+
budgetBytes: CACHE_KEEP_MAX_BODY_BYTES,
|
|
20821
|
+
targets: this.targets.size,
|
|
20822
|
+
maxTargets: CACHE_KEEP_MAX_TARGETS,
|
|
20823
|
+
cacheExpiresAt: target.cacheExpiresAt,
|
|
20824
|
+
nextPrewarmAt: target.nextPrewarmAt,
|
|
20825
|
+
...details
|
|
20826
|
+
});
|
|
20588
20827
|
this.retainStopped(target, stopReason(reason), now);
|
|
20589
20828
|
this.targets.delete(target.id);
|
|
20590
20829
|
this.options.onTargetRemoved?.(target.id);
|
|
@@ -20597,17 +20836,28 @@ class CacheKeepManager2 {
|
|
|
20597
20836
|
warmStopped: { at: now, reason }
|
|
20598
20837
|
});
|
|
20599
20838
|
}
|
|
20839
|
+
finishSessionTargets(sessionId, keep) {
|
|
20840
|
+
for (const target of [...this.targets.values()])
|
|
20841
|
+
if (target !== keep && (target.id === sessionId || target.policyState?.ownerSessionId === sessionId))
|
|
20842
|
+
try {
|
|
20843
|
+
this.untrack(target.id);
|
|
20844
|
+
} catch {}
|
|
20845
|
+
}
|
|
20600
20846
|
reportStop(target, reason, at) {
|
|
20847
|
+
if (this.targets.get(target.id) !== target)
|
|
20848
|
+
return;
|
|
20601
20849
|
const state = target.policyState;
|
|
20602
20850
|
if (!target.sourceWarm)
|
|
20603
|
-
this.setWarmingRecord(target.id, {
|
|
20604
|
-
|
|
20851
|
+
this.setWarmingRecord(target.id, {
|
|
20852
|
+
stopReason: reportStopReason(reason)
|
|
20853
|
+
});
|
|
20854
|
+
if (target.sourceWarm || !state || !state.hasWarmed && !this.restoredTargets.has(target) || this.reportedStops.has(state))
|
|
20605
20855
|
return;
|
|
20606
|
-
|
|
20856
|
+
this.reportedStops.add(state);
|
|
20857
|
+
reportSessionCacheWarmStopped(state.ownerSessionId, {
|
|
20607
20858
|
at,
|
|
20608
20859
|
reason: reportStopReason(reason)
|
|
20609
|
-
})
|
|
20610
|
-
this.reportedStops.add(state);
|
|
20860
|
+
});
|
|
20611
20861
|
}
|
|
20612
20862
|
evictOldestTarget(now, reason) {
|
|
20613
20863
|
const oldest = this.targets.values().next().value;
|
|
@@ -20626,7 +20876,16 @@ class CacheKeepManager2 {
|
|
|
20626
20876
|
continue;
|
|
20627
20877
|
}
|
|
20628
20878
|
if (now >= target.cacheExpiresAt) {
|
|
20629
|
-
|
|
20879
|
+
const reason = target.policyState?.planned ? "retry-window-ended" : "expired";
|
|
20880
|
+
logger2.info("cachekeep", "stopped warming session", {
|
|
20881
|
+
session: target.id,
|
|
20882
|
+
reason,
|
|
20883
|
+
stage: "prune",
|
|
20884
|
+
cacheExpiresAt: target.cacheExpiresAt,
|
|
20885
|
+
nextPrewarmAt: target.nextPrewarmAt,
|
|
20886
|
+
overdueMs: now - target.cacheExpiresAt
|
|
20887
|
+
});
|
|
20888
|
+
this.reportStop(target, reason, now);
|
|
20630
20889
|
this.targets.delete(id);
|
|
20631
20890
|
this.options.onTargetRemoved?.(id);
|
|
20632
20891
|
}
|
|
@@ -20652,10 +20911,10 @@ class CacheKeepManager2 {
|
|
|
20652
20911
|
}
|
|
20653
20912
|
const now = this.options.now?.() ?? Date.now();
|
|
20654
20913
|
const acceptedAt = input.acceptedAt ?? input.retained?.lastTouchAt ?? now;
|
|
20655
|
-
if (input.retained && input.retained.cacheExpiresAt <= now)
|
|
20656
|
-
return { tracked: false, reason: "cache expired" };
|
|
20657
20914
|
let bodyBytes;
|
|
20658
20915
|
const refuse = (reason, reasonCode) => {
|
|
20916
|
+
if (input.sessionId && !input.retained && !input.sourceWarm)
|
|
20917
|
+
this.finishSessionTargets(input.sessionId);
|
|
20659
20918
|
if (reasonCode === "body-budget")
|
|
20660
20919
|
logger2.warn("cachekeep", "tracking skipped", {
|
|
20661
20920
|
session: input.sessionId ?? null,
|
|
@@ -20684,18 +20943,27 @@ class CacheKeepManager2 {
|
|
|
20684
20943
|
previous = undefined;
|
|
20685
20944
|
}
|
|
20686
20945
|
const ownerSessionId = input.ownerSessionId ?? input.retained?.policyState?.ownerSessionId ?? input.sessionId;
|
|
20687
|
-
const
|
|
20946
|
+
const freshPolicy = readSessionCachePolicy(ownerSessionId, true);
|
|
20947
|
+
const restoredPlan = input.retained?.policyState?.planned === true;
|
|
20948
|
+
const policy = freshPolicy ?? (restoredPlan ? input.retained?.policyState?.policy ?? {
|
|
20949
|
+
keep_warm: "auto"
|
|
20950
|
+
} : null);
|
|
20688
20951
|
const planned = policy?.keep_warm !== undefined;
|
|
20952
|
+
const sessionId = input.sessionId;
|
|
20689
20953
|
const retire = (reason) => {
|
|
20690
20954
|
if (previous)
|
|
20691
20955
|
this.removeTarget(previous, reason, now);
|
|
20692
20956
|
return refuse(reason, reason);
|
|
20693
20957
|
};
|
|
20958
|
+
if (input.retained && input.retained.cacheExpiresAt <= now) {
|
|
20959
|
+
return { tracked: false, reason: "cache expired" };
|
|
20960
|
+
}
|
|
20961
|
+
if (restoredPlan && freshPolicy && freshPolicy.keep_warm === undefined)
|
|
20962
|
+
return retire("session-ended");
|
|
20694
20963
|
if (input.retained && (planned || isCacheKeepAlways(input.storage)) && input.retained.policyState?.needsRealRequest)
|
|
20695
20964
|
return retire("unsupported");
|
|
20696
|
-
if (!
|
|
20965
|
+
if (!input.retained && !policy && previous?.policyState?.planned)
|
|
20697
20966
|
return retire("session-ended");
|
|
20698
|
-
const sessionId = input.sessionId;
|
|
20699
20967
|
const keptOff = () => {
|
|
20700
20968
|
if (!previous && !input.sourceWarm)
|
|
20701
20969
|
this.recordWarmingOff(sessionId);
|
|
@@ -20748,6 +21016,7 @@ class CacheKeepManager2 {
|
|
|
20748
21016
|
}
|
|
20749
21017
|
const today = cacheKeepPeriodKey(input.storage, window, new Date(now));
|
|
20750
21018
|
this.pruneTargets(now, today);
|
|
21019
|
+
previous = this.targets.get(input.sessionId);
|
|
20751
21020
|
if (this.targets.has(input.sessionId))
|
|
20752
21021
|
this.targets.delete(input.sessionId);
|
|
20753
21022
|
this.stoppedSessions.delete(input.sessionId);
|
|
@@ -20777,15 +21046,18 @@ class CacheKeepManager2 {
|
|
|
20777
21046
|
dayKey: today,
|
|
20778
21047
|
oauthAccountId: input.oauthAccountId,
|
|
20779
21048
|
oauthAccountIdentity: input.oauthAccountIdentity,
|
|
21049
|
+
hostMetadata: input.hostMetadata,
|
|
20780
21050
|
accountStoragePath: input.accountStoragePath,
|
|
20781
21051
|
isSubagent: input.isSubagent ?? false,
|
|
20782
21052
|
policyState: input.retained?.policyState ? {
|
|
20783
21053
|
...input.retained.policyState,
|
|
20784
21054
|
warmCostSoFar: input.retained.policyState.warmCostSoFar + (input.retained.policyState.pendingWarmCost ?? 0),
|
|
20785
|
-
pendingWarmCost: undefined
|
|
21055
|
+
pendingWarmCost: undefined,
|
|
21056
|
+
...policy && { policy: structuredClone(policy) }
|
|
20786
21057
|
} : {
|
|
20787
21058
|
ownerSessionId,
|
|
20788
21059
|
planned,
|
|
21060
|
+
...policy && { policy: structuredClone(policy) },
|
|
20789
21061
|
lastRealRequestAt: acceptedAt,
|
|
20790
21062
|
warmsSinceLastRealRequest: 0,
|
|
20791
21063
|
warmCostSoFar: 0,
|
|
@@ -20793,11 +21065,23 @@ class CacheKeepManager2 {
|
|
|
20793
21065
|
},
|
|
20794
21066
|
...input.sourceWarm === true && { sourceWarm: true }
|
|
20795
21067
|
});
|
|
20796
|
-
this.pruneTargets(now, today);
|
|
20797
|
-
this.publishTrackedSessions();
|
|
20798
21068
|
const target = this.targets.get(input.sessionId);
|
|
20799
21069
|
if (!target)
|
|
20800
21070
|
return { tracked: false, reason: "evicted by cachekeep limits" };
|
|
21071
|
+
if (input.retained) {
|
|
21072
|
+
this.restoredTargets.add(target);
|
|
21073
|
+
if (restoredPlan && !freshPolicy && target.policyState) {
|
|
21074
|
+
this.restoringPolicies.add(target.policyState);
|
|
21075
|
+
if (!input.retained.policyState?.policy)
|
|
21076
|
+
logger2.info("cachekeep", "restored legacy planned policy as auto", {
|
|
21077
|
+
session: target.id
|
|
21078
|
+
});
|
|
21079
|
+
}
|
|
21080
|
+
}
|
|
21081
|
+
this.pruneTargets(now, today);
|
|
21082
|
+
this.publishTrackedSessions();
|
|
21083
|
+
if (this.targets.get(input.sessionId) !== target)
|
|
21084
|
+
return { tracked: false, reason: "evicted by cachekeep limits" };
|
|
20801
21085
|
if (input.acceptedUsage)
|
|
20802
21086
|
updateAcceptedUsage(target, input.bodyText, input.acceptedUsage);
|
|
20803
21087
|
if (planned) {
|
|
@@ -20844,15 +21128,12 @@ class CacheKeepManager2 {
|
|
|
20844
21128
|
if (!current)
|
|
20845
21129
|
this.immediateTargets.set(target.id, target);
|
|
20846
21130
|
try {
|
|
20847
|
-
|
|
20848
|
-
|
|
20849
|
-
|
|
21131
|
+
return await this.sendPrewarm(target, (receivedAt, result) => {
|
|
21132
|
+
if (current && this.isCurrentTarget(target)) {
|
|
21133
|
+
this.acceptWarm(current, result, receivedAt);
|
|
21134
|
+
this.scheduleDueTimer();
|
|
21135
|
+
}
|
|
20850
21136
|
});
|
|
20851
|
-
if (result.ok && current && this.isCurrentTarget(target)) {
|
|
20852
|
-
this.acceptWarm(current, result, acceptedAt ?? this.options.now?.() ?? Date.now());
|
|
20853
|
-
this.scheduleDueTimer();
|
|
20854
|
-
}
|
|
20855
|
-
return result;
|
|
20856
21137
|
} finally {
|
|
20857
21138
|
if (this.immediateTargets.get(target.id) === target)
|
|
20858
21139
|
this.immediateTargets.delete(target.id);
|
|
@@ -20861,17 +21142,25 @@ class CacheKeepManager2 {
|
|
|
20861
21142
|
tick() {
|
|
20862
21143
|
if (this.tickPromise)
|
|
20863
21144
|
return this.tickPromise;
|
|
21145
|
+
const lifetime = this.lifetime;
|
|
21146
|
+
const generation = this.schedulerGeneration;
|
|
20864
21147
|
let run;
|
|
20865
|
-
run = this.runTick().finally(() => {
|
|
21148
|
+
run = this.runTick(lifetime).finally(() => {
|
|
21149
|
+
this.ticks.delete(run);
|
|
20866
21150
|
if (this.tickPromise === run)
|
|
20867
21151
|
this.tickPromise = null;
|
|
20868
|
-
this.
|
|
21152
|
+
if (lifetime === this.lifetime && generation === this.schedulerGeneration)
|
|
21153
|
+
this.scheduleDueTimer();
|
|
20869
21154
|
});
|
|
20870
21155
|
this.tickPromise = run;
|
|
21156
|
+
this.ticks.add(run);
|
|
20871
21157
|
return run;
|
|
20872
21158
|
}
|
|
20873
|
-
async runTick() {
|
|
21159
|
+
async runTick(lifetime) {
|
|
21160
|
+
const generation = this.schedulerGeneration;
|
|
20874
21161
|
const loaded = await this.options.loadStorage();
|
|
21162
|
+
if (lifetime !== this.lifetime || generation !== this.schedulerGeneration)
|
|
21163
|
+
return;
|
|
20875
21164
|
const storage = loaded && this.options.resolveSettings ? this.options.resolveSettings(loaded) : loaded;
|
|
20876
21165
|
const window = getCacheKeepWindow(storage);
|
|
20877
21166
|
const now = this.options.now?.() ?? Date.now();
|
|
@@ -20889,49 +21178,58 @@ class CacheKeepManager2 {
|
|
|
20889
21178
|
}
|
|
20890
21179
|
logger2.debug("cachekeep", "fired", { targets: this.targets.size });
|
|
20891
21180
|
const targets = [...this.targets.values()].sort((a, b) => this.lastPrewarmStart(a) - this.lastPrewarmStart(b));
|
|
20892
|
-
|
|
21181
|
+
const warm = async (target) => {
|
|
21182
|
+
if (generation !== this.schedulerGeneration)
|
|
21183
|
+
return;
|
|
20893
21184
|
if (this.targets.get(target.id) !== target)
|
|
20894
|
-
|
|
21185
|
+
return;
|
|
21186
|
+
if (this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
|
|
21187
|
+
return;
|
|
20895
21188
|
const attemptAt = this.options.now?.() ?? Date.now();
|
|
20896
21189
|
const decision = this.policyDecision(target, attemptAt);
|
|
20897
21190
|
if (decision?.action === "stop") {
|
|
20898
21191
|
this.removeTarget(target, decision.reason, attemptAt);
|
|
20899
|
-
|
|
21192
|
+
return;
|
|
20900
21193
|
}
|
|
20901
21194
|
if (decision?.action === "wait") {
|
|
20902
21195
|
target.nextPrewarmAt = Math.max(target.nextPrewarmAt, decision.until);
|
|
20903
|
-
|
|
21196
|
+
return;
|
|
20904
21197
|
}
|
|
20905
21198
|
if (!target.policyState?.planned) {
|
|
20906
21199
|
const targetStorage = storage ? this.targetSettings(storage, target.bodyText) : storage;
|
|
20907
21200
|
if (!isCacheKeepHybridActive(targetStorage)) {
|
|
20908
21201
|
this.removeTarget(target, "cachekeep-hybrid-inactive", attemptAt);
|
|
20909
|
-
|
|
21202
|
+
return;
|
|
20910
21203
|
}
|
|
20911
21204
|
const targetToday = cacheKeepPeriodKey(targetStorage, window, new Date(attemptAt));
|
|
20912
21205
|
if (isCacheKeepAlways(targetStorage))
|
|
20913
21206
|
target.dayKey = "always";
|
|
20914
21207
|
if (!isCacheKeepActiveNow(targetStorage, new Date(attemptAt)) || target.dayKey !== targetToday) {
|
|
20915
21208
|
this.removeTarget(target, "schedule-period-ended", attemptAt);
|
|
20916
|
-
|
|
21209
|
+
return;
|
|
20917
21210
|
}
|
|
20918
21211
|
if (isCacheKeepAlways(targetStorage)) {
|
|
20919
21212
|
const count2 = this.countDecision(target);
|
|
20920
21213
|
if (count2?.action === "stop") {
|
|
20921
21214
|
this.removeTarget(target, count2.reason, attemptAt);
|
|
20922
|
-
|
|
21215
|
+
return;
|
|
20923
21216
|
}
|
|
20924
21217
|
}
|
|
20925
21218
|
}
|
|
20926
21219
|
if (target.nextPrewarmAt > attemptAt)
|
|
20927
|
-
|
|
21220
|
+
return;
|
|
20928
21221
|
if (attemptAt > this.lastPrewarmStart(target)) {
|
|
20929
|
-
this.removeTarget(target,
|
|
20930
|
-
|
|
21222
|
+
this.removeTarget(target, "retry-window-ended", attemptAt, {
|
|
21223
|
+
stage: "dispatch",
|
|
21224
|
+
overdueMs: attemptAt - this.lastPrewarmStart(target)
|
|
21225
|
+
});
|
|
21226
|
+
return;
|
|
20931
21227
|
}
|
|
20932
21228
|
try {
|
|
20933
21229
|
await this.prewarm(target, attemptAt);
|
|
20934
21230
|
} catch (error) {
|
|
21231
|
+
if (generation !== this.schedulerGeneration)
|
|
21232
|
+
return;
|
|
20935
21233
|
logger2.warn("cachekeep", "prewarm failed", {
|
|
20936
21234
|
session: target.id,
|
|
20937
21235
|
...classifyCacheKeepFailure(error, "send"),
|
|
@@ -20940,11 +21238,20 @@ class CacheKeepManager2 {
|
|
|
20940
21238
|
});
|
|
20941
21239
|
this.scheduleRetry(target, true);
|
|
20942
21240
|
} finally {
|
|
20943
|
-
if (this.targets.get(target.id) === target)
|
|
21241
|
+
if (generation === this.schedulerGeneration && this.targets.get(target.id) === target)
|
|
20944
21242
|
this.options.onTargetChanged?.(target);
|
|
20945
21243
|
}
|
|
20946
|
-
}
|
|
20947
|
-
|
|
21244
|
+
};
|
|
21245
|
+
let index = 0;
|
|
21246
|
+
await Promise.all(Array.from({ length: Math.min(4, targets.length) }, async () => {
|
|
21247
|
+
while (index < targets.length) {
|
|
21248
|
+
const target = targets[index++];
|
|
21249
|
+
if (target)
|
|
21250
|
+
await warm(target);
|
|
21251
|
+
}
|
|
21252
|
+
}));
|
|
21253
|
+
if (lifetime === this.lifetime && generation === this.schedulerGeneration)
|
|
21254
|
+
this.publishTrackedSessions();
|
|
20948
21255
|
}
|
|
20949
21256
|
targetSettings(storage, bodyText) {
|
|
20950
21257
|
if (!this.options.resolveSettings)
|
|
@@ -20969,7 +21276,10 @@ class CacheKeepManager2 {
|
|
|
20969
21276
|
const now = this.options.now?.() ?? Date.now();
|
|
20970
21277
|
const deadline = this.lastPrewarmStart(target);
|
|
20971
21278
|
if (now >= deadline) {
|
|
20972
|
-
this.removeTarget(target,
|
|
21279
|
+
this.removeTarget(target, "retry-window-ended", now, {
|
|
21280
|
+
stage: "retry",
|
|
21281
|
+
overdueMs: now - deadline
|
|
21282
|
+
});
|
|
20973
21283
|
return;
|
|
20974
21284
|
}
|
|
20975
21285
|
target.consecutiveFailures += 1;
|
|
@@ -20978,13 +21288,78 @@ class CacheKeepManager2 {
|
|
|
20978
21288
|
target.nextPrewarmAt = Math.min(now + delay3, deadline);
|
|
20979
21289
|
}
|
|
20980
21290
|
async sendPrewarm(target, onAccepted) {
|
|
21291
|
+
const generation = this.schedulerGeneration;
|
|
21292
|
+
const session = target.policyState?.ownerSessionId ?? target.id;
|
|
21293
|
+
if (this.realTurnBusy(session))
|
|
21294
|
+
return { ok: false, skipped: true, reason: "real-turn-in-flight" };
|
|
21295
|
+
let queued = false;
|
|
21296
|
+
while (this.sessionWarms.has(session)) {
|
|
21297
|
+
queued = true;
|
|
21298
|
+
await this.sessionWarms.get(session);
|
|
21299
|
+
if (generation !== this.schedulerGeneration)
|
|
21300
|
+
return { ok: false, skipped: true, reason: "scheduler-paused" };
|
|
21301
|
+
}
|
|
21302
|
+
if (!this.isCurrentTarget(target))
|
|
21303
|
+
return { ok: false, skipped: true, reason: "target-replaced" };
|
|
21304
|
+
if (this.realTurnBusy(session))
|
|
21305
|
+
return { ok: false, skipped: true, reason: "real-turn-in-flight" };
|
|
21306
|
+
const current = this.targets.get(target.id);
|
|
21307
|
+
if (queued && current && current.nextPrewarmAt > (this.options.now?.() ?? Date.now()))
|
|
21308
|
+
return { ok: false, skipped: true, reason: "already-warmed" };
|
|
21309
|
+
let acceptedAt;
|
|
21310
|
+
const sending = this.sendPrewarmAttempt(target, (receivedAt) => {
|
|
21311
|
+
acceptedAt = receivedAt;
|
|
21312
|
+
}).then((result) => {
|
|
21313
|
+
if (generation !== this.schedulerGeneration)
|
|
21314
|
+
return {
|
|
21315
|
+
ok: false,
|
|
21316
|
+
skipped: true,
|
|
21317
|
+
reason: "scheduler-paused"
|
|
21318
|
+
};
|
|
21319
|
+
if (result.ok && this.realTurnBusy(session))
|
|
21320
|
+
return {
|
|
21321
|
+
ok: false,
|
|
21322
|
+
skipped: true,
|
|
21323
|
+
reason: "real-turn-in-flight"
|
|
21324
|
+
};
|
|
21325
|
+
if (result.ok)
|
|
21326
|
+
onAccepted?.(acceptedAt ?? this.options.now?.() ?? Date.now(), result);
|
|
21327
|
+
return result;
|
|
21328
|
+
});
|
|
21329
|
+
this.sessionWarms.set(session, sending);
|
|
21330
|
+
this.warmRuns.add(sending);
|
|
21331
|
+
try {
|
|
21332
|
+
return await sending;
|
|
21333
|
+
} finally {
|
|
21334
|
+
this.warmRuns.delete(sending);
|
|
21335
|
+
if (this.sessionWarms.get(session) === sending)
|
|
21336
|
+
this.sessionWarms.delete(session);
|
|
21337
|
+
}
|
|
21338
|
+
}
|
|
21339
|
+
async sendPrewarmAttempt(target, onAccepted) {
|
|
21340
|
+
const generation = this.schedulerGeneration;
|
|
20981
21341
|
const remaining = target.cacheExpiresAt - (this.options.now?.() ?? Date.now()) - CACHE_KEEP_EXPIRY_SAFETY_MS;
|
|
20982
21342
|
const timeout = Math.min(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS, target.policyState?.planned || target.sourceWarm ? remaining : Infinity);
|
|
20983
21343
|
if (timeout <= 0)
|
|
20984
|
-
return { ok: false, refused: true, reason: "
|
|
21344
|
+
return { ok: false, refused: true, reason: "retry-window-ended" };
|
|
21345
|
+
const startedAt = this.options.now?.() ?? Date.now();
|
|
21346
|
+
const controller = new AbortController;
|
|
21347
|
+
this.warmControllers.set(controller, target.policyState?.ownerSessionId ?? target.id);
|
|
21348
|
+
let headersMs = null;
|
|
20985
21349
|
const attempt = {
|
|
20986
21350
|
id: ++this.nextPrewarmAttemptId,
|
|
20987
|
-
signal: AbortSignal.
|
|
21351
|
+
signal: AbortSignal.any([
|
|
21352
|
+
AbortSignal.timeout(timeout),
|
|
21353
|
+
controller.signal
|
|
21354
|
+
]),
|
|
21355
|
+
onResponseHeaders: () => {
|
|
21356
|
+
headersMs ??= (this.options.now?.() ?? Date.now()) - startedAt;
|
|
21357
|
+
}
|
|
21358
|
+
};
|
|
21359
|
+
const ensureActive = () => {
|
|
21360
|
+
if (generation !== this.schedulerGeneration || controller.signal.aborted)
|
|
21361
|
+
throw new CacheKeepWarmWait;
|
|
21362
|
+
attempt.signal.throwIfAborted();
|
|
20988
21363
|
};
|
|
20989
21364
|
let stage = "authorization";
|
|
20990
21365
|
let responseStatus;
|
|
@@ -21009,21 +21384,25 @@ class CacheKeepManager2 {
|
|
|
21009
21384
|
throw new CacheKeepWarmRefusal("routing-moved");
|
|
21010
21385
|
};
|
|
21011
21386
|
try {
|
|
21387
|
+
ensureActive();
|
|
21012
21388
|
checkRouting();
|
|
21013
21389
|
let bodyText = target.bodyText;
|
|
21014
21390
|
if (this.options.prepareBody) {
|
|
21015
21391
|
try {
|
|
21016
21392
|
bodyText = await this.options.prepareBody(bodyText, target);
|
|
21017
21393
|
} catch {
|
|
21394
|
+
ensureActive();
|
|
21018
21395
|
logger2.warn("cachekeep", "prepare body failed", {
|
|
21019
21396
|
session: target.id
|
|
21020
21397
|
});
|
|
21021
21398
|
}
|
|
21399
|
+
ensureActive();
|
|
21022
21400
|
}
|
|
21023
21401
|
const preparedTarget = { ...target, bodyText };
|
|
21024
21402
|
const prewarm = await buildCacheKeepPrewarmBody(bodyText, {
|
|
21025
21403
|
stripServerFallback: target.sourceWarm === true
|
|
21026
21404
|
});
|
|
21405
|
+
ensureActive();
|
|
21027
21406
|
if (!prewarm.ok)
|
|
21028
21407
|
return prewarm;
|
|
21029
21408
|
if (this.options.validatePrewarm) {
|
|
@@ -21036,6 +21415,7 @@ class CacheKeepManager2 {
|
|
|
21036
21415
|
} catch {
|
|
21037
21416
|
verdict = undefined;
|
|
21038
21417
|
}
|
|
21418
|
+
ensureActive();
|
|
21039
21419
|
if (!verdict?.ok) {
|
|
21040
21420
|
return {
|
|
21041
21421
|
ok: false,
|
|
@@ -21046,7 +21426,9 @@ class CacheKeepManager2 {
|
|
|
21046
21426
|
}
|
|
21047
21427
|
const fetchImpl = this.options.fetchForTarget?.(target) ?? this.options.fetchImpl ?? fetch;
|
|
21048
21428
|
const prewarmTarget = { ...preparedTarget, bodyText: prewarm.bodyText };
|
|
21429
|
+
ensureActive();
|
|
21049
21430
|
let headers = this.options.prepareHeaders ? await this.options.prepareHeaders(new Headers(target.headers), prewarmTarget, attempt) : new Headers(target.headers);
|
|
21431
|
+
ensureActive();
|
|
21050
21432
|
if (!headers) {
|
|
21051
21433
|
const summary2 = summarizePrewarmProviderError({
|
|
21052
21434
|
failure: "credential_unavailable"
|
|
@@ -21064,6 +21446,7 @@ class CacheKeepManager2 {
|
|
|
21064
21446
|
stage = "send";
|
|
21065
21447
|
let response;
|
|
21066
21448
|
const send = async (attemptHeaders) => {
|
|
21449
|
+
ensureActive();
|
|
21067
21450
|
if (!this.isCurrentTarget(target))
|
|
21068
21451
|
throw new CacheKeepWarmRefusal("stopped");
|
|
21069
21452
|
checkRouting();
|
|
@@ -21071,30 +21454,41 @@ class CacheKeepManager2 {
|
|
|
21071
21454
|
if (!this.options.deferWarmReservation)
|
|
21072
21455
|
await this.reserveWarmDispatch(target);
|
|
21073
21456
|
}
|
|
21074
|
-
|
|
21457
|
+
ensureActive();
|
|
21075
21458
|
const scope = createProviderErrorResponseScope(cacheKeepSentCredentials(attemptHeaders), "http");
|
|
21076
21459
|
try {
|
|
21077
|
-
const dispatch = () =>
|
|
21078
|
-
|
|
21079
|
-
|
|
21080
|
-
|
|
21081
|
-
|
|
21082
|
-
|
|
21460
|
+
const dispatch = () => {
|
|
21461
|
+
ensureActive();
|
|
21462
|
+
return fetchImpl(target.url, {
|
|
21463
|
+
method: "POST",
|
|
21464
|
+
headers: attemptHeaders,
|
|
21465
|
+
body: prewarm.bodyText,
|
|
21466
|
+
signal: attempt.signal
|
|
21467
|
+
});
|
|
21468
|
+
};
|
|
21083
21469
|
let billing;
|
|
21084
21470
|
try {
|
|
21085
21471
|
billing = this.options.billingRequest?.(prewarmTarget, attempt);
|
|
21086
21472
|
} catch {}
|
|
21087
21473
|
const sent = await (billing ? withAnthropicBilling(billing, dispatch) : dispatch());
|
|
21474
|
+
try {
|
|
21475
|
+
ensureActive();
|
|
21476
|
+
} catch (error) {
|
|
21477
|
+
await sent.body?.cancel().catch(() => {});
|
|
21478
|
+
throw error;
|
|
21479
|
+
}
|
|
21480
|
+
headersMs ??= (this.options.now?.() ?? Date.now()) - startedAt;
|
|
21088
21481
|
if (!sent.ok && this.isCurrentTarget(target) && target.policyState) {
|
|
21089
21482
|
const state = target.policyState;
|
|
21090
21483
|
const cost = this.admittedWarmCosts.get(state) ?? 0;
|
|
21091
21484
|
target.policyState.pendingWarmCost = Math.max(0, (target.policyState.pendingWarmCost ?? 0) - cost) || undefined;
|
|
21092
21485
|
this.admittedWarmCosts.delete(state);
|
|
21093
21486
|
await this.options.settleWarm?.(target);
|
|
21487
|
+
ensureActive();
|
|
21094
21488
|
}
|
|
21095
21489
|
return scope.redactResponse(sent);
|
|
21096
21490
|
} catch (error) {
|
|
21097
|
-
if (error instanceof CacheKeepWarmRefusal || nativeAccountRefusal(error)) {
|
|
21491
|
+
if (error instanceof CacheKeepWarmRefusal || isCacheKeepWarmWait(error) || nativeAccountRefusal(error)) {
|
|
21098
21492
|
scope.dispose();
|
|
21099
21493
|
throw error;
|
|
21100
21494
|
}
|
|
@@ -21103,6 +21497,7 @@ class CacheKeepManager2 {
|
|
|
21103
21497
|
}
|
|
21104
21498
|
};
|
|
21105
21499
|
response = await send(headers);
|
|
21500
|
+
ensureActive();
|
|
21106
21501
|
if (response.status === 401 && !attempt.signal?.aborted && this.options.retryOnUnauthorized) {
|
|
21107
21502
|
let rotatedHeaders;
|
|
21108
21503
|
try {
|
|
@@ -21113,28 +21508,34 @@ class CacheKeepManager2 {
|
|
|
21113
21508
|
attempt
|
|
21114
21509
|
});
|
|
21115
21510
|
} catch (error) {
|
|
21511
|
+
ensureActive();
|
|
21116
21512
|
if (error instanceof NativeAccountRefusal) {
|
|
21117
21513
|
await response.body?.cancel().catch(() => {});
|
|
21514
|
+
ensureActive();
|
|
21118
21515
|
throw error;
|
|
21119
21516
|
}
|
|
21120
21517
|
}
|
|
21518
|
+
ensureActive();
|
|
21121
21519
|
if (rotatedHeaders && !attempt.signal?.aborted) {
|
|
21122
21520
|
rotatedHeaders.delete("content-length");
|
|
21123
21521
|
rotatedHeaders.delete("transfer-encoding");
|
|
21124
21522
|
await response.body?.cancel().catch(() => {});
|
|
21523
|
+
ensureActive();
|
|
21125
21524
|
headers = rotatedHeaders;
|
|
21126
21525
|
response = await send(headers);
|
|
21526
|
+
ensureActive();
|
|
21127
21527
|
}
|
|
21128
21528
|
}
|
|
21129
21529
|
stage = "response";
|
|
21130
21530
|
responseStatus = response.status;
|
|
21131
21531
|
const receivedAt = this.options.now?.() ?? Date.now();
|
|
21132
21532
|
const raw = await response.text();
|
|
21133
|
-
|
|
21533
|
+
ensureActive();
|
|
21134
21534
|
let data = null;
|
|
21135
21535
|
try {
|
|
21136
21536
|
data = raw ? JSON.parse(raw) : null;
|
|
21137
21537
|
} catch {}
|
|
21538
|
+
ensureActive();
|
|
21138
21539
|
const summary = response.ok ? undefined : summarizePrewarmProviderError({ status: response.status, body: raw });
|
|
21139
21540
|
try {
|
|
21140
21541
|
await this.options.onResponse?.({
|
|
@@ -21146,6 +21547,7 @@ class CacheKeepManager2 {
|
|
|
21146
21547
|
attempt
|
|
21147
21548
|
});
|
|
21148
21549
|
} catch {}
|
|
21550
|
+
ensureActive();
|
|
21149
21551
|
try {
|
|
21150
21552
|
const dumpHandle = await dumpDirectRequest({
|
|
21151
21553
|
affinity: target.id,
|
|
@@ -21157,14 +21559,17 @@ class CacheKeepManager2 {
|
|
|
21157
21559
|
headers,
|
|
21158
21560
|
tag: "cachekeep"
|
|
21159
21561
|
});
|
|
21562
|
+
ensureActive();
|
|
21160
21563
|
await dumpResponseArtifact(dumpHandle, {
|
|
21161
21564
|
status: response.status,
|
|
21162
21565
|
message: data,
|
|
21163
21566
|
...summary && { provider_error: summary.provider_error }
|
|
21164
21567
|
});
|
|
21165
21568
|
} catch {
|
|
21569
|
+
ensureActive();
|
|
21166
21570
|
logger2.debug("cachekeep", "dump failed", { session: target.id });
|
|
21167
21571
|
}
|
|
21572
|
+
ensureActive();
|
|
21168
21573
|
if (summary) {
|
|
21169
21574
|
return {
|
|
21170
21575
|
ok: false,
|
|
@@ -21182,6 +21587,10 @@ class CacheKeepManager2 {
|
|
|
21182
21587
|
...usage && { usage }
|
|
21183
21588
|
};
|
|
21184
21589
|
} catch (error) {
|
|
21590
|
+
if (controller.signal.aborted || generation !== this.schedulerGeneration)
|
|
21591
|
+
return { ok: false, skipped: true, reason: "warm-cancelled" };
|
|
21592
|
+
if (isCacheKeepWarmWait(error))
|
|
21593
|
+
return { ok: false, skipped: true, reason: "wait" };
|
|
21185
21594
|
if (error instanceof CacheKeepWarmRefusal)
|
|
21186
21595
|
return { ok: false, refused: true, reason: error.reason };
|
|
21187
21596
|
const failure = classifyCacheKeepFailure(error, stage, responseStatus);
|
|
@@ -21202,17 +21611,31 @@ class CacheKeepManager2 {
|
|
|
21202
21611
|
transient: true
|
|
21203
21612
|
};
|
|
21204
21613
|
} finally {
|
|
21614
|
+
this.warmControllers.delete(controller);
|
|
21615
|
+
try {
|
|
21616
|
+
logger2.info("cachekeep", "prewarm timing", {
|
|
21617
|
+
session: target.id,
|
|
21618
|
+
stage,
|
|
21619
|
+
headersMs,
|
|
21620
|
+
totalMs: (this.options.now?.() ?? Date.now()) - startedAt
|
|
21621
|
+
});
|
|
21622
|
+
} catch {}
|
|
21205
21623
|
try {
|
|
21206
21624
|
await this.options.onComplete?.({ target, attempt });
|
|
21207
21625
|
} catch {}
|
|
21208
21626
|
}
|
|
21209
21627
|
}
|
|
21210
21628
|
async prewarm(target, now) {
|
|
21211
|
-
|
|
21212
|
-
const result = await this.sendPrewarm(target, (receivedAt) => {
|
|
21213
|
-
|
|
21629
|
+
const generation = this.schedulerGeneration;
|
|
21630
|
+
const result = await this.sendPrewarm(target, (receivedAt, accepted) => {
|
|
21631
|
+
if (this.targets.get(target.id) === target)
|
|
21632
|
+
this.acceptWarm(target, accepted, receivedAt);
|
|
21214
21633
|
});
|
|
21634
|
+
if (generation !== this.schedulerGeneration)
|
|
21635
|
+
return;
|
|
21215
21636
|
if (!result.ok) {
|
|
21637
|
+
if (result.refused !== true && result.skipped)
|
|
21638
|
+
return;
|
|
21216
21639
|
if (result.refused === true) {
|
|
21217
21640
|
this.removeTarget(target, result.reason, now, {
|
|
21218
21641
|
detail: "prewarm refused before send"
|
|
@@ -21241,10 +21664,6 @@ class CacheKeepManager2 {
|
|
|
21241
21664
|
}
|
|
21242
21665
|
return;
|
|
21243
21666
|
}
|
|
21244
|
-
if (this.targets.get(target.id) !== target)
|
|
21245
|
-
return;
|
|
21246
|
-
acceptedAt ??= this.options.now?.() ?? Date.now();
|
|
21247
|
-
this.acceptWarm(target, result, acceptedAt);
|
|
21248
21667
|
}
|
|
21249
21668
|
acceptWarm(target, result, acceptedAt) {
|
|
21250
21669
|
const state = target.policyState;
|
|
@@ -21303,8 +21722,8 @@ import { uptime } from "node:os";
|
|
|
21303
21722
|
import { basename as basename13, dirname as dirname20, join as join25 } from "node:path";
|
|
21304
21723
|
|
|
21305
21724
|
// src/native-lock-observer.ts
|
|
21306
|
-
import { AsyncLocalStorage as
|
|
21307
|
-
var detachedLocks = new
|
|
21725
|
+
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
|
|
21726
|
+
var detachedLocks = new AsyncLocalStorage4;
|
|
21308
21727
|
function withDetachedNativeLocks(work) {
|
|
21309
21728
|
return detachedLocks.run(true, work);
|
|
21310
21729
|
}
|
|
@@ -21433,9 +21852,9 @@ function recordIdentityIn(tx, id, identity4) {
|
|
|
21433
21852
|
return disableIdentityDuplicates(tx, identity4);
|
|
21434
21853
|
}
|
|
21435
21854
|
// ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
|
|
21436
|
-
import { AsyncLocalStorage as
|
|
21437
|
-
var insideHook = new
|
|
21438
|
-
var insideCodec = new
|
|
21855
|
+
import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
|
|
21856
|
+
var insideHook = new AsyncLocalStorage5;
|
|
21857
|
+
var insideCodec = new AsyncLocalStorage5;
|
|
21439
21858
|
function assertNotInsideHook(operation) {
|
|
21440
21859
|
if (insideHook.getStore() !== undefined)
|
|
21441
21860
|
throw new PoolReentryError(operation);
|
|
@@ -24517,14 +24936,17 @@ function settingsRefusal(message) {
|
|
|
24517
24936
|
});
|
|
24518
24937
|
}
|
|
24519
24938
|
var settingsCache = new FileReadCache;
|
|
24520
|
-
|
|
24521
|
-
|
|
24522
|
-
|
|
24939
|
+
function readPoolSettings(rt) {
|
|
24940
|
+
return readPoolSettingsAt(rt.ctx.configPath);
|
|
24941
|
+
}
|
|
24942
|
+
async function readPoolSettingsAt(configPath) {
|
|
24943
|
+
const read = async ([path2 = configPath] = []) => {
|
|
24944
|
+
const result2 = await readPoolConfig(path2);
|
|
24523
24945
|
if (result2.status === "error")
|
|
24524
24946
|
return { status: "error", file: "config", reason: result2.reason };
|
|
24525
24947
|
return { status: result2.status, settings: settingsOf(result2.config) };
|
|
24526
24948
|
};
|
|
24527
|
-
const result = windowsPrivateFiles ? await read() : await settingsCache.read([
|
|
24949
|
+
const result = windowsPrivateFiles ? await read() : await settingsCache.read([configPath], read);
|
|
24528
24950
|
return structuredClone(result);
|
|
24529
24951
|
}
|
|
24530
24952
|
async function updatePoolSettings(rt, mutator, options = {}) {
|
|
@@ -25379,20 +25801,6 @@ async function drainNativePoolStores(statePaths) {
|
|
|
25379
25801
|
function createNativePoolStore(options) {
|
|
25380
25802
|
return trackStore(options.paths.state, openNativePoolStore(options));
|
|
25381
25803
|
}
|
|
25382
|
-
var exactSettingsReaders = new Map;
|
|
25383
|
-
function readNativePoolSettingsAt(configPath, quota) {
|
|
25384
|
-
let reader = exactSettingsReaders.get(configPath);
|
|
25385
|
-
if (!reader) {
|
|
25386
|
-
reader = openPoolStore({
|
|
25387
|
-
provider: "anthropic",
|
|
25388
|
-
configPath,
|
|
25389
|
-
statePath: configPath,
|
|
25390
|
-
quota
|
|
25391
|
-
});
|
|
25392
|
-
exactSettingsReaders.set(configPath, reader);
|
|
25393
|
-
}
|
|
25394
|
-
return reader.readSettings();
|
|
25395
|
-
}
|
|
25396
25804
|
function openNativePoolStore(options) {
|
|
25397
25805
|
const store = openPoolStore({
|
|
25398
25806
|
provider: "anthropic",
|
|
@@ -31355,6 +31763,7 @@ function record12(target, pluginVersion) {
|
|
|
31355
31763
|
policyState: {
|
|
31356
31764
|
ownerSessionId: target.policyState.ownerSessionId,
|
|
31357
31765
|
planned: target.policyState.planned,
|
|
31766
|
+
policy: target.policyState.policy,
|
|
31358
31767
|
lastRealRequestAt: target.policyState.lastRealRequestAt,
|
|
31359
31768
|
lastWarmAt: target.policyState.lastWarmAt,
|
|
31360
31769
|
warmsSinceLastRealRequest: target.policyState.warmsSinceLastRealRequest,
|
|
@@ -31388,13 +31797,39 @@ function invalidReason(value, name, now) {
|
|
|
31388
31797
|
return "format";
|
|
31389
31798
|
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))
|
|
31390
31799
|
return "invalid";
|
|
31391
|
-
if (value.cacheExpiresAt <= now)
|
|
31392
|
-
return "expired";
|
|
31393
31800
|
const state = value.policyState;
|
|
31394
31801
|
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))))
|
|
31395
31802
|
return "invalid";
|
|
31803
|
+
if (state?.policy !== undefined && !validSavedPolicy(state.policy))
|
|
31804
|
+
return "invalid";
|
|
31396
31805
|
if (sanitizedBody(value.bodyText) !== value.bodyText)
|
|
31397
31806
|
return "invalid";
|
|
31807
|
+
if (value.cacheExpiresAt <= now)
|
|
31808
|
+
return "expired";
|
|
31809
|
+
}
|
|
31810
|
+
function validSavedPolicy(value) {
|
|
31811
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
31812
|
+
return false;
|
|
31813
|
+
const policy = value;
|
|
31814
|
+
if (policy.ttl !== undefined && !["none", "short", "long"].includes(String(policy.ttl)))
|
|
31815
|
+
return false;
|
|
31816
|
+
if (policy.keep_warm !== undefined && !["off", "auto", "always", "hours"].includes(String(policy.keep_warm)))
|
|
31817
|
+
return false;
|
|
31818
|
+
if (policy.keep_warm !== "hours")
|
|
31819
|
+
return policy.hours === undefined;
|
|
31820
|
+
const hours = policy.hours;
|
|
31821
|
+
if (!hours || typeof hours !== "object" || Array.isArray(hours))
|
|
31822
|
+
return false;
|
|
31823
|
+
if (![hours.from, hours.to].every((time4) => typeof time4 === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(time4)))
|
|
31824
|
+
return false;
|
|
31825
|
+
if (typeof hours.tz !== "string" || !hours.tz)
|
|
31826
|
+
return false;
|
|
31827
|
+
try {
|
|
31828
|
+
new Intl.DateTimeFormat("en-GB", { timeZone: hours.tz });
|
|
31829
|
+
return true;
|
|
31830
|
+
} catch {
|
|
31831
|
+
return false;
|
|
31832
|
+
}
|
|
31398
31833
|
}
|
|
31399
31834
|
|
|
31400
31835
|
class CacheKeepStore {
|
|
@@ -31465,7 +31900,7 @@ class CacheKeepStore {
|
|
|
31465
31900
|
await action();
|
|
31466
31901
|
}).catch(() => this.writeFailed());
|
|
31467
31902
|
}
|
|
31468
|
-
async load(now, accept, claim) {
|
|
31903
|
+
async load(now, accept, claim, guard) {
|
|
31469
31904
|
await this.chain;
|
|
31470
31905
|
if (!await this.directoryReady())
|
|
31471
31906
|
return;
|
|
@@ -31494,7 +31929,17 @@ class CacheKeepStore {
|
|
|
31494
31929
|
continue;
|
|
31495
31930
|
const path2 = join27(directory, name);
|
|
31496
31931
|
let reason = "unreadable";
|
|
31932
|
+
let entry2;
|
|
31933
|
+
const permitted = async () => {
|
|
31934
|
+
try {
|
|
31935
|
+
return (!guard || await guard(name.slice(0, 64))) && (!release2?.canRemove || await release2.canRemove());
|
|
31936
|
+
} catch {
|
|
31937
|
+
return false;
|
|
31938
|
+
}
|
|
31939
|
+
};
|
|
31497
31940
|
try {
|
|
31941
|
+
if (!await permitted())
|
|
31942
|
+
continue;
|
|
31498
31943
|
if (TEMP.test(name)) {
|
|
31499
31944
|
reason = "unfinished-write";
|
|
31500
31945
|
throw new Error("Unfinished write");
|
|
@@ -31517,9 +31962,16 @@ class CacheKeepStore {
|
|
|
31517
31962
|
maxOutputLength: MAX_RECORD_BYTES
|
|
31518
31963
|
});
|
|
31519
31964
|
reason = "invalid";
|
|
31520
|
-
|
|
31965
|
+
entry2 = JSON.parse(raw.toString("utf8"));
|
|
31521
31966
|
const invalid3 = invalidReason(entry2, name, now);
|
|
31522
|
-
|
|
31967
|
+
if (invalid3 && invalid3 !== "expired") {
|
|
31968
|
+
reason = invalid3;
|
|
31969
|
+
throw new Error("Invalid restart file");
|
|
31970
|
+
}
|
|
31971
|
+
const acceptance = accept(entry2);
|
|
31972
|
+
if (acceptance === undefined)
|
|
31973
|
+
continue;
|
|
31974
|
+
const accepted = invalid3 ?? acceptance;
|
|
31523
31975
|
if (accepted !== true && accepted !== undefined) {
|
|
31524
31976
|
reason = accepted || "invalid";
|
|
31525
31977
|
throw new Error("Stale restart file");
|
|
@@ -31527,7 +31979,10 @@ class CacheKeepStore {
|
|
|
31527
31979
|
if (accepted === true) {
|
|
31528
31980
|
if (directory !== this.directory) {
|
|
31529
31981
|
try {
|
|
31530
|
-
|
|
31982
|
+
const adopted = entry2;
|
|
31983
|
+
const migrating = this.chain.then(() => this.writeEntry(adopted));
|
|
31984
|
+
this.chain = migrating.catch(() => this.writeFailed());
|
|
31985
|
+
await migrating;
|
|
31531
31986
|
} catch {
|
|
31532
31987
|
this.refuse();
|
|
31533
31988
|
return;
|
|
@@ -31537,12 +31992,17 @@ class CacheKeepStore {
|
|
|
31537
31992
|
restored++;
|
|
31538
31993
|
}
|
|
31539
31994
|
} catch {
|
|
31540
|
-
|
|
31541
|
-
|
|
31542
|
-
|
|
31543
|
-
|
|
31544
|
-
|
|
31545
|
-
|
|
31995
|
+
this.chain = this.chain.then(async () => {
|
|
31996
|
+
if (!await permitted())
|
|
31997
|
+
return;
|
|
31998
|
+
await rm8(path2, { force: true });
|
|
31999
|
+
logger2.debug("cachekeep", "restart record dropped", {
|
|
32000
|
+
file: name,
|
|
32001
|
+
reason
|
|
32002
|
+
});
|
|
32003
|
+
dropped++;
|
|
32004
|
+
}).catch(() => this.writeFailed());
|
|
32005
|
+
await this.chain;
|
|
31546
32006
|
} finally {
|
|
31547
32007
|
await release2?.();
|
|
31548
32008
|
}
|
|
@@ -41931,7 +42391,7 @@ function buildNativeAccountRuntime(options, env, runtimeSettings) {
|
|
|
41931
42391
|
async getRelayConfig() {
|
|
41932
42392
|
const { mode, paths: paths3, store: store2 } = await selectedStorage();
|
|
41933
42393
|
const { location, files } = await relayLocation.resolve(mode);
|
|
41934
|
-
const readSettings = files ? () =>
|
|
42394
|
+
const readSettings = files ? () => readPoolSettingsAt(files.config) : () => store2.readSettings();
|
|
41935
42395
|
const runtimeFile = files ? files.runtime : paths3.runtime;
|
|
41936
42396
|
for (let attempt = 0;attempt < 4; attempt++) {
|
|
41937
42397
|
if (attempt)
|
|
@@ -52251,6 +52711,7 @@ export {
|
|
|
52251
52711
|
writeDumpFile,
|
|
52252
52712
|
withSessionCacheReportHandoff,
|
|
52253
52713
|
withNativeLock,
|
|
52714
|
+
withCacheKeepRealTurn,
|
|
52254
52715
|
withAnthropicBilling,
|
|
52255
52716
|
withAbortableFetch,
|
|
52256
52717
|
warnRelayProxyRefused,
|
|
@@ -52354,6 +52815,7 @@ export {
|
|
|
52354
52815
|
requireNoSupervisedAuthContentSnapshot,
|
|
52355
52816
|
requireAnthropicOAuthOrigin,
|
|
52356
52817
|
requestSignal,
|
|
52818
|
+
requestShortestCacheLifetimeMs,
|
|
52357
52819
|
requestGzipPadding,
|
|
52358
52820
|
requestCacheLifetimeMs,
|
|
52359
52821
|
reportSessionCacheWarmStopped,
|
|
@@ -52387,7 +52849,6 @@ export {
|
|
|
52387
52849
|
readRelocationPointer,
|
|
52388
52850
|
readPeerLegacySettingsProtection,
|
|
52389
52851
|
readOwnLegacySettingsProtection,
|
|
52390
|
-
readNativePoolSettingsAt,
|
|
52391
52852
|
readNativeMigrationJournal,
|
|
52392
52853
|
readNativeHostAuthKind,
|
|
52393
52854
|
readNativeEnrollmentMode,
|
|
@@ -52515,6 +52976,7 @@ export {
|
|
|
52515
52976
|
isStateLayoutRefusalCode,
|
|
52516
52977
|
isSseCandidateFrame,
|
|
52517
52978
|
isSettingsImportPending,
|
|
52979
|
+
isSessionCacheWarmStopReason,
|
|
52518
52980
|
isServerFallbackUsageMarker,
|
|
52519
52981
|
isSeparateSettingsInstall,
|
|
52520
52982
|
isSecretKey,
|
|
@@ -52551,6 +53013,7 @@ export {
|
|
|
52551
53013
|
isClaudeFableOrMythos5Model,
|
|
52552
53014
|
isClaudeFableOrMythos51Model,
|
|
52553
53015
|
isClaudeFable51Model,
|
|
53016
|
+
isCacheKeepWarmWait,
|
|
52554
53017
|
isCacheKeepSubagentsEnabled,
|
|
52555
53018
|
isCacheKeepPersistentlyEnabled,
|
|
52556
53019
|
isCacheKeepHybridActive,
|
|
@@ -52688,6 +53151,7 @@ export {
|
|
|
52688
53151
|
custodyTombstoneOAuth,
|
|
52689
53152
|
custodyTombstoneKey,
|
|
52690
53153
|
custodyStatusLabel,
|
|
53154
|
+
currentCacheKeepRealTurn,
|
|
52691
53155
|
createWindowsOwnerOnly,
|
|
52692
53156
|
createStringPatch,
|
|
52693
53157
|
createStickyNoRouteResponse,
|