@cortexkit/anthropic-auth-core 2.13.1 → 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/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"
|
|
@@ -14258,6 +14259,7 @@ function executeCache1hCommand(input) {
|
|
|
14258
14259
|
`);
|
|
14259
14260
|
}
|
|
14260
14261
|
// src/cachekeep.ts
|
|
14262
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
14261
14263
|
import { createHash as createHash9 } from "node:crypto";
|
|
14262
14264
|
|
|
14263
14265
|
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/decision.js
|
|
@@ -14274,7 +14276,7 @@ function withinHours(hours, at) {
|
|
|
14274
14276
|
return hours.from < hours.to ? time >= hours.from && time < hours.to : time >= hours.from || time < hours.to;
|
|
14275
14277
|
}
|
|
14276
14278
|
function decideCacheKeep(input) {
|
|
14277
|
-
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;
|
|
14278
14280
|
if (mode === "off")
|
|
14279
14281
|
return { action: "stop", reason: "unsupported" };
|
|
14280
14282
|
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
@@ -14286,10 +14288,11 @@ function decideCacheKeep(input) {
|
|
|
14286
14288
|
return { action: "stop", reason: "cost-cap" };
|
|
14287
14289
|
const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
|
|
14288
14290
|
const expiresAt = last + ttlMs;
|
|
14289
|
-
const
|
|
14291
|
+
const lead = Math.min(Number.isFinite(leadMs) && leadMs > 0 ? leadMs : 30000, ttlMs / 2);
|
|
14292
|
+
const due = expiresAt - lead;
|
|
14290
14293
|
const at = Math.max(now, due);
|
|
14291
14294
|
if (at >= expiresAt - Math.min(5000, ttlMs / 10)) {
|
|
14292
|
-
return { action: "stop", reason: "
|
|
14295
|
+
return { action: "stop", reason: "deadline-missed" };
|
|
14293
14296
|
}
|
|
14294
14297
|
if (mode === "hours" && (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
|
|
14295
14298
|
return { action: "stop", reason: "outside-hours" };
|
|
@@ -14383,6 +14386,7 @@ class CacheKeepManager {
|
|
|
14383
14386
|
log;
|
|
14384
14387
|
ttlMs;
|
|
14385
14388
|
leadMs;
|
|
14389
|
+
planLeadMs;
|
|
14386
14390
|
maxIdleWarmMs;
|
|
14387
14391
|
maxSubagentIdleMs;
|
|
14388
14392
|
tickIntervalMs;
|
|
@@ -14408,6 +14412,7 @@ class CacheKeepManager {
|
|
|
14408
14412
|
this.ttlMs = positive(options.ttlMs, DEFAULT_TTL_MS);
|
|
14409
14413
|
this.tickIntervalMs = positive(options.tickIntervalMs, DEFAULT_TICK_INTERVAL_MS);
|
|
14410
14414
|
this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15000);
|
|
14415
|
+
this.planLeadMs = options.planLeadMs;
|
|
14411
14416
|
this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
|
|
14412
14417
|
this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
|
|
14413
14418
|
this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
|
|
@@ -14628,7 +14633,7 @@ class CacheKeepManager {
|
|
|
14628
14633
|
cacheExpiresAt: target.cacheExpiresAt,
|
|
14629
14634
|
failures: target.failures
|
|
14630
14635
|
});
|
|
14631
|
-
this.drop(sessionKey, target.plan ? "
|
|
14636
|
+
this.drop(sessionKey, target.plan ? "deadline-missed" : "expired");
|
|
14632
14637
|
return true;
|
|
14633
14638
|
}
|
|
14634
14639
|
isCurrent(sessionKey, target) {
|
|
@@ -14689,6 +14694,7 @@ class CacheKeepManager {
|
|
|
14689
14694
|
...plan.mode === "hours" ? { mode: plan.mode, hours: plan.hours } : { mode: plan.mode },
|
|
14690
14695
|
now: this.now(),
|
|
14691
14696
|
ttlMs: target.ttlMs,
|
|
14697
|
+
...this.planLeadMs !== undefined ? { leadMs: this.planLeadMs } : {},
|
|
14692
14698
|
lastRealRequestAt: target.lastRealRequestAt,
|
|
14693
14699
|
lastWarmAt: target.lastWarmedAt,
|
|
14694
14700
|
warmsSinceLastRealRequest: target.warmCount,
|
|
@@ -19786,6 +19792,9 @@ function withSessionCacheReportHandoff(work) {
|
|
|
19786
19792
|
function reportSessionCacheTouch(sessionId, input) {
|
|
19787
19793
|
detachReport2(() => reportCacheTouch(sessionId, input), input.source === "response", input.source === "warm");
|
|
19788
19794
|
}
|
|
19795
|
+
function isSessionCacheWarmStopReason(value) {
|
|
19796
|
+
return isCacheWarmStopReason(value);
|
|
19797
|
+
}
|
|
19789
19798
|
function reportSessionCacheWarmStopped(sessionId, input) {
|
|
19790
19799
|
return detachReport2(() => reportCacheWarmStopped(sessionId, input));
|
|
19791
19800
|
}
|
|
@@ -19874,7 +19883,9 @@ var CLAUDE_CACHE_KEEP_COMMAND_NAME = "claude-cachekeep";
|
|
|
19874
19883
|
var CACHE_KEEP_TTL_MS = 60 * 60000;
|
|
19875
19884
|
var CACHE_KEEP_PREWARM_LEAD_MS = 5 * 60000;
|
|
19876
19885
|
function replayPrewarmLeadMs(ttlMs, planned) {
|
|
19877
|
-
if (
|
|
19886
|
+
if (planned)
|
|
19887
|
+
return Math.min(CACHE_KEEP_PREWARM_LEAD_MS, ttlMs / 2);
|
|
19888
|
+
if (ttlMs === CACHE_KEEP_TTL_MS)
|
|
19878
19889
|
return CACHE_KEEP_PREWARM_LEAD_MS;
|
|
19879
19890
|
return Math.min(30000, ttlMs / 2);
|
|
19880
19891
|
}
|
|
@@ -20139,6 +20150,7 @@ function stopReason(reason) {
|
|
|
20139
20150
|
case "schedule-period-ended":
|
|
20140
20151
|
return "schedule";
|
|
20141
20152
|
case "retry-window-ended":
|
|
20153
|
+
case "deadline-missed":
|
|
20142
20154
|
return "retries-exhausted";
|
|
20143
20155
|
case "cachekeep-hybrid-inactive":
|
|
20144
20156
|
return "disabled";
|
|
@@ -20151,34 +20163,22 @@ function stopReason(reason) {
|
|
|
20151
20163
|
}
|
|
20152
20164
|
}
|
|
20153
20165
|
function reportStopReason(reason) {
|
|
20166
|
+
if (isSessionCacheWarmStopReason(reason))
|
|
20167
|
+
return reason;
|
|
20154
20168
|
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
20169
|
case "schedule":
|
|
20171
20170
|
case "schedule-period-ended":
|
|
20172
20171
|
return "outside-hours";
|
|
20172
|
+
case "stopped":
|
|
20173
20173
|
case "session-forgotten":
|
|
20174
20174
|
return "session-ended";
|
|
20175
20175
|
case "retry-window-ended":
|
|
20176
|
-
|
|
20176
|
+
case "retries-exhausted":
|
|
20177
|
+
case "expired":
|
|
20178
|
+
return "deadline-missed";
|
|
20179
|
+
case "idle":
|
|
20177
20180
|
case "source-warm-idle-cap":
|
|
20178
20181
|
return "cost-cap";
|
|
20179
|
-
case "credential-changed":
|
|
20180
|
-
case "account-unavailable":
|
|
20181
|
-
return "account-changed";
|
|
20182
20182
|
default:
|
|
20183
20183
|
return "unsupported";
|
|
20184
20184
|
}
|
|
@@ -20271,6 +20271,23 @@ class CacheKeepWarmRefusal extends Error {
|
|
|
20271
20271
|
this.reason = reason;
|
|
20272
20272
|
}
|
|
20273
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
|
+
}
|
|
20274
20291
|
|
|
20275
20292
|
class CacheKeepManager2 {
|
|
20276
20293
|
options;
|
|
@@ -20281,8 +20298,19 @@ class CacheKeepManager2 {
|
|
|
20281
20298
|
timer = null;
|
|
20282
20299
|
dueTimer = null;
|
|
20283
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;
|
|
20284
20309
|
nextPrewarmAttemptId = 0;
|
|
20285
20310
|
reportedStops = new WeakSet;
|
|
20311
|
+
restoredTargets = new WeakSet;
|
|
20312
|
+
restoringPolicies = new WeakSet;
|
|
20313
|
+
sessionWarms = new Map;
|
|
20286
20314
|
admittedWarmCosts = new WeakMap;
|
|
20287
20315
|
constructor(options) {
|
|
20288
20316
|
this.options = options;
|
|
@@ -20292,7 +20320,7 @@ class CacheKeepManager2 {
|
|
|
20292
20320
|
return;
|
|
20293
20321
|
logger2.debug("cachekeep", "started");
|
|
20294
20322
|
this.timer = (this.options.setIntervalImpl ?? globalThis.setInterval)(() => {
|
|
20295
|
-
this.tick().catch(() => {
|
|
20323
|
+
return this.tick().catch(() => {
|
|
20296
20324
|
logger2.warn("cachekeep", "tick failed");
|
|
20297
20325
|
});
|
|
20298
20326
|
}, CACHE_KEEP_TICK_MS);
|
|
@@ -20301,10 +20329,9 @@ class CacheKeepManager2 {
|
|
|
20301
20329
|
this.scheduleDueTimer();
|
|
20302
20330
|
}
|
|
20303
20331
|
stop() {
|
|
20332
|
+
this.schedulerGeneration++;
|
|
20333
|
+
this.tickPromise = null;
|
|
20304
20334
|
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
20335
|
if (this.dueTimer) {
|
|
20309
20336
|
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
20310
20337
|
this.dueTimer = null;
|
|
@@ -20316,6 +20343,172 @@ class CacheKeepManager2 {
|
|
|
20316
20343
|
clearIntervalImpl(this.timer);
|
|
20317
20344
|
this.timer = null;
|
|
20318
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
|
+
}
|
|
20319
20512
|
stats(window, now = this.options.now?.() ?? Date.now(), always = false) {
|
|
20320
20513
|
const today = always ? "always" : localWindowKey(window, new Date(now));
|
|
20321
20514
|
const targets = [...this.targets.values()].filter((target) => target.dayKey === today);
|
|
@@ -20393,7 +20586,10 @@ class CacheKeepManager2 {
|
|
|
20393
20586
|
const record6 = this.warmingRecords.get(id);
|
|
20394
20587
|
if (!record6)
|
|
20395
20588
|
return;
|
|
20396
|
-
return
|
|
20589
|
+
return isSessionCacheWarmStopReason(record6.stopReason) ? {
|
|
20590
|
+
on: false,
|
|
20591
|
+
stopReason: record6.stopReason
|
|
20592
|
+
} : { on: false };
|
|
20397
20593
|
}
|
|
20398
20594
|
recordWarmingOff(id) {
|
|
20399
20595
|
this.setWarmingRecord(id, {});
|
|
@@ -20423,7 +20619,7 @@ class CacheKeepManager2 {
|
|
|
20423
20619
|
this.options.onTargetChanged?.(target);
|
|
20424
20620
|
this.scheduleDueTimer();
|
|
20425
20621
|
}
|
|
20426
|
-
costs(target) {
|
|
20622
|
+
costs(target, ownReservation = false) {
|
|
20427
20623
|
const state = target.policyState;
|
|
20428
20624
|
if (state?.prefixTokens === undefined)
|
|
20429
20625
|
return;
|
|
@@ -20451,14 +20647,22 @@ class CacheKeepManager2 {
|
|
|
20451
20647
|
return {
|
|
20452
20648
|
nextWarmCost: read * state.prefixTokens,
|
|
20453
20649
|
rewriteCost: write * state.prefixTokens,
|
|
20454
|
-
warmCostSoFar: state.warmCostSoFar
|
|
20650
|
+
warmCostSoFar: state.warmCostSoFar + Math.max(0, (state.pendingWarmCost ?? 0) - (ownReservation ? this.admittedWarmCosts.get(state) ?? 0 : 0))
|
|
20455
20651
|
};
|
|
20456
20652
|
}
|
|
20457
20653
|
policyDecision(target, now, ownReservation = false) {
|
|
20458
20654
|
const state = target.policyState;
|
|
20459
20655
|
if (!state)
|
|
20460
20656
|
return;
|
|
20461
|
-
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);
|
|
20462
20666
|
if (!policy && state.planned)
|
|
20463
20667
|
return { action: "stop", reason: "session-ended" };
|
|
20464
20668
|
if (!policy)
|
|
@@ -20476,13 +20680,14 @@ class CacheKeepManager2 {
|
|
|
20476
20680
|
const plan = mode === "hours" ? policy.hours && { mode, hours: policy.hours } : { mode };
|
|
20477
20681
|
if (!plan)
|
|
20478
20682
|
return { action: "stop", reason: "unsupported" };
|
|
20479
|
-
const costs = this.costs(target);
|
|
20683
|
+
const costs = this.costs(target, ownReservation);
|
|
20480
20684
|
if (mode === "auto" && !costs && state.lastRealRequestAt < now - (target.isSubagent ? PLANNED_UNPRICED_SUBAGENT_IDLE_MS : PLANNED_UNPRICED_MAIN_IDLE_MS))
|
|
20481
20685
|
return { action: "stop", reason: "idle" };
|
|
20482
20686
|
return decideCacheKeep({
|
|
20483
20687
|
...plan,
|
|
20484
20688
|
now,
|
|
20485
20689
|
ttlMs: target.ttlMs ?? 0,
|
|
20690
|
+
leadMs: CACHE_KEEP_PREWARM_LEAD_MS,
|
|
20486
20691
|
lastRealRequestAt: state.lastRealRequestAt,
|
|
20487
20692
|
lastWarmAt: state.lastWarmAt,
|
|
20488
20693
|
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest - Number(ownReservation),
|
|
@@ -20497,26 +20702,34 @@ class CacheKeepManager2 {
|
|
|
20497
20702
|
mode: "always",
|
|
20498
20703
|
now: state.lastRealRequestAt,
|
|
20499
20704
|
ttlMs: CACHE_KEEP_TTL_MS,
|
|
20705
|
+
...state.planned && { leadMs: CACHE_KEEP_PREWARM_LEAD_MS },
|
|
20500
20706
|
lastRealRequestAt: state.lastRealRequestAt,
|
|
20501
20707
|
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest
|
|
20502
20708
|
});
|
|
20503
20709
|
return result.action === "stop" && result.reason === "count-cap" ? result : undefined;
|
|
20504
20710
|
}
|
|
20505
20711
|
async reserveWarmDispatch(target) {
|
|
20712
|
+
const generation = this.schedulerGeneration;
|
|
20506
20713
|
const current = this.targets.get(target.id);
|
|
20507
20714
|
if (!current || !this.isCurrentTarget(target))
|
|
20508
20715
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20509
20716
|
const state = current.policyState;
|
|
20717
|
+
if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
|
|
20718
|
+
throw new CacheKeepWarmWait;
|
|
20510
20719
|
const loaded = await this.options.loadStorage();
|
|
20720
|
+
if (generation !== this.schedulerGeneration)
|
|
20721
|
+
throw new CacheKeepWarmWait;
|
|
20511
20722
|
const storage = loaded && this.options.resolveSettings ? this.targetSettings(this.options.resolveSettings(loaded), target.bodyText) : loaded;
|
|
20512
20723
|
if (!this.isCurrentTarget(target))
|
|
20513
20724
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20725
|
+
if (this.realTurnBusy(state?.ownerSessionId ?? target.id))
|
|
20726
|
+
throw new CacheKeepWarmWait;
|
|
20514
20727
|
const now = this.options.now?.() ?? Date.now();
|
|
20515
20728
|
const decision = this.policyDecision(current, now) ?? (isCacheKeepAlways(storage) ? this.countDecision(current) : undefined);
|
|
20516
20729
|
if (decision?.action === "stop")
|
|
20517
20730
|
throw new CacheKeepWarmRefusal(decision.reason);
|
|
20518
20731
|
if (decision?.action === "wait")
|
|
20519
|
-
throw new
|
|
20732
|
+
throw new CacheKeepWarmWait;
|
|
20520
20733
|
const admittedCost = this.costs(current)?.nextWarmCost ?? 0;
|
|
20521
20734
|
const pendingCost = state?.pendingWarmCost;
|
|
20522
20735
|
if (state) {
|
|
@@ -20528,6 +20741,8 @@ class CacheKeepManager2 {
|
|
|
20528
20741
|
try {
|
|
20529
20742
|
committed = await this.options.reserveWarm(current);
|
|
20530
20743
|
} catch {}
|
|
20744
|
+
if (generation !== this.schedulerGeneration)
|
|
20745
|
+
throw new CacheKeepWarmWait;
|
|
20531
20746
|
if (!committed && (state?.planned || isCacheKeepAlways(storage))) {
|
|
20532
20747
|
if (state) {
|
|
20533
20748
|
state.warmsSinceLastRealRequest--;
|
|
@@ -20540,19 +20755,29 @@ class CacheKeepManager2 {
|
|
|
20540
20755
|
this.admittedWarmCosts.set(state, admittedCost);
|
|
20541
20756
|
if (!this.isCurrentTarget(target))
|
|
20542
20757
|
throw new CacheKeepWarmRefusal("stopped");
|
|
20543
|
-
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);
|
|
20544
20759
|
if (fresh?.action === "stop")
|
|
20545
20760
|
throw new CacheKeepWarmRefusal(fresh.reason);
|
|
20546
|
-
if (fresh?.action === "wait")
|
|
20547
|
-
|
|
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
|
+
}
|
|
20548
20770
|
}
|
|
20549
20771
|
scheduleDueTimer() {
|
|
20550
20772
|
if (this.dueTimer)
|
|
20551
20773
|
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
20552
20774
|
this.dueTimer = null;
|
|
20775
|
+
if (!this.timer)
|
|
20776
|
+
return;
|
|
20553
20777
|
let due = Infinity;
|
|
20554
20778
|
for (const target of this.targets.values())
|
|
20555
|
-
|
|
20779
|
+
if (!this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
|
|
20780
|
+
due = Math.min(due, target.nextPrewarmAt);
|
|
20556
20781
|
if (!Number.isFinite(due))
|
|
20557
20782
|
return;
|
|
20558
20783
|
this.dueTimer = (this.options.setTimeoutImpl ?? setTimeout)(() => {
|
|
@@ -20587,19 +20812,18 @@ class CacheKeepManager2 {
|
|
|
20587
20812
|
if (this.targets.get(target.id) !== target)
|
|
20588
20813
|
return;
|
|
20589
20814
|
this.reportStop(target, reason, now);
|
|
20590
|
-
|
|
20591
|
-
|
|
20592
|
-
|
|
20593
|
-
|
|
20594
|
-
|
|
20595
|
-
|
|
20596
|
-
|
|
20597
|
-
|
|
20598
|
-
|
|
20599
|
-
|
|
20600
|
-
|
|
20601
|
-
|
|
20602
|
-
});
|
|
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
|
+
});
|
|
20603
20827
|
this.retainStopped(target, stopReason(reason), now);
|
|
20604
20828
|
this.targets.delete(target.id);
|
|
20605
20829
|
this.options.onTargetRemoved?.(target.id);
|
|
@@ -20612,17 +20836,28 @@ class CacheKeepManager2 {
|
|
|
20612
20836
|
warmStopped: { at: now, reason }
|
|
20613
20837
|
});
|
|
20614
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
|
+
}
|
|
20615
20846
|
reportStop(target, reason, at) {
|
|
20847
|
+
if (this.targets.get(target.id) !== target)
|
|
20848
|
+
return;
|
|
20616
20849
|
const state = target.policyState;
|
|
20617
20850
|
if (!target.sourceWarm)
|
|
20618
|
-
this.setWarmingRecord(target.id, {
|
|
20619
|
-
|
|
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))
|
|
20620
20855
|
return;
|
|
20621
|
-
|
|
20856
|
+
this.reportedStops.add(state);
|
|
20857
|
+
reportSessionCacheWarmStopped(state.ownerSessionId, {
|
|
20622
20858
|
at,
|
|
20623
20859
|
reason: reportStopReason(reason)
|
|
20624
|
-
})
|
|
20625
|
-
this.reportedStops.add(state);
|
|
20860
|
+
});
|
|
20626
20861
|
}
|
|
20627
20862
|
evictOldestTarget(now, reason) {
|
|
20628
20863
|
const oldest = this.targets.values().next().value;
|
|
@@ -20641,7 +20876,16 @@ class CacheKeepManager2 {
|
|
|
20641
20876
|
continue;
|
|
20642
20877
|
}
|
|
20643
20878
|
if (now >= target.cacheExpiresAt) {
|
|
20644
|
-
|
|
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);
|
|
20645
20889
|
this.targets.delete(id);
|
|
20646
20890
|
this.options.onTargetRemoved?.(id);
|
|
20647
20891
|
}
|
|
@@ -20667,10 +20911,10 @@ class CacheKeepManager2 {
|
|
|
20667
20911
|
}
|
|
20668
20912
|
const now = this.options.now?.() ?? Date.now();
|
|
20669
20913
|
const acceptedAt = input.acceptedAt ?? input.retained?.lastTouchAt ?? now;
|
|
20670
|
-
if (input.retained && input.retained.cacheExpiresAt <= now)
|
|
20671
|
-
return { tracked: false, reason: "cache expired" };
|
|
20672
20914
|
let bodyBytes;
|
|
20673
20915
|
const refuse = (reason, reasonCode) => {
|
|
20916
|
+
if (input.sessionId && !input.retained && !input.sourceWarm)
|
|
20917
|
+
this.finishSessionTargets(input.sessionId);
|
|
20674
20918
|
if (reasonCode === "body-budget")
|
|
20675
20919
|
logger2.warn("cachekeep", "tracking skipped", {
|
|
20676
20920
|
session: input.sessionId ?? null,
|
|
@@ -20699,18 +20943,27 @@ class CacheKeepManager2 {
|
|
|
20699
20943
|
previous = undefined;
|
|
20700
20944
|
}
|
|
20701
20945
|
const ownerSessionId = input.ownerSessionId ?? input.retained?.policyState?.ownerSessionId ?? input.sessionId;
|
|
20702
|
-
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);
|
|
20703
20951
|
const planned = policy?.keep_warm !== undefined;
|
|
20952
|
+
const sessionId = input.sessionId;
|
|
20704
20953
|
const retire = (reason) => {
|
|
20705
20954
|
if (previous)
|
|
20706
20955
|
this.removeTarget(previous, reason, now);
|
|
20707
20956
|
return refuse(reason, reason);
|
|
20708
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");
|
|
20709
20963
|
if (input.retained && (planned || isCacheKeepAlways(input.storage)) && input.retained.policyState?.needsRealRequest)
|
|
20710
20964
|
return retire("unsupported");
|
|
20711
|
-
if (!
|
|
20965
|
+
if (!input.retained && !policy && previous?.policyState?.planned)
|
|
20712
20966
|
return retire("session-ended");
|
|
20713
|
-
const sessionId = input.sessionId;
|
|
20714
20967
|
const keptOff = () => {
|
|
20715
20968
|
if (!previous && !input.sourceWarm)
|
|
20716
20969
|
this.recordWarmingOff(sessionId);
|
|
@@ -20763,6 +21016,7 @@ class CacheKeepManager2 {
|
|
|
20763
21016
|
}
|
|
20764
21017
|
const today = cacheKeepPeriodKey(input.storage, window, new Date(now));
|
|
20765
21018
|
this.pruneTargets(now, today);
|
|
21019
|
+
previous = this.targets.get(input.sessionId);
|
|
20766
21020
|
if (this.targets.has(input.sessionId))
|
|
20767
21021
|
this.targets.delete(input.sessionId);
|
|
20768
21022
|
this.stoppedSessions.delete(input.sessionId);
|
|
@@ -20792,15 +21046,18 @@ class CacheKeepManager2 {
|
|
|
20792
21046
|
dayKey: today,
|
|
20793
21047
|
oauthAccountId: input.oauthAccountId,
|
|
20794
21048
|
oauthAccountIdentity: input.oauthAccountIdentity,
|
|
21049
|
+
hostMetadata: input.hostMetadata,
|
|
20795
21050
|
accountStoragePath: input.accountStoragePath,
|
|
20796
21051
|
isSubagent: input.isSubagent ?? false,
|
|
20797
21052
|
policyState: input.retained?.policyState ? {
|
|
20798
21053
|
...input.retained.policyState,
|
|
20799
21054
|
warmCostSoFar: input.retained.policyState.warmCostSoFar + (input.retained.policyState.pendingWarmCost ?? 0),
|
|
20800
|
-
pendingWarmCost: undefined
|
|
21055
|
+
pendingWarmCost: undefined,
|
|
21056
|
+
...policy && { policy: structuredClone(policy) }
|
|
20801
21057
|
} : {
|
|
20802
21058
|
ownerSessionId,
|
|
20803
21059
|
planned,
|
|
21060
|
+
...policy && { policy: structuredClone(policy) },
|
|
20804
21061
|
lastRealRequestAt: acceptedAt,
|
|
20805
21062
|
warmsSinceLastRealRequest: 0,
|
|
20806
21063
|
warmCostSoFar: 0,
|
|
@@ -20808,11 +21065,23 @@ class CacheKeepManager2 {
|
|
|
20808
21065
|
},
|
|
20809
21066
|
...input.sourceWarm === true && { sourceWarm: true }
|
|
20810
21067
|
});
|
|
20811
|
-
this.pruneTargets(now, today);
|
|
20812
|
-
this.publishTrackedSessions();
|
|
20813
21068
|
const target = this.targets.get(input.sessionId);
|
|
20814
21069
|
if (!target)
|
|
20815
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" };
|
|
20816
21085
|
if (input.acceptedUsage)
|
|
20817
21086
|
updateAcceptedUsage(target, input.bodyText, input.acceptedUsage);
|
|
20818
21087
|
if (planned) {
|
|
@@ -20859,15 +21128,12 @@ class CacheKeepManager2 {
|
|
|
20859
21128
|
if (!current)
|
|
20860
21129
|
this.immediateTargets.set(target.id, target);
|
|
20861
21130
|
try {
|
|
20862
|
-
|
|
20863
|
-
|
|
20864
|
-
|
|
21131
|
+
return await this.sendPrewarm(target, (receivedAt, result) => {
|
|
21132
|
+
if (current && this.isCurrentTarget(target)) {
|
|
21133
|
+
this.acceptWarm(current, result, receivedAt);
|
|
21134
|
+
this.scheduleDueTimer();
|
|
21135
|
+
}
|
|
20865
21136
|
});
|
|
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
21137
|
} finally {
|
|
20872
21138
|
if (this.immediateTargets.get(target.id) === target)
|
|
20873
21139
|
this.immediateTargets.delete(target.id);
|
|
@@ -20876,17 +21142,25 @@ class CacheKeepManager2 {
|
|
|
20876
21142
|
tick() {
|
|
20877
21143
|
if (this.tickPromise)
|
|
20878
21144
|
return this.tickPromise;
|
|
21145
|
+
const lifetime = this.lifetime;
|
|
21146
|
+
const generation = this.schedulerGeneration;
|
|
20879
21147
|
let run;
|
|
20880
|
-
run = this.runTick().finally(() => {
|
|
21148
|
+
run = this.runTick(lifetime).finally(() => {
|
|
21149
|
+
this.ticks.delete(run);
|
|
20881
21150
|
if (this.tickPromise === run)
|
|
20882
21151
|
this.tickPromise = null;
|
|
20883
|
-
this.
|
|
21152
|
+
if (lifetime === this.lifetime && generation === this.schedulerGeneration)
|
|
21153
|
+
this.scheduleDueTimer();
|
|
20884
21154
|
});
|
|
20885
21155
|
this.tickPromise = run;
|
|
21156
|
+
this.ticks.add(run);
|
|
20886
21157
|
return run;
|
|
20887
21158
|
}
|
|
20888
|
-
async runTick() {
|
|
21159
|
+
async runTick(lifetime) {
|
|
21160
|
+
const generation = this.schedulerGeneration;
|
|
20889
21161
|
const loaded = await this.options.loadStorage();
|
|
21162
|
+
if (lifetime !== this.lifetime || generation !== this.schedulerGeneration)
|
|
21163
|
+
return;
|
|
20890
21164
|
const storage = loaded && this.options.resolveSettings ? this.options.resolveSettings(loaded) : loaded;
|
|
20891
21165
|
const window = getCacheKeepWindow(storage);
|
|
20892
21166
|
const now = this.options.now?.() ?? Date.now();
|
|
@@ -20904,49 +21178,58 @@ class CacheKeepManager2 {
|
|
|
20904
21178
|
}
|
|
20905
21179
|
logger2.debug("cachekeep", "fired", { targets: this.targets.size });
|
|
20906
21180
|
const targets = [...this.targets.values()].sort((a, b) => this.lastPrewarmStart(a) - this.lastPrewarmStart(b));
|
|
20907
|
-
|
|
21181
|
+
const warm = async (target) => {
|
|
21182
|
+
if (generation !== this.schedulerGeneration)
|
|
21183
|
+
return;
|
|
20908
21184
|
if (this.targets.get(target.id) !== target)
|
|
20909
|
-
|
|
21185
|
+
return;
|
|
21186
|
+
if (this.realTurnBusy(target.policyState?.ownerSessionId ?? target.id))
|
|
21187
|
+
return;
|
|
20910
21188
|
const attemptAt = this.options.now?.() ?? Date.now();
|
|
20911
21189
|
const decision = this.policyDecision(target, attemptAt);
|
|
20912
21190
|
if (decision?.action === "stop") {
|
|
20913
21191
|
this.removeTarget(target, decision.reason, attemptAt);
|
|
20914
|
-
|
|
21192
|
+
return;
|
|
20915
21193
|
}
|
|
20916
21194
|
if (decision?.action === "wait") {
|
|
20917
21195
|
target.nextPrewarmAt = Math.max(target.nextPrewarmAt, decision.until);
|
|
20918
|
-
|
|
21196
|
+
return;
|
|
20919
21197
|
}
|
|
20920
21198
|
if (!target.policyState?.planned) {
|
|
20921
21199
|
const targetStorage = storage ? this.targetSettings(storage, target.bodyText) : storage;
|
|
20922
21200
|
if (!isCacheKeepHybridActive(targetStorage)) {
|
|
20923
21201
|
this.removeTarget(target, "cachekeep-hybrid-inactive", attemptAt);
|
|
20924
|
-
|
|
21202
|
+
return;
|
|
20925
21203
|
}
|
|
20926
21204
|
const targetToday = cacheKeepPeriodKey(targetStorage, window, new Date(attemptAt));
|
|
20927
21205
|
if (isCacheKeepAlways(targetStorage))
|
|
20928
21206
|
target.dayKey = "always";
|
|
20929
21207
|
if (!isCacheKeepActiveNow(targetStorage, new Date(attemptAt)) || target.dayKey !== targetToday) {
|
|
20930
21208
|
this.removeTarget(target, "schedule-period-ended", attemptAt);
|
|
20931
|
-
|
|
21209
|
+
return;
|
|
20932
21210
|
}
|
|
20933
21211
|
if (isCacheKeepAlways(targetStorage)) {
|
|
20934
21212
|
const count2 = this.countDecision(target);
|
|
20935
21213
|
if (count2?.action === "stop") {
|
|
20936
21214
|
this.removeTarget(target, count2.reason, attemptAt);
|
|
20937
|
-
|
|
21215
|
+
return;
|
|
20938
21216
|
}
|
|
20939
21217
|
}
|
|
20940
21218
|
}
|
|
20941
21219
|
if (target.nextPrewarmAt > attemptAt)
|
|
20942
|
-
|
|
21220
|
+
return;
|
|
20943
21221
|
if (attemptAt > this.lastPrewarmStart(target)) {
|
|
20944
|
-
this.removeTarget(target,
|
|
20945
|
-
|
|
21222
|
+
this.removeTarget(target, "retry-window-ended", attemptAt, {
|
|
21223
|
+
stage: "dispatch",
|
|
21224
|
+
overdueMs: attemptAt - this.lastPrewarmStart(target)
|
|
21225
|
+
});
|
|
21226
|
+
return;
|
|
20946
21227
|
}
|
|
20947
21228
|
try {
|
|
20948
21229
|
await this.prewarm(target, attemptAt);
|
|
20949
21230
|
} catch (error) {
|
|
21231
|
+
if (generation !== this.schedulerGeneration)
|
|
21232
|
+
return;
|
|
20950
21233
|
logger2.warn("cachekeep", "prewarm failed", {
|
|
20951
21234
|
session: target.id,
|
|
20952
21235
|
...classifyCacheKeepFailure(error, "send"),
|
|
@@ -20955,11 +21238,20 @@ class CacheKeepManager2 {
|
|
|
20955
21238
|
});
|
|
20956
21239
|
this.scheduleRetry(target, true);
|
|
20957
21240
|
} finally {
|
|
20958
|
-
if (this.targets.get(target.id) === target)
|
|
21241
|
+
if (generation === this.schedulerGeneration && this.targets.get(target.id) === target)
|
|
20959
21242
|
this.options.onTargetChanged?.(target);
|
|
20960
21243
|
}
|
|
20961
|
-
}
|
|
20962
|
-
|
|
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();
|
|
20963
21255
|
}
|
|
20964
21256
|
targetSettings(storage, bodyText) {
|
|
20965
21257
|
if (!this.options.resolveSettings)
|
|
@@ -20984,7 +21276,10 @@ class CacheKeepManager2 {
|
|
|
20984
21276
|
const now = this.options.now?.() ?? Date.now();
|
|
20985
21277
|
const deadline = this.lastPrewarmStart(target);
|
|
20986
21278
|
if (now >= deadline) {
|
|
20987
|
-
this.removeTarget(target,
|
|
21279
|
+
this.removeTarget(target, "retry-window-ended", now, {
|
|
21280
|
+
stage: "retry",
|
|
21281
|
+
overdueMs: now - deadline
|
|
21282
|
+
});
|
|
20988
21283
|
return;
|
|
20989
21284
|
}
|
|
20990
21285
|
target.consecutiveFailures += 1;
|
|
@@ -20993,13 +21288,78 @@ class CacheKeepManager2 {
|
|
|
20993
21288
|
target.nextPrewarmAt = Math.min(now + delay3, deadline);
|
|
20994
21289
|
}
|
|
20995
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;
|
|
20996
21341
|
const remaining = target.cacheExpiresAt - (this.options.now?.() ?? Date.now()) - CACHE_KEEP_EXPIRY_SAFETY_MS;
|
|
20997
21342
|
const timeout = Math.min(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS, target.policyState?.planned || target.sourceWarm ? remaining : Infinity);
|
|
20998
21343
|
if (timeout <= 0)
|
|
20999
|
-
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;
|
|
21000
21349
|
const attempt = {
|
|
21001
21350
|
id: ++this.nextPrewarmAttemptId,
|
|
21002
|
-
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();
|
|
21003
21363
|
};
|
|
21004
21364
|
let stage = "authorization";
|
|
21005
21365
|
let responseStatus;
|
|
@@ -21024,21 +21384,25 @@ class CacheKeepManager2 {
|
|
|
21024
21384
|
throw new CacheKeepWarmRefusal("routing-moved");
|
|
21025
21385
|
};
|
|
21026
21386
|
try {
|
|
21387
|
+
ensureActive();
|
|
21027
21388
|
checkRouting();
|
|
21028
21389
|
let bodyText = target.bodyText;
|
|
21029
21390
|
if (this.options.prepareBody) {
|
|
21030
21391
|
try {
|
|
21031
21392
|
bodyText = await this.options.prepareBody(bodyText, target);
|
|
21032
21393
|
} catch {
|
|
21394
|
+
ensureActive();
|
|
21033
21395
|
logger2.warn("cachekeep", "prepare body failed", {
|
|
21034
21396
|
session: target.id
|
|
21035
21397
|
});
|
|
21036
21398
|
}
|
|
21399
|
+
ensureActive();
|
|
21037
21400
|
}
|
|
21038
21401
|
const preparedTarget = { ...target, bodyText };
|
|
21039
21402
|
const prewarm = await buildCacheKeepPrewarmBody(bodyText, {
|
|
21040
21403
|
stripServerFallback: target.sourceWarm === true
|
|
21041
21404
|
});
|
|
21405
|
+
ensureActive();
|
|
21042
21406
|
if (!prewarm.ok)
|
|
21043
21407
|
return prewarm;
|
|
21044
21408
|
if (this.options.validatePrewarm) {
|
|
@@ -21051,6 +21415,7 @@ class CacheKeepManager2 {
|
|
|
21051
21415
|
} catch {
|
|
21052
21416
|
verdict = undefined;
|
|
21053
21417
|
}
|
|
21418
|
+
ensureActive();
|
|
21054
21419
|
if (!verdict?.ok) {
|
|
21055
21420
|
return {
|
|
21056
21421
|
ok: false,
|
|
@@ -21061,7 +21426,9 @@ class CacheKeepManager2 {
|
|
|
21061
21426
|
}
|
|
21062
21427
|
const fetchImpl = this.options.fetchForTarget?.(target) ?? this.options.fetchImpl ?? fetch;
|
|
21063
21428
|
const prewarmTarget = { ...preparedTarget, bodyText: prewarm.bodyText };
|
|
21429
|
+
ensureActive();
|
|
21064
21430
|
let headers = this.options.prepareHeaders ? await this.options.prepareHeaders(new Headers(target.headers), prewarmTarget, attempt) : new Headers(target.headers);
|
|
21431
|
+
ensureActive();
|
|
21065
21432
|
if (!headers) {
|
|
21066
21433
|
const summary2 = summarizePrewarmProviderError({
|
|
21067
21434
|
failure: "credential_unavailable"
|
|
@@ -21079,6 +21446,7 @@ class CacheKeepManager2 {
|
|
|
21079
21446
|
stage = "send";
|
|
21080
21447
|
let response;
|
|
21081
21448
|
const send = async (attemptHeaders) => {
|
|
21449
|
+
ensureActive();
|
|
21082
21450
|
if (!this.isCurrentTarget(target))
|
|
21083
21451
|
throw new CacheKeepWarmRefusal("stopped");
|
|
21084
21452
|
checkRouting();
|
|
@@ -21086,30 +21454,41 @@ class CacheKeepManager2 {
|
|
|
21086
21454
|
if (!this.options.deferWarmReservation)
|
|
21087
21455
|
await this.reserveWarmDispatch(target);
|
|
21088
21456
|
}
|
|
21089
|
-
|
|
21457
|
+
ensureActive();
|
|
21090
21458
|
const scope = createProviderErrorResponseScope(cacheKeepSentCredentials(attemptHeaders), "http");
|
|
21091
21459
|
try {
|
|
21092
|
-
const dispatch = () =>
|
|
21093
|
-
|
|
21094
|
-
|
|
21095
|
-
|
|
21096
|
-
|
|
21097
|
-
|
|
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
|
+
};
|
|
21098
21469
|
let billing;
|
|
21099
21470
|
try {
|
|
21100
21471
|
billing = this.options.billingRequest?.(prewarmTarget, attempt);
|
|
21101
21472
|
} catch {}
|
|
21102
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;
|
|
21103
21481
|
if (!sent.ok && this.isCurrentTarget(target) && target.policyState) {
|
|
21104
21482
|
const state = target.policyState;
|
|
21105
21483
|
const cost = this.admittedWarmCosts.get(state) ?? 0;
|
|
21106
21484
|
target.policyState.pendingWarmCost = Math.max(0, (target.policyState.pendingWarmCost ?? 0) - cost) || undefined;
|
|
21107
21485
|
this.admittedWarmCosts.delete(state);
|
|
21108
21486
|
await this.options.settleWarm?.(target);
|
|
21487
|
+
ensureActive();
|
|
21109
21488
|
}
|
|
21110
21489
|
return scope.redactResponse(sent);
|
|
21111
21490
|
} catch (error) {
|
|
21112
|
-
if (error instanceof CacheKeepWarmRefusal || nativeAccountRefusal(error)) {
|
|
21491
|
+
if (error instanceof CacheKeepWarmRefusal || isCacheKeepWarmWait(error) || nativeAccountRefusal(error)) {
|
|
21113
21492
|
scope.dispose();
|
|
21114
21493
|
throw error;
|
|
21115
21494
|
}
|
|
@@ -21118,6 +21497,7 @@ class CacheKeepManager2 {
|
|
|
21118
21497
|
}
|
|
21119
21498
|
};
|
|
21120
21499
|
response = await send(headers);
|
|
21500
|
+
ensureActive();
|
|
21121
21501
|
if (response.status === 401 && !attempt.signal?.aborted && this.options.retryOnUnauthorized) {
|
|
21122
21502
|
let rotatedHeaders;
|
|
21123
21503
|
try {
|
|
@@ -21128,28 +21508,34 @@ class CacheKeepManager2 {
|
|
|
21128
21508
|
attempt
|
|
21129
21509
|
});
|
|
21130
21510
|
} catch (error) {
|
|
21511
|
+
ensureActive();
|
|
21131
21512
|
if (error instanceof NativeAccountRefusal) {
|
|
21132
21513
|
await response.body?.cancel().catch(() => {});
|
|
21514
|
+
ensureActive();
|
|
21133
21515
|
throw error;
|
|
21134
21516
|
}
|
|
21135
21517
|
}
|
|
21518
|
+
ensureActive();
|
|
21136
21519
|
if (rotatedHeaders && !attempt.signal?.aborted) {
|
|
21137
21520
|
rotatedHeaders.delete("content-length");
|
|
21138
21521
|
rotatedHeaders.delete("transfer-encoding");
|
|
21139
21522
|
await response.body?.cancel().catch(() => {});
|
|
21523
|
+
ensureActive();
|
|
21140
21524
|
headers = rotatedHeaders;
|
|
21141
21525
|
response = await send(headers);
|
|
21526
|
+
ensureActive();
|
|
21142
21527
|
}
|
|
21143
21528
|
}
|
|
21144
21529
|
stage = "response";
|
|
21145
21530
|
responseStatus = response.status;
|
|
21146
21531
|
const receivedAt = this.options.now?.() ?? Date.now();
|
|
21147
21532
|
const raw = await response.text();
|
|
21148
|
-
|
|
21533
|
+
ensureActive();
|
|
21149
21534
|
let data = null;
|
|
21150
21535
|
try {
|
|
21151
21536
|
data = raw ? JSON.parse(raw) : null;
|
|
21152
21537
|
} catch {}
|
|
21538
|
+
ensureActive();
|
|
21153
21539
|
const summary = response.ok ? undefined : summarizePrewarmProviderError({ status: response.status, body: raw });
|
|
21154
21540
|
try {
|
|
21155
21541
|
await this.options.onResponse?.({
|
|
@@ -21161,6 +21547,7 @@ class CacheKeepManager2 {
|
|
|
21161
21547
|
attempt
|
|
21162
21548
|
});
|
|
21163
21549
|
} catch {}
|
|
21550
|
+
ensureActive();
|
|
21164
21551
|
try {
|
|
21165
21552
|
const dumpHandle = await dumpDirectRequest({
|
|
21166
21553
|
affinity: target.id,
|
|
@@ -21172,14 +21559,17 @@ class CacheKeepManager2 {
|
|
|
21172
21559
|
headers,
|
|
21173
21560
|
tag: "cachekeep"
|
|
21174
21561
|
});
|
|
21562
|
+
ensureActive();
|
|
21175
21563
|
await dumpResponseArtifact(dumpHandle, {
|
|
21176
21564
|
status: response.status,
|
|
21177
21565
|
message: data,
|
|
21178
21566
|
...summary && { provider_error: summary.provider_error }
|
|
21179
21567
|
});
|
|
21180
21568
|
} catch {
|
|
21569
|
+
ensureActive();
|
|
21181
21570
|
logger2.debug("cachekeep", "dump failed", { session: target.id });
|
|
21182
21571
|
}
|
|
21572
|
+
ensureActive();
|
|
21183
21573
|
if (summary) {
|
|
21184
21574
|
return {
|
|
21185
21575
|
ok: false,
|
|
@@ -21197,6 +21587,10 @@ class CacheKeepManager2 {
|
|
|
21197
21587
|
...usage && { usage }
|
|
21198
21588
|
};
|
|
21199
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" };
|
|
21200
21594
|
if (error instanceof CacheKeepWarmRefusal)
|
|
21201
21595
|
return { ok: false, refused: true, reason: error.reason };
|
|
21202
21596
|
const failure = classifyCacheKeepFailure(error, stage, responseStatus);
|
|
@@ -21217,17 +21611,31 @@ class CacheKeepManager2 {
|
|
|
21217
21611
|
transient: true
|
|
21218
21612
|
};
|
|
21219
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 {}
|
|
21220
21623
|
try {
|
|
21221
21624
|
await this.options.onComplete?.({ target, attempt });
|
|
21222
21625
|
} catch {}
|
|
21223
21626
|
}
|
|
21224
21627
|
}
|
|
21225
21628
|
async prewarm(target, now) {
|
|
21226
|
-
|
|
21227
|
-
const result = await this.sendPrewarm(target, (receivedAt) => {
|
|
21228
|
-
|
|
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);
|
|
21229
21633
|
});
|
|
21634
|
+
if (generation !== this.schedulerGeneration)
|
|
21635
|
+
return;
|
|
21230
21636
|
if (!result.ok) {
|
|
21637
|
+
if (result.refused !== true && result.skipped)
|
|
21638
|
+
return;
|
|
21231
21639
|
if (result.refused === true) {
|
|
21232
21640
|
this.removeTarget(target, result.reason, now, {
|
|
21233
21641
|
detail: "prewarm refused before send"
|
|
@@ -21256,10 +21664,6 @@ class CacheKeepManager2 {
|
|
|
21256
21664
|
}
|
|
21257
21665
|
return;
|
|
21258
21666
|
}
|
|
21259
|
-
if (this.targets.get(target.id) !== target)
|
|
21260
|
-
return;
|
|
21261
|
-
acceptedAt ??= this.options.now?.() ?? Date.now();
|
|
21262
|
-
this.acceptWarm(target, result, acceptedAt);
|
|
21263
21667
|
}
|
|
21264
21668
|
acceptWarm(target, result, acceptedAt) {
|
|
21265
21669
|
const state = target.policyState;
|
|
@@ -21318,8 +21722,8 @@ import { uptime } from "node:os";
|
|
|
21318
21722
|
import { basename as basename13, dirname as dirname20, join as join25 } from "node:path";
|
|
21319
21723
|
|
|
21320
21724
|
// src/native-lock-observer.ts
|
|
21321
|
-
import { AsyncLocalStorage as
|
|
21322
|
-
var detachedLocks = new
|
|
21725
|
+
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
|
|
21726
|
+
var detachedLocks = new AsyncLocalStorage4;
|
|
21323
21727
|
function withDetachedNativeLocks(work) {
|
|
21324
21728
|
return detachedLocks.run(true, work);
|
|
21325
21729
|
}
|
|
@@ -21448,9 +21852,9 @@ function recordIdentityIn(tx, id, identity4) {
|
|
|
21448
21852
|
return disableIdentityDuplicates(tx, identity4);
|
|
21449
21853
|
}
|
|
21450
21854
|
// ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
|
|
21451
|
-
import { AsyncLocalStorage as
|
|
21452
|
-
var insideHook = new
|
|
21453
|
-
var insideCodec = new
|
|
21855
|
+
import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
|
|
21856
|
+
var insideHook = new AsyncLocalStorage5;
|
|
21857
|
+
var insideCodec = new AsyncLocalStorage5;
|
|
21454
21858
|
function assertNotInsideHook(operation) {
|
|
21455
21859
|
if (insideHook.getStore() !== undefined)
|
|
21456
21860
|
throw new PoolReentryError(operation);
|
|
@@ -31359,6 +31763,7 @@ function record12(target, pluginVersion) {
|
|
|
31359
31763
|
policyState: {
|
|
31360
31764
|
ownerSessionId: target.policyState.ownerSessionId,
|
|
31361
31765
|
planned: target.policyState.planned,
|
|
31766
|
+
policy: target.policyState.policy,
|
|
31362
31767
|
lastRealRequestAt: target.policyState.lastRealRequestAt,
|
|
31363
31768
|
lastWarmAt: target.policyState.lastWarmAt,
|
|
31364
31769
|
warmsSinceLastRealRequest: target.policyState.warmsSinceLastRealRequest,
|
|
@@ -31392,13 +31797,39 @@ function invalidReason(value, name, now) {
|
|
|
31392
31797
|
return "format";
|
|
31393
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))
|
|
31394
31799
|
return "invalid";
|
|
31395
|
-
if (value.cacheExpiresAt <= now)
|
|
31396
|
-
return "expired";
|
|
31397
31800
|
const state = value.policyState;
|
|
31398
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))))
|
|
31399
31802
|
return "invalid";
|
|
31803
|
+
if (state?.policy !== undefined && !validSavedPolicy(state.policy))
|
|
31804
|
+
return "invalid";
|
|
31400
31805
|
if (sanitizedBody(value.bodyText) !== value.bodyText)
|
|
31401
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
|
+
}
|
|
31402
31833
|
}
|
|
31403
31834
|
|
|
31404
31835
|
class CacheKeepStore {
|
|
@@ -31469,7 +31900,7 @@ class CacheKeepStore {
|
|
|
31469
31900
|
await action();
|
|
31470
31901
|
}).catch(() => this.writeFailed());
|
|
31471
31902
|
}
|
|
31472
|
-
async load(now, accept, claim) {
|
|
31903
|
+
async load(now, accept, claim, guard) {
|
|
31473
31904
|
await this.chain;
|
|
31474
31905
|
if (!await this.directoryReady())
|
|
31475
31906
|
return;
|
|
@@ -31498,7 +31929,17 @@ class CacheKeepStore {
|
|
|
31498
31929
|
continue;
|
|
31499
31930
|
const path2 = join27(directory, name);
|
|
31500
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
|
+
};
|
|
31501
31940
|
try {
|
|
31941
|
+
if (!await permitted())
|
|
31942
|
+
continue;
|
|
31502
31943
|
if (TEMP.test(name)) {
|
|
31503
31944
|
reason = "unfinished-write";
|
|
31504
31945
|
throw new Error("Unfinished write");
|
|
@@ -31521,9 +31962,16 @@ class CacheKeepStore {
|
|
|
31521
31962
|
maxOutputLength: MAX_RECORD_BYTES
|
|
31522
31963
|
});
|
|
31523
31964
|
reason = "invalid";
|
|
31524
|
-
|
|
31965
|
+
entry2 = JSON.parse(raw.toString("utf8"));
|
|
31525
31966
|
const invalid3 = invalidReason(entry2, name, now);
|
|
31526
|
-
|
|
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;
|
|
31527
31975
|
if (accepted !== true && accepted !== undefined) {
|
|
31528
31976
|
reason = accepted || "invalid";
|
|
31529
31977
|
throw new Error("Stale restart file");
|
|
@@ -31531,7 +31979,10 @@ class CacheKeepStore {
|
|
|
31531
31979
|
if (accepted === true) {
|
|
31532
31980
|
if (directory !== this.directory) {
|
|
31533
31981
|
try {
|
|
31534
|
-
|
|
31982
|
+
const adopted = entry2;
|
|
31983
|
+
const migrating = this.chain.then(() => this.writeEntry(adopted));
|
|
31984
|
+
this.chain = migrating.catch(() => this.writeFailed());
|
|
31985
|
+
await migrating;
|
|
31535
31986
|
} catch {
|
|
31536
31987
|
this.refuse();
|
|
31537
31988
|
return;
|
|
@@ -31541,12 +31992,17 @@ class CacheKeepStore {
|
|
|
31541
31992
|
restored++;
|
|
31542
31993
|
}
|
|
31543
31994
|
} catch {
|
|
31544
|
-
|
|
31545
|
-
|
|
31546
|
-
|
|
31547
|
-
|
|
31548
|
-
|
|
31549
|
-
|
|
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;
|
|
31550
32006
|
} finally {
|
|
31551
32007
|
await release2?.();
|
|
31552
32008
|
}
|
|
@@ -52255,6 +52711,7 @@ export {
|
|
|
52255
52711
|
writeDumpFile,
|
|
52256
52712
|
withSessionCacheReportHandoff,
|
|
52257
52713
|
withNativeLock,
|
|
52714
|
+
withCacheKeepRealTurn,
|
|
52258
52715
|
withAnthropicBilling,
|
|
52259
52716
|
withAbortableFetch,
|
|
52260
52717
|
warnRelayProxyRefused,
|
|
@@ -52519,6 +52976,7 @@ export {
|
|
|
52519
52976
|
isStateLayoutRefusalCode,
|
|
52520
52977
|
isSseCandidateFrame,
|
|
52521
52978
|
isSettingsImportPending,
|
|
52979
|
+
isSessionCacheWarmStopReason,
|
|
52522
52980
|
isServerFallbackUsageMarker,
|
|
52523
52981
|
isSeparateSettingsInstall,
|
|
52524
52982
|
isSecretKey,
|
|
@@ -52555,6 +53013,7 @@ export {
|
|
|
52555
53013
|
isClaudeFableOrMythos5Model,
|
|
52556
53014
|
isClaudeFableOrMythos51Model,
|
|
52557
53015
|
isClaudeFable51Model,
|
|
53016
|
+
isCacheKeepWarmWait,
|
|
52558
53017
|
isCacheKeepSubagentsEnabled,
|
|
52559
53018
|
isCacheKeepPersistentlyEnabled,
|
|
52560
53019
|
isCacheKeepHybridActive,
|
|
@@ -52692,6 +53151,7 @@ export {
|
|
|
52692
53151
|
custodyTombstoneOAuth,
|
|
52693
53152
|
custodyTombstoneKey,
|
|
52694
53153
|
custodyStatusLabel,
|
|
53154
|
+
currentCacheKeepRealTurn,
|
|
52695
53155
|
createWindowsOwnerOnly,
|
|
52696
53156
|
createStringPatch,
|
|
52697
53157
|
createStickyNoRouteResponse,
|