@cortexkit/anthropic-auth-core 2.6.0 → 2.7.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 +13 -1
- package/dist/cachekeep.d.ts +66 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1832 -444
- package/dist/internal-types/claustrum/availability.d.ts +1 -0
- package/dist/internal-types/claustrum/index.d.ts +1 -1
- package/dist/internal-types/routing-accessor/cache-policy.d.ts +51 -0
- package/dist/internal-types/routing-accessor/index.d.ts +2 -1
- package/dist/session-cache-activity.d.ts +1 -1
- package/dist/session-cache-policy.d.ts +21 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -29,6 +29,7 @@ var VAULT_FAILURE_CLASSES = Object.freeze({
|
|
|
29
29
|
unavailable: "unreachable",
|
|
30
30
|
timeout: "unreachable",
|
|
31
31
|
route_closed: "unreachable",
|
|
32
|
+
route_busy: "unreachable",
|
|
32
33
|
daemon_draining: "unreachable",
|
|
33
34
|
connection_closed: "unreachable",
|
|
34
35
|
connection_dropped: "unreachable",
|
|
@@ -6889,6 +6890,111 @@ function routingHandle(sessionId) {
|
|
|
6889
6890
|
return typeof handle === "object" && handle !== null ? handle : undefined;
|
|
6890
6891
|
}
|
|
6891
6892
|
|
|
6893
|
+
// ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/cache-policy.js
|
|
6894
|
+
var warned = new Set;
|
|
6895
|
+
function shape(value, seen = new Set) {
|
|
6896
|
+
if (typeof value !== "object" || value === null) {
|
|
6897
|
+
return `${typeof value}:${String(value)}`;
|
|
6898
|
+
}
|
|
6899
|
+
if (seen.has(value))
|
|
6900
|
+
return "cycle";
|
|
6901
|
+
seen.add(value);
|
|
6902
|
+
return `${Array.isArray(value) ? "array" : "object"}:{${Object.entries(Object.getOwnPropertyDescriptors(value)).sort(([a], [b]) => a.localeCompare(b)).map(([key, descriptor]) => `${key}:${"value" in descriptor ? shape(descriptor.value, seen) : "accessor"}`).join(",")}}`;
|
|
6903
|
+
}
|
|
6904
|
+
function invalid(kind, value) {
|
|
6905
|
+
let fingerprint = "unreadable";
|
|
6906
|
+
try {
|
|
6907
|
+
fingerprint = shape(value);
|
|
6908
|
+
} catch {}
|
|
6909
|
+
try {
|
|
6910
|
+
const key = `${kind}:${fingerprint}`;
|
|
6911
|
+
if (!warned.has(key)) {
|
|
6912
|
+
warned.add(key);
|
|
6913
|
+
console.warn(`[common-auth] Ignoring invalid session ${kind} policy`);
|
|
6914
|
+
}
|
|
6915
|
+
} catch {}
|
|
6916
|
+
return null;
|
|
6917
|
+
}
|
|
6918
|
+
function record2(value) {
|
|
6919
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6920
|
+
}
|
|
6921
|
+
function rejectAsync(value) {
|
|
6922
|
+
if (typeof value.then !== "function")
|
|
6923
|
+
return false;
|
|
6924
|
+
Promise.resolve(value).catch(() => {});
|
|
6925
|
+
return true;
|
|
6926
|
+
}
|
|
6927
|
+
function onlyKeys(value, keys) {
|
|
6928
|
+
return Reflect.ownKeys(value).every((key) => typeof key === "string" && keys.includes(key));
|
|
6929
|
+
}
|
|
6930
|
+
function sessionCachePolicy(sessionId) {
|
|
6931
|
+
let answer;
|
|
6932
|
+
try {
|
|
6933
|
+
const handle = routingHandle(sessionId);
|
|
6934
|
+
if (!handle)
|
|
6935
|
+
return null;
|
|
6936
|
+
const read = handle.cache;
|
|
6937
|
+
if (typeof read !== "function")
|
|
6938
|
+
return null;
|
|
6939
|
+
answer = read.call(handle);
|
|
6940
|
+
if (answer === null)
|
|
6941
|
+
return null;
|
|
6942
|
+
if (!record2(answer) || rejectAsync(answer))
|
|
6943
|
+
return invalid("cache", answer);
|
|
6944
|
+
const { ttl, keep_warm, hours } = answer;
|
|
6945
|
+
if (!onlyKeys(answer, ["ttl", "keep_warm", "hours"]) || ttl !== undefined && ttl !== "none" && ttl !== "short" && ttl !== "long" || keep_warm !== undefined && keep_warm !== "off" && keep_warm !== "hours" && keep_warm !== "always" && keep_warm !== "auto" || ttl === "none" && keep_warm !== undefined && keep_warm !== "off" || keep_warm !== "hours" && "hours" in answer) {
|
|
6946
|
+
return invalid("cache", answer);
|
|
6947
|
+
}
|
|
6948
|
+
const policy = {
|
|
6949
|
+
...ttl !== undefined ? { ttl } : {},
|
|
6950
|
+
...keep_warm !== undefined ? { keep_warm } : {}
|
|
6951
|
+
};
|
|
6952
|
+
if (keep_warm === "hours") {
|
|
6953
|
+
if (!record2(hours) || !onlyKeys(hours, ["from", "to", "tz"])) {
|
|
6954
|
+
return invalid("cache", answer);
|
|
6955
|
+
}
|
|
6956
|
+
const { from, to, tz } = hours;
|
|
6957
|
+
const time = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
|
|
6958
|
+
if (typeof from !== "string" || !time.test(from) || typeof to !== "string" || !time.test(to) || from === to || typeof tz !== "string" || tz.length === 0) {
|
|
6959
|
+
return invalid("cache", answer);
|
|
6960
|
+
}
|
|
6961
|
+
new Intl.DateTimeFormat("en", { timeZone: tz });
|
|
6962
|
+
policy.hours = { from, to, tz };
|
|
6963
|
+
}
|
|
6964
|
+
return policy;
|
|
6965
|
+
} catch {
|
|
6966
|
+
return invalid("cache", answer);
|
|
6967
|
+
}
|
|
6968
|
+
}
|
|
6969
|
+
function report(sessionId, payload) {
|
|
6970
|
+
const handle = routingHandle(sessionId);
|
|
6971
|
+
if (!handle)
|
|
6972
|
+
return;
|
|
6973
|
+
const send = handle.report;
|
|
6974
|
+
if (typeof send !== "function")
|
|
6975
|
+
return;
|
|
6976
|
+
const pending = send.call(handle, payload);
|
|
6977
|
+
if (record2(pending) && typeof pending.then === "function") {
|
|
6978
|
+
Promise.resolve(pending).catch(() => {});
|
|
6979
|
+
}
|
|
6980
|
+
}
|
|
6981
|
+
function reportCacheTouch(sessionId, input) {
|
|
6982
|
+
try {
|
|
6983
|
+
const { at, ttlMs, source } = input;
|
|
6984
|
+
if (!Number.isSafeInteger(at) || at < 0 || ttlMs !== "implicit" && (typeof ttlMs !== "number" || !Number.isFinite(ttlMs) || ttlMs < 0) || source !== "response" && source !== "warm")
|
|
6985
|
+
return;
|
|
6986
|
+
report(sessionId, { kind: "cache_touch", at, ttl_ms: ttlMs, source });
|
|
6987
|
+
} catch {}
|
|
6988
|
+
}
|
|
6989
|
+
function reportCacheWarmStopped(sessionId, input) {
|
|
6990
|
+
try {
|
|
6991
|
+
const { at, reason } = input;
|
|
6992
|
+
if (!Number.isSafeInteger(at) || at < 0 || typeof reason !== "string")
|
|
6993
|
+
return;
|
|
6994
|
+
report(sessionId, { kind: "cache_warm_stopped", at, reason });
|
|
6995
|
+
} catch {}
|
|
6996
|
+
}
|
|
6997
|
+
|
|
6892
6998
|
// ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
|
|
6893
6999
|
function isObject(value) {
|
|
6894
7000
|
return typeof value === "object" && value !== null;
|
|
@@ -6985,8 +7091,8 @@ function reportRouting(input) {
|
|
|
6985
7091
|
const handle = routingHandle(input.sessionId);
|
|
6986
7092
|
if (!handle)
|
|
6987
7093
|
return;
|
|
6988
|
-
const
|
|
6989
|
-
if (typeof
|
|
7094
|
+
const report2 = handle.report;
|
|
7095
|
+
if (typeof report2 !== "function")
|
|
6990
7096
|
return;
|
|
6991
7097
|
let payload;
|
|
6992
7098
|
if ("kind" in input) {
|
|
@@ -7044,7 +7150,7 @@ function reportRouting(input) {
|
|
|
7044
7150
|
return;
|
|
7045
7151
|
}
|
|
7046
7152
|
}
|
|
7047
|
-
const pending =
|
|
7153
|
+
const pending = report2.call(handle, payload);
|
|
7048
7154
|
if (isObject(pending) && typeof pending.then === "function") {
|
|
7049
7155
|
Promise.resolve(pending).catch(() => {});
|
|
7050
7156
|
}
|
|
@@ -8497,7 +8603,7 @@ function validatePlugin(plugin) {
|
|
|
8497
8603
|
}
|
|
8498
8604
|
}
|
|
8499
8605
|
async function enrollmentReport(plugin, hosts, recorded) {
|
|
8500
|
-
const
|
|
8606
|
+
const report2 = [];
|
|
8501
8607
|
for (const host of hosts) {
|
|
8502
8608
|
let outcome = recorded.get(host) ?? "not-enrolled";
|
|
8503
8609
|
if (outcome === "unknown") {
|
|
@@ -8508,9 +8614,9 @@ async function enrollmentReport(plugin, hosts, recorded) {
|
|
|
8508
8614
|
else if (authority === "local")
|
|
8509
8615
|
outcome = "not-enrolled";
|
|
8510
8616
|
}
|
|
8511
|
-
|
|
8617
|
+
report2.push({ host, outcome });
|
|
8512
8618
|
}
|
|
8513
|
-
return
|
|
8619
|
+
return report2;
|
|
8514
8620
|
}
|
|
8515
8621
|
async function runSetup(plugin, argv = [], io = {}) {
|
|
8516
8622
|
const options = parseSetupFlags(argv);
|
|
@@ -8670,9 +8776,9 @@ ${write.content}`);
|
|
|
8670
8776
|
if (enrollment.size === 0)
|
|
8671
8777
|
throw error;
|
|
8672
8778
|
try {
|
|
8673
|
-
const
|
|
8674
|
-
recordSetupEnrollment(error,
|
|
8675
|
-
for (const entry of
|
|
8779
|
+
const report2 = await enrollmentReport(plugin, hosts, enrollment);
|
|
8780
|
+
recordSetupEnrollment(error, report2);
|
|
8781
|
+
for (const entry of report2)
|
|
8676
8782
|
printLine(terminal, setupEnrollmentLine(entry));
|
|
8677
8783
|
} catch {}
|
|
8678
8784
|
throw error;
|
|
@@ -10755,6 +10861,694 @@ function executeCache1hCommand(input) {
|
|
|
10755
10861
|
// src/cachekeep.ts
|
|
10756
10862
|
import { createHash as createHash9 } from "node:crypto";
|
|
10757
10863
|
|
|
10864
|
+
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/decision.js
|
|
10865
|
+
function withinHours(hours, at) {
|
|
10866
|
+
const parts = new Intl.DateTimeFormat("en-GB", {
|
|
10867
|
+
timeZone: hours.tz,
|
|
10868
|
+
hour: "2-digit",
|
|
10869
|
+
minute: "2-digit",
|
|
10870
|
+
hourCycle: "h23"
|
|
10871
|
+
}).formatToParts(at);
|
|
10872
|
+
const hour = parts.find((part) => part.type === "hour")?.value;
|
|
10873
|
+
const minute = parts.find((part) => part.type === "minute")?.value;
|
|
10874
|
+
const time = `${hour}:${minute}`;
|
|
10875
|
+
return hours.from < hours.to ? time >= hours.from && time < hours.to : time >= hours.from || time < hours.to;
|
|
10876
|
+
}
|
|
10877
|
+
function decideCacheKeep(input) {
|
|
10878
|
+
const { mode, now, ttlMs, lastRealRequestAt, lastWarmAt, warmsSinceLastRealRequest, warmCostSoFar, nextWarmCost, rewriteCost } = input;
|
|
10879
|
+
if (mode === "off")
|
|
10880
|
+
return { action: "stop", reason: "unsupported" };
|
|
10881
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
10882
|
+
return { action: "stop", reason: "unsupported" };
|
|
10883
|
+
}
|
|
10884
|
+
if ((mode === "hours" || mode === "always") && warmsSinceLastRealRequest >= 24)
|
|
10885
|
+
return { action: "stop", reason: "count-cap" };
|
|
10886
|
+
if (mode === "auto" && warmCostSoFar !== undefined && nextWarmCost !== undefined && rewriteCost !== undefined && warmCostSoFar + nextWarmCost >= rewriteCost)
|
|
10887
|
+
return { action: "stop", reason: "cost-cap" };
|
|
10888
|
+
const last = Math.max(lastRealRequestAt, lastWarmAt ?? lastRealRequestAt);
|
|
10889
|
+
const expiresAt = last + ttlMs;
|
|
10890
|
+
const due = expiresAt - Math.min(30000, ttlMs / 2);
|
|
10891
|
+
const at = Math.max(now, due);
|
|
10892
|
+
if (at >= expiresAt - Math.min(5000, ttlMs / 10)) {
|
|
10893
|
+
return { action: "stop", reason: "cost-cap" };
|
|
10894
|
+
}
|
|
10895
|
+
if (mode === "hours" && (!withinHours(input.hours, due) || !withinHours(input.hours, at)))
|
|
10896
|
+
return { action: "stop", reason: "outside-hours" };
|
|
10897
|
+
return now < due ? { action: "wait", until: due } : { action: "warm", at };
|
|
10898
|
+
}
|
|
10899
|
+
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/failure.js
|
|
10900
|
+
var ERROR_NAMES = ["AbortError", "TimeoutError", "TypeError"];
|
|
10901
|
+
var NETWORK_CODES = [
|
|
10902
|
+
"ECONNRESET",
|
|
10903
|
+
"ECONNREFUSED",
|
|
10904
|
+
"ETIMEDOUT",
|
|
10905
|
+
"EPIPE",
|
|
10906
|
+
"ENOTFOUND",
|
|
10907
|
+
"EAI_AGAIN",
|
|
10908
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
10909
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
10910
|
+
"UND_ERR_HEADERS_OVERFLOW",
|
|
10911
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
10912
|
+
"UND_ERR_RESPONSE_STATUS_CODE",
|
|
10913
|
+
"UND_ERR_INVALID_ARG",
|
|
10914
|
+
"UND_ERR_INVALID_RETURN_VALUE",
|
|
10915
|
+
"UND_ERR_ABORTED",
|
|
10916
|
+
"UND_ERR_CLIENT_DESTROYED",
|
|
10917
|
+
"UND_ERR_CLIENT_CLOSED",
|
|
10918
|
+
"UND_ERR_SOCKET",
|
|
10919
|
+
"UND_ERR_NOT_SUPPORTED",
|
|
10920
|
+
"UND_ERR_REQ_CONTENT_LENGTH_MISMATCH",
|
|
10921
|
+
"UND_ERR_RES_CONTENT_LENGTH_MISMATCH",
|
|
10922
|
+
"UND_ERR_INFO",
|
|
10923
|
+
"UND_ERR_RES_EXCEEDED_MAX_SIZE",
|
|
10924
|
+
"UND_ERR_PRX_TLS"
|
|
10925
|
+
];
|
|
10926
|
+
function allowed(values, value) {
|
|
10927
|
+
return typeof value === "string" && values.includes(value);
|
|
10928
|
+
}
|
|
10929
|
+
function classifyFailure(error, stage, status) {
|
|
10930
|
+
try {
|
|
10931
|
+
if (status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599 && (status < 200 || status >= 300)) {
|
|
10932
|
+
return { stage: "response", class: status };
|
|
10933
|
+
}
|
|
10934
|
+
if (typeof error === "object" && error !== null) {
|
|
10935
|
+
const fields2 = error;
|
|
10936
|
+
const name = fields2.name;
|
|
10937
|
+
if (name === "AbortError" || name === "TimeoutError")
|
|
10938
|
+
return { stage, class: name };
|
|
10939
|
+
const code = fields2.code;
|
|
10940
|
+
if (allowed(NETWORK_CODES, code))
|
|
10941
|
+
return { stage, class: code };
|
|
10942
|
+
const causeCode = fields2.cause?.code;
|
|
10943
|
+
if (allowed(NETWORK_CODES, causeCode))
|
|
10944
|
+
return { stage, class: causeCode };
|
|
10945
|
+
if (allowed(ERROR_NAMES, name))
|
|
10946
|
+
return { stage, class: name };
|
|
10947
|
+
}
|
|
10948
|
+
} catch {}
|
|
10949
|
+
return { stage, class: "unknown" };
|
|
10950
|
+
}
|
|
10951
|
+
|
|
10952
|
+
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/window.js
|
|
10953
|
+
function isWithinCacheKeepWindow(window, now = new Date) {
|
|
10954
|
+
if (!window)
|
|
10955
|
+
return false;
|
|
10956
|
+
const hour = now.getHours();
|
|
10957
|
+
if (window.startHour < window.endHour) {
|
|
10958
|
+
return hour >= window.startHour && hour < window.endHour;
|
|
10959
|
+
}
|
|
10960
|
+
return hour >= window.startHour || hour < window.endHour;
|
|
10961
|
+
}
|
|
10962
|
+
|
|
10963
|
+
// ../../node_modules/@cortexkit/common-auth/dist/cachekeep/manager.js
|
|
10964
|
+
var DEFAULT_TTL_MS = 5 * 60000;
|
|
10965
|
+
var DEFAULT_MAX_IDLE_WARM_MS = 60 * 60000;
|
|
10966
|
+
var DEFAULT_MAX_SUBAGENT_IDLE_MS = 30 * 60000;
|
|
10967
|
+
var DEFAULT_TICK_INTERVAL_MS = 60000;
|
|
10968
|
+
var DEFAULT_MAX_TARGETS = 32;
|
|
10969
|
+
var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
10970
|
+
var DEFAULT_WARM_TIMEOUT_MS = 30000;
|
|
10971
|
+
var DEFAULT_BACKOFF_MS = 10 * 60000;
|
|
10972
|
+
var TRANSIENT_RETRY_STEP_MS = 20000;
|
|
10973
|
+
var TRANSIENT_RETRY_MAX_MS = 60000;
|
|
10974
|
+
var EXPIRY_SAFETY_MS = 5000;
|
|
10975
|
+
function positive(value, fallback) {
|
|
10976
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
10977
|
+
}
|
|
10978
|
+
|
|
10979
|
+
class CacheKeepManager {
|
|
10980
|
+
targets = new Map;
|
|
10981
|
+
adapter;
|
|
10982
|
+
now;
|
|
10983
|
+
log;
|
|
10984
|
+
ttlMs;
|
|
10985
|
+
leadMs;
|
|
10986
|
+
maxIdleWarmMs;
|
|
10987
|
+
maxSubagentIdleMs;
|
|
10988
|
+
tickIntervalMs;
|
|
10989
|
+
maxTargets;
|
|
10990
|
+
maxBytes;
|
|
10991
|
+
warmTimeoutMs;
|
|
10992
|
+
backoff;
|
|
10993
|
+
getWindow;
|
|
10994
|
+
getSustain;
|
|
10995
|
+
setIntervalImpl;
|
|
10996
|
+
clearIntervalImpl;
|
|
10997
|
+
timer = null;
|
|
10998
|
+
startedAt = null;
|
|
10999
|
+
totalBytes = 0;
|
|
11000
|
+
tickPromise = null;
|
|
11001
|
+
disposed = false;
|
|
11002
|
+
planWarningLogged = false;
|
|
11003
|
+
abortController = new AbortController;
|
|
11004
|
+
constructor(options) {
|
|
11005
|
+
this.adapter = options.adapter;
|
|
11006
|
+
this.now = options.now;
|
|
11007
|
+
this.log = options.logger;
|
|
11008
|
+
this.ttlMs = positive(options.ttlMs, DEFAULT_TTL_MS);
|
|
11009
|
+
this.tickIntervalMs = positive(options.tickIntervalMs, DEFAULT_TICK_INTERVAL_MS);
|
|
11010
|
+
this.leadMs = positive(options.leadMs, this.tickIntervalMs + 15000);
|
|
11011
|
+
this.maxIdleWarmMs = positive(options.maxIdleWarmMs, DEFAULT_MAX_IDLE_WARM_MS);
|
|
11012
|
+
this.maxSubagentIdleMs = positive(options.maxSubagentIdleMs, DEFAULT_MAX_SUBAGENT_IDLE_MS);
|
|
11013
|
+
this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
|
|
11014
|
+
this.maxBytes = positive(options.maxBytes, DEFAULT_MAX_BYTES);
|
|
11015
|
+
this.warmTimeoutMs = positive(options.warmTimeoutMs, DEFAULT_WARM_TIMEOUT_MS);
|
|
11016
|
+
this.backoff = options.backoffMs;
|
|
11017
|
+
this.getWindow = options.getWindow;
|
|
11018
|
+
this.getSustain = options.getSustain;
|
|
11019
|
+
this.setIntervalImpl = options.setIntervalImpl ?? globalThis.setInterval;
|
|
11020
|
+
this.clearIntervalImpl = options.clearIntervalImpl ?? globalThis.clearInterval;
|
|
11021
|
+
}
|
|
11022
|
+
track(input) {
|
|
11023
|
+
const { sessionKey, bodyText } = input;
|
|
11024
|
+
const previous = this.targets.get(sessionKey);
|
|
11025
|
+
const plan = this.readPlan(sessionKey);
|
|
11026
|
+
if (!plan && previous?.plan) {
|
|
11027
|
+
this.drop(sessionKey, "session-ended");
|
|
11028
|
+
return { tracked: false, reason: "session-ended" };
|
|
11029
|
+
}
|
|
11030
|
+
if (plan?.mode === "off") {
|
|
11031
|
+
this.drop(sessionKey, "unsupported");
|
|
11032
|
+
return { tracked: false, reason: "unsupported" };
|
|
11033
|
+
}
|
|
11034
|
+
this.pruneStale(plan ? sessionKey : undefined);
|
|
11035
|
+
const bodyBytes = Buffer.byteLength(bodyText, "utf8");
|
|
11036
|
+
if (bodyBytes > this.maxBytes) {
|
|
11037
|
+
this.log?.debug("cachekeep track skipped (body exceeds maxBytes)", {
|
|
11038
|
+
sessionKey,
|
|
11039
|
+
bodyBytes,
|
|
11040
|
+
maxBytes: this.maxBytes
|
|
11041
|
+
});
|
|
11042
|
+
return { tracked: false, reason: "body-exceeds-max-bytes" };
|
|
11043
|
+
}
|
|
11044
|
+
const window = this.getWindow?.();
|
|
11045
|
+
if (!plan && window && !isWithinCacheKeepWindow(window, new Date(this.now()))) {
|
|
11046
|
+
this.log?.debug("cachekeep track skipped (outside window)", {
|
|
11047
|
+
sessionKey,
|
|
11048
|
+
startHour: window.startHour,
|
|
11049
|
+
endHour: window.endHour
|
|
11050
|
+
});
|
|
11051
|
+
return { tracked: false, reason: "outside-window" };
|
|
11052
|
+
}
|
|
11053
|
+
const hasWarmed = this.targets.get(sessionKey)?.hasWarmed ?? false;
|
|
11054
|
+
this.drop(sessionKey, null);
|
|
11055
|
+
while (this.targets.size >= this.maxTargets || this.totalBytes + bodyBytes > this.maxBytes && this.targets.size > 0) {
|
|
11056
|
+
const evictKey = this.leastRecentlyTouched();
|
|
11057
|
+
if (evictKey === undefined)
|
|
11058
|
+
break;
|
|
11059
|
+
this.log?.debug("cachekeep evicted least recently used target", {
|
|
11060
|
+
sessionKey: evictKey
|
|
11061
|
+
});
|
|
11062
|
+
this.drop(evictKey, "evicted");
|
|
11063
|
+
}
|
|
11064
|
+
const isSubagent = input.isSubagent === true;
|
|
11065
|
+
const accountId = input.accountId || undefined;
|
|
11066
|
+
const profile = this.adapter.profile?.({
|
|
11067
|
+
bodyText,
|
|
11068
|
+
isSubagent,
|
|
11069
|
+
accountId,
|
|
11070
|
+
meta: input.meta
|
|
11071
|
+
});
|
|
11072
|
+
const ttlMs = positive(profile?.ttlMs, this.ttlMs);
|
|
11073
|
+
const now = this.now();
|
|
11074
|
+
const target = {
|
|
11075
|
+
plan,
|
|
11076
|
+
warmCostSoFar: 0,
|
|
11077
|
+
hasWarmed,
|
|
11078
|
+
bodyText,
|
|
11079
|
+
bodyBytes,
|
|
11080
|
+
accountId,
|
|
11081
|
+
isSubagent,
|
|
11082
|
+
meta: input.meta,
|
|
11083
|
+
ttlMs,
|
|
11084
|
+
maxWarms: profile?.maxWarms !== undefined && profile.maxWarms > 0 ? Math.floor(profile.maxWarms) : undefined,
|
|
11085
|
+
maxIdleMs: profile?.maxIdleMs !== undefined ? positive(profile.maxIdleMs, this.idleDefault(isSubagent)) : undefined,
|
|
11086
|
+
cacheExpiresAt: now + ttlMs,
|
|
11087
|
+
lastRealRequestAt: now,
|
|
11088
|
+
failures: 0,
|
|
11089
|
+
warmCount: 0
|
|
11090
|
+
};
|
|
11091
|
+
this.targets.set(sessionKey, target);
|
|
11092
|
+
this.totalBytes += bodyBytes;
|
|
11093
|
+
this.log?.debug("cachekeep captured target", { sessionKey, accountId });
|
|
11094
|
+
this.start();
|
|
11095
|
+
if (plan)
|
|
11096
|
+
this.planDecision(sessionKey, target);
|
|
11097
|
+
return { tracked: true };
|
|
11098
|
+
}
|
|
11099
|
+
remove(sessionKey) {
|
|
11100
|
+
if (this.drop(sessionKey)) {
|
|
11101
|
+
this.log?.debug("cachekeep removed target", { sessionKey });
|
|
11102
|
+
}
|
|
11103
|
+
}
|
|
11104
|
+
start() {
|
|
11105
|
+
this.disposed = false;
|
|
11106
|
+
if (this.timer)
|
|
11107
|
+
return;
|
|
11108
|
+
this.startedAt = this.now();
|
|
11109
|
+
this.timer = this.setIntervalImpl(() => {
|
|
11110
|
+
this.tick().catch((error) => {
|
|
11111
|
+
this.log?.warn("cachekeep tick failed", classifyFailure(error, "send"));
|
|
11112
|
+
});
|
|
11113
|
+
}, this.tickIntervalMs);
|
|
11114
|
+
if (typeof this.timer === "object" && "unref" in this.timer) {
|
|
11115
|
+
this.timer.unref();
|
|
11116
|
+
}
|
|
11117
|
+
this.log?.debug("cachekeep started", {
|
|
11118
|
+
ttlMs: this.ttlMs,
|
|
11119
|
+
leadMs: this.leadMs,
|
|
11120
|
+
maxIdleWarmMs: this.maxIdleWarmMs
|
|
11121
|
+
});
|
|
11122
|
+
}
|
|
11123
|
+
stop() {
|
|
11124
|
+
this.disposed = true;
|
|
11125
|
+
this.abortController.abort();
|
|
11126
|
+
this.abortController = new AbortController;
|
|
11127
|
+
if (this.timer) {
|
|
11128
|
+
this.clearIntervalImpl(this.timer);
|
|
11129
|
+
this.timer = null;
|
|
11130
|
+
}
|
|
11131
|
+
this.startedAt = null;
|
|
11132
|
+
for (const sessionKey of this.targets.keys())
|
|
11133
|
+
this.drop(sessionKey, "stopped");
|
|
11134
|
+
this.totalBytes = 0;
|
|
11135
|
+
this.log?.debug("cachekeep stopped");
|
|
11136
|
+
}
|
|
11137
|
+
status() {
|
|
11138
|
+
const window = this.getWindow?.();
|
|
11139
|
+
return {
|
|
11140
|
+
running: this.timer !== null,
|
|
11141
|
+
tracked: this.targets.size,
|
|
11142
|
+
totalBytes: this.totalBytes,
|
|
11143
|
+
generatedAt: this.now(),
|
|
11144
|
+
startedAt: this.startedAt,
|
|
11145
|
+
ttlMs: this.ttlMs,
|
|
11146
|
+
leadMs: this.leadMs,
|
|
11147
|
+
maxIdleWarmMs: this.maxIdleWarmMs,
|
|
11148
|
+
maxSubagentIdleMs: this.maxSubagentIdleMs,
|
|
11149
|
+
sustain: this.getSustain?.() === true,
|
|
11150
|
+
...window ? { window } : {},
|
|
11151
|
+
targets: [...this.targets].map(([sessionKey, target]) => ({
|
|
11152
|
+
sessionKey,
|
|
11153
|
+
...target.plan ? { mode: target.plan.mode } : {},
|
|
11154
|
+
accountId: target.accountId,
|
|
11155
|
+
isSubagent: target.isSubagent,
|
|
11156
|
+
cacheExpiresAt: target.cacheExpiresAt,
|
|
11157
|
+
lastRealRequestAt: target.lastRealRequestAt,
|
|
11158
|
+
...target.lastWarmedAt !== undefined ? { lastWarmedAt: target.lastWarmedAt } : {},
|
|
11159
|
+
...target.backoffUntil !== undefined ? { backoffUntil: target.backoffUntil } : {},
|
|
11160
|
+
failures: target.failures,
|
|
11161
|
+
warmCount: target.warmCount,
|
|
11162
|
+
ttlMs: target.ttlMs,
|
|
11163
|
+
bodyBytes: target.bodyBytes
|
|
11164
|
+
}))
|
|
11165
|
+
};
|
|
11166
|
+
}
|
|
11167
|
+
tick() {
|
|
11168
|
+
if (this.tickPromise)
|
|
11169
|
+
return this.tickPromise;
|
|
11170
|
+
const run = this.runTick().finally(() => {
|
|
11171
|
+
if (this.tickPromise === run)
|
|
11172
|
+
this.tickPromise = null;
|
|
11173
|
+
});
|
|
11174
|
+
this.tickPromise = run;
|
|
11175
|
+
return run;
|
|
11176
|
+
}
|
|
11177
|
+
async runTick() {
|
|
11178
|
+
this.pruneStale();
|
|
11179
|
+
const window = this.getWindow?.();
|
|
11180
|
+
const outsideWindow = window && !isWithinCacheKeepWindow(window, new Date(this.now()));
|
|
11181
|
+
for (const [sessionKey, target] of [...this.targets]) {
|
|
11182
|
+
if (this.disposed)
|
|
11183
|
+
return;
|
|
11184
|
+
if (this.targets.get(sessionKey) !== target)
|
|
11185
|
+
continue;
|
|
11186
|
+
if (!this.refreshPlan(sessionKey, target))
|
|
11187
|
+
continue;
|
|
11188
|
+
const now = this.now();
|
|
11189
|
+
if (target.plan) {
|
|
11190
|
+
const decision = this.planDecision(sessionKey, target);
|
|
11191
|
+
if (decision.action !== "warm")
|
|
11192
|
+
continue;
|
|
11193
|
+
if (target.backoffUntil !== undefined && now < target.backoffUntil) {
|
|
11194
|
+
this.schedulePlan(sessionKey, target, target.backoffUntil);
|
|
11195
|
+
continue;
|
|
11196
|
+
}
|
|
11197
|
+
} else {
|
|
11198
|
+
if (outsideWindow)
|
|
11199
|
+
continue;
|
|
11200
|
+
if (target.cacheExpiresAt > now + this.leadMs)
|
|
11201
|
+
continue;
|
|
11202
|
+
}
|
|
11203
|
+
if (target.backoffUntil !== undefined && now < target.backoffUntil) {
|
|
11204
|
+
continue;
|
|
11205
|
+
}
|
|
11206
|
+
if (!this.canRetry(target))
|
|
11207
|
+
continue;
|
|
11208
|
+
await this.warm(sessionKey, target);
|
|
11209
|
+
}
|
|
11210
|
+
}
|
|
11211
|
+
retireIfExpired(sessionKey, target) {
|
|
11212
|
+
if (this.now() < target.cacheExpiresAt)
|
|
11213
|
+
return false;
|
|
11214
|
+
this.log?.debug("cachekeep retired target (cache lifetime ended)", {
|
|
11215
|
+
sessionKey,
|
|
11216
|
+
accountId: target.accountId,
|
|
11217
|
+
cacheExpiresAt: target.cacheExpiresAt,
|
|
11218
|
+
failures: target.failures
|
|
11219
|
+
});
|
|
11220
|
+
this.drop(sessionKey, target.plan ? "cost-cap" : "expired");
|
|
11221
|
+
return true;
|
|
11222
|
+
}
|
|
11223
|
+
isCurrent(sessionKey, target) {
|
|
11224
|
+
return !this.disposed && this.targets.get(sessionKey) === target;
|
|
11225
|
+
}
|
|
11226
|
+
view(sessionKey, target) {
|
|
11227
|
+
return {
|
|
11228
|
+
sessionKey,
|
|
11229
|
+
accountId: target.accountId,
|
|
11230
|
+
bodyText: target.bodyText,
|
|
11231
|
+
isSubagent: target.isSubagent,
|
|
11232
|
+
meta: target.meta,
|
|
11233
|
+
warmCount: target.warmCount,
|
|
11234
|
+
ttlMs: target.ttlMs
|
|
11235
|
+
};
|
|
11236
|
+
}
|
|
11237
|
+
readPlan(sessionKey) {
|
|
11238
|
+
try {
|
|
11239
|
+
return this.adapter.plan?.(sessionKey);
|
|
11240
|
+
} catch {
|
|
11241
|
+
if (!this.planWarningLogged) {
|
|
11242
|
+
this.planWarningLogged = true;
|
|
11243
|
+
this.log?.warn("cachekeep plan unavailable");
|
|
11244
|
+
}
|
|
11245
|
+
return;
|
|
11246
|
+
}
|
|
11247
|
+
}
|
|
11248
|
+
refreshPlan(sessionKey, target) {
|
|
11249
|
+
const plan = this.readPlan(sessionKey);
|
|
11250
|
+
if (!plan && target.plan) {
|
|
11251
|
+
this.drop(sessionKey, "session-ended");
|
|
11252
|
+
return false;
|
|
11253
|
+
}
|
|
11254
|
+
target.plan = plan;
|
|
11255
|
+
if (plan?.mode === "off") {
|
|
11256
|
+
this.drop(sessionKey, "unsupported");
|
|
11257
|
+
return false;
|
|
11258
|
+
}
|
|
11259
|
+
return true;
|
|
11260
|
+
}
|
|
11261
|
+
usesLegacyBounds(target) {
|
|
11262
|
+
return !target.plan || target.plan.mode === "auto" && !target.plan.costs;
|
|
11263
|
+
}
|
|
11264
|
+
planDecision(sessionKey, target) {
|
|
11265
|
+
const plan = target.plan;
|
|
11266
|
+
if (!plan)
|
|
11267
|
+
return { action: "stop", reason: "session-ended" };
|
|
11268
|
+
if (this.usesLegacyBounds(target)) {
|
|
11269
|
+
if (this.retireIfIdle(sessionKey, target, this.getSustain?.() === true)) {
|
|
11270
|
+
return { action: "stop", reason: "idle" };
|
|
11271
|
+
}
|
|
11272
|
+
if (target.maxWarms !== undefined && target.warmCount >= target.maxWarms) {
|
|
11273
|
+
this.drop(sessionKey, "count-cap");
|
|
11274
|
+
return { action: "stop", reason: "count-cap" };
|
|
11275
|
+
}
|
|
11276
|
+
}
|
|
11277
|
+
const decision = plan.mode === "hours" && !plan.hours ? { action: "stop", reason: "unsupported" } : decideCacheKeep({
|
|
11278
|
+
...plan.mode === "hours" ? { mode: plan.mode, hours: plan.hours } : { mode: plan.mode },
|
|
11279
|
+
now: this.now(),
|
|
11280
|
+
ttlMs: target.ttlMs,
|
|
11281
|
+
lastRealRequestAt: target.lastRealRequestAt,
|
|
11282
|
+
lastWarmAt: target.lastWarmedAt,
|
|
11283
|
+
warmsSinceLastRealRequest: target.warmCount,
|
|
11284
|
+
...plan.costs ? {
|
|
11285
|
+
warmCostSoFar: target.warmCostSoFar,
|
|
11286
|
+
nextWarmCost: plan.costs.nextWarm,
|
|
11287
|
+
rewriteCost: plan.costs.rewrite
|
|
11288
|
+
} : {}
|
|
11289
|
+
});
|
|
11290
|
+
if (decision.action === "stop")
|
|
11291
|
+
this.drop(sessionKey, decision.reason);
|
|
11292
|
+
else if (decision.action === "wait") {
|
|
11293
|
+
this.schedulePlan(sessionKey, target, Math.max(decision.until, target.backoffUntil ?? 0));
|
|
11294
|
+
} else
|
|
11295
|
+
this.clearPlanTimer(target);
|
|
11296
|
+
return decision;
|
|
11297
|
+
}
|
|
11298
|
+
clearPlanTimer(target) {
|
|
11299
|
+
if (target.planTimer === undefined)
|
|
11300
|
+
return;
|
|
11301
|
+
this.clearIntervalImpl(target.planTimer);
|
|
11302
|
+
target.planTimer = undefined;
|
|
11303
|
+
target.planDueAt = undefined;
|
|
11304
|
+
}
|
|
11305
|
+
schedulePlan(sessionKey, target, until) {
|
|
11306
|
+
if (target.planTimer !== undefined && target.planDueAt === until)
|
|
11307
|
+
return;
|
|
11308
|
+
this.clearPlanTimer(target);
|
|
11309
|
+
target.planDueAt = until;
|
|
11310
|
+
target.planTimer = this.setIntervalImpl(() => {
|
|
11311
|
+
this.clearPlanTimer(target);
|
|
11312
|
+
return (async () => {
|
|
11313
|
+
await this.tickPromise;
|
|
11314
|
+
if (this.isCurrent(sessionKey, target))
|
|
11315
|
+
await this.tick();
|
|
11316
|
+
})().catch((error) => {
|
|
11317
|
+
this.log?.warn("cachekeep tick failed", classifyFailure(error, "send"));
|
|
11318
|
+
});
|
|
11319
|
+
}, Math.max(0, until - this.now()));
|
|
11320
|
+
if (typeof target.planTimer === "object" && "unref" in target.planTimer) {
|
|
11321
|
+
target.planTimer.unref();
|
|
11322
|
+
}
|
|
11323
|
+
}
|
|
11324
|
+
report(callback) {
|
|
11325
|
+
try {
|
|
11326
|
+
Promise.resolve(callback()).catch(() => {
|
|
11327
|
+
this.log?.debug("cachekeep report failed");
|
|
11328
|
+
});
|
|
11329
|
+
} catch {
|
|
11330
|
+
this.log?.debug("cachekeep report failed");
|
|
11331
|
+
}
|
|
11332
|
+
}
|
|
11333
|
+
fail(sessionKey, target, message, failure, transient = false, status) {
|
|
11334
|
+
if (!this.isCurrent(sessionKey, target))
|
|
11335
|
+
return;
|
|
11336
|
+
target.failures += 1;
|
|
11337
|
+
const now = this.now();
|
|
11338
|
+
let delay3 = typeof this.backoff === "function" ? this.backoff({ sessionKey, failures: target.failures }) : this.backoff ?? DEFAULT_BACKOFF_MS;
|
|
11339
|
+
const deadline = this.lastRetryStart(target);
|
|
11340
|
+
const fastRetry = this.backoff === undefined && transient && now < deadline;
|
|
11341
|
+
if (fastRetry) {
|
|
11342
|
+
delay3 = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
|
|
11343
|
+
}
|
|
11344
|
+
target.backoffUntil = now + (Number.isFinite(delay3) && delay3 > 0 ? delay3 : 0);
|
|
11345
|
+
this.clearRetry(target);
|
|
11346
|
+
if (fastRetry)
|
|
11347
|
+
this.scheduleRetry(sessionKey, target, delay3);
|
|
11348
|
+
else if (target.plan) {
|
|
11349
|
+
this.schedulePlan(sessionKey, target, target.backoffUntil);
|
|
11350
|
+
}
|
|
11351
|
+
this.log?.warn(message, {
|
|
11352
|
+
sessionKey,
|
|
11353
|
+
accountId: target.accountId,
|
|
11354
|
+
failures: target.failures,
|
|
11355
|
+
backoffUntil: target.backoffUntil,
|
|
11356
|
+
...failure,
|
|
11357
|
+
...status !== undefined && { status }
|
|
11358
|
+
});
|
|
11359
|
+
}
|
|
11360
|
+
lastRetryStart(target) {
|
|
11361
|
+
return target.cacheExpiresAt - this.warmTimeoutMs - EXPIRY_SAFETY_MS;
|
|
11362
|
+
}
|
|
11363
|
+
canRetry(target) {
|
|
11364
|
+
return this.backoff !== undefined || target.failures === 0 || this.now() <= this.lastRetryStart(target);
|
|
11365
|
+
}
|
|
11366
|
+
clearRetry(target) {
|
|
11367
|
+
if (target.retryTimer === undefined)
|
|
11368
|
+
return;
|
|
11369
|
+
this.clearIntervalImpl(target.retryTimer);
|
|
11370
|
+
target.retryTimer = undefined;
|
|
11371
|
+
}
|
|
11372
|
+
scheduleRetry(sessionKey, target, delay3) {
|
|
11373
|
+
target.retryTimer = this.setIntervalImpl(() => {
|
|
11374
|
+
this.clearRetry(target);
|
|
11375
|
+
return (async () => {
|
|
11376
|
+
await this.tickPromise;
|
|
11377
|
+
if (this.isCurrent(sessionKey, target))
|
|
11378
|
+
await this.tick();
|
|
11379
|
+
})().catch((error) => {
|
|
11380
|
+
this.log?.warn("cachekeep tick failed", classifyFailure(error, "send"));
|
|
11381
|
+
});
|
|
11382
|
+
}, delay3);
|
|
11383
|
+
if (typeof target.retryTimer === "object" && "unref" in target.retryTimer) {
|
|
11384
|
+
target.retryTimer.unref();
|
|
11385
|
+
}
|
|
11386
|
+
}
|
|
11387
|
+
async warm(sessionKey, target) {
|
|
11388
|
+
if (this.retireIfExpired(sessionKey, target))
|
|
11389
|
+
return;
|
|
11390
|
+
if (!this.canRetry(target))
|
|
11391
|
+
return;
|
|
11392
|
+
this.clearRetry(target);
|
|
11393
|
+
const view = this.view(sessionKey, target);
|
|
11394
|
+
if (this.adapter.activeAccount) {
|
|
11395
|
+
let active;
|
|
11396
|
+
try {
|
|
11397
|
+
active = await this.adapter.activeAccount(sessionKey, view);
|
|
11398
|
+
} catch (error) {
|
|
11399
|
+
this.fail(sessionKey, target, "cachekeep skip (active account unknown)", classifyFailure(error, "authorization"), true);
|
|
11400
|
+
return;
|
|
11401
|
+
}
|
|
11402
|
+
if (!this.isCurrent(sessionKey, target))
|
|
11403
|
+
return;
|
|
11404
|
+
if (active !== undefined && active !== target.accountId) {
|
|
11405
|
+
this.log?.debug("cachekeep dropped target (session changed account)", {
|
|
11406
|
+
sessionKey,
|
|
11407
|
+
accountId: target.accountId,
|
|
11408
|
+
activeAccountId: active
|
|
11409
|
+
});
|
|
11410
|
+
this.drop(sessionKey, "account-changed");
|
|
11411
|
+
return;
|
|
11412
|
+
}
|
|
11413
|
+
}
|
|
11414
|
+
let body;
|
|
11415
|
+
try {
|
|
11416
|
+
body = await this.adapter.buildBody(view);
|
|
11417
|
+
} catch (error) {
|
|
11418
|
+
this.fail(sessionKey, target, "cachekeep skip (replay body unbuildable)", classifyFailure(error, "authorization"));
|
|
11419
|
+
return;
|
|
11420
|
+
}
|
|
11421
|
+
if (!this.isCurrent(sessionKey, target))
|
|
11422
|
+
return;
|
|
11423
|
+
if (this.retireIfExpired(sessionKey, target))
|
|
11424
|
+
return;
|
|
11425
|
+
if (!this.canRetry(target))
|
|
11426
|
+
return;
|
|
11427
|
+
if (!this.refreshPlan(sessionKey, target))
|
|
11428
|
+
return;
|
|
11429
|
+
if (target.plan && this.planDecision(sessionKey, target).action !== "warm") {
|
|
11430
|
+
return;
|
|
11431
|
+
}
|
|
11432
|
+
const nextWarmCost = target.plan?.costs?.nextWarm ?? 0;
|
|
11433
|
+
const combined = combineAbortSignals([
|
|
11434
|
+
AbortSignal.timeout(this.warmTimeoutMs),
|
|
11435
|
+
this.abortController.signal
|
|
11436
|
+
]);
|
|
11437
|
+
const signal = combined.signal;
|
|
11438
|
+
let response;
|
|
11439
|
+
let text = "";
|
|
11440
|
+
let stage = "send";
|
|
11441
|
+
let status;
|
|
11442
|
+
try {
|
|
11443
|
+
response = await this.adapter.send({ target: view, body, signal });
|
|
11444
|
+
stage = "response";
|
|
11445
|
+
status = response.status;
|
|
11446
|
+
text = await response.text();
|
|
11447
|
+
} catch (error) {
|
|
11448
|
+
this.fail(sessionKey, target, "cachekeep failed", classifyFailure(error, stage, status), status === undefined || status >= 200 && status < 300 || status === 408 || status === 429 || status >= 500, status);
|
|
11449
|
+
return;
|
|
11450
|
+
} finally {
|
|
11451
|
+
combined.dispose();
|
|
11452
|
+
}
|
|
11453
|
+
if (!this.isCurrent(sessionKey, target))
|
|
11454
|
+
return;
|
|
11455
|
+
if (!response.ok) {
|
|
11456
|
+
this.fail(sessionKey, target, "cachekeep failed", classifyFailure(undefined, "response", response.status), response.status === 408 || response.status === 429 || response.status >= 500, response.status);
|
|
11457
|
+
return;
|
|
11458
|
+
}
|
|
11459
|
+
let usage;
|
|
11460
|
+
try {
|
|
11461
|
+
usage = this.adapter.readUsage?.({ target: view, response, text });
|
|
11462
|
+
} catch {}
|
|
11463
|
+
const now = this.now();
|
|
11464
|
+
target.cacheExpiresAt = now + target.ttlMs;
|
|
11465
|
+
target.lastWarmedAt = now;
|
|
11466
|
+
target.backoffUntil = undefined;
|
|
11467
|
+
this.clearRetry(target);
|
|
11468
|
+
target.failures = 0;
|
|
11469
|
+
target.warmCount += 1;
|
|
11470
|
+
target.hasWarmed = true;
|
|
11471
|
+
target.warmCostSoFar += nextWarmCost;
|
|
11472
|
+
if (this.adapter.onWarmed) {
|
|
11473
|
+
this.report(() => this.adapter.onWarmed?.(sessionKey, { at: now }));
|
|
11474
|
+
}
|
|
11475
|
+
this.log?.debug("cachekeep fired", {
|
|
11476
|
+
sessionKey,
|
|
11477
|
+
accountId: target.accountId,
|
|
11478
|
+
warmCount: target.warmCount,
|
|
11479
|
+
...usage
|
|
11480
|
+
});
|
|
11481
|
+
if (this.usesLegacyBounds(target) && target.maxWarms !== undefined && target.warmCount >= target.maxWarms) {
|
|
11482
|
+
this.log?.debug("cachekeep retired target (warm cap reached)", {
|
|
11483
|
+
sessionKey,
|
|
11484
|
+
warmCount: target.warmCount
|
|
11485
|
+
});
|
|
11486
|
+
this.drop(sessionKey, "count-cap");
|
|
11487
|
+
}
|
|
11488
|
+
if (target.plan && this.isCurrent(sessionKey, target)) {
|
|
11489
|
+
if (this.refreshPlan(sessionKey, target))
|
|
11490
|
+
this.planDecision(sessionKey, target);
|
|
11491
|
+
}
|
|
11492
|
+
}
|
|
11493
|
+
idleDefault(isSubagent) {
|
|
11494
|
+
return isSubagent ? this.maxSubagentIdleMs : this.maxIdleWarmMs;
|
|
11495
|
+
}
|
|
11496
|
+
pruneStale(skipSessionKey) {
|
|
11497
|
+
const now = this.now();
|
|
11498
|
+
const sustain = this.getSustain?.() === true;
|
|
11499
|
+
for (const [sessionKey, target] of [...this.targets]) {
|
|
11500
|
+
if (sessionKey === skipSessionKey)
|
|
11501
|
+
continue;
|
|
11502
|
+
if (this.retireIfExpired(sessionKey, target))
|
|
11503
|
+
continue;
|
|
11504
|
+
if (!this.refreshPlan(sessionKey, target))
|
|
11505
|
+
continue;
|
|
11506
|
+
if (!this.usesLegacyBounds(target))
|
|
11507
|
+
continue;
|
|
11508
|
+
this.retireIfIdle(sessionKey, target, sustain, now);
|
|
11509
|
+
}
|
|
11510
|
+
}
|
|
11511
|
+
retireIfIdle(sessionKey, target, sustain, now = this.now()) {
|
|
11512
|
+
if (sustain && !target.isSubagent)
|
|
11513
|
+
return false;
|
|
11514
|
+
const maxIdleMs = target.maxIdleMs ?? this.idleDefault(target.isSubagent);
|
|
11515
|
+
if (target.lastRealRequestAt >= now - maxIdleMs)
|
|
11516
|
+
return false;
|
|
11517
|
+
this.log?.debug("cachekeep pruned idle target", {
|
|
11518
|
+
sessionKey,
|
|
11519
|
+
accountId: target.accountId,
|
|
11520
|
+
lastRealRequestAt: target.lastRealRequestAt,
|
|
11521
|
+
maxIdleMs
|
|
11522
|
+
});
|
|
11523
|
+
this.drop(sessionKey, "idle");
|
|
11524
|
+
return true;
|
|
11525
|
+
}
|
|
11526
|
+
leastRecentlyTouched() {
|
|
11527
|
+
let evictKey;
|
|
11528
|
+
let evictTouchedAt = Number.POSITIVE_INFINITY;
|
|
11529
|
+
for (const [key, target] of this.targets) {
|
|
11530
|
+
const touchedAt = Math.max(target.lastRealRequestAt, target.lastWarmedAt ?? 0);
|
|
11531
|
+
if (touchedAt < evictTouchedAt) {
|
|
11532
|
+
evictKey = key;
|
|
11533
|
+
evictTouchedAt = touchedAt;
|
|
11534
|
+
}
|
|
11535
|
+
}
|
|
11536
|
+
return evictKey;
|
|
11537
|
+
}
|
|
11538
|
+
drop(sessionKey, reason = "session-ended") {
|
|
11539
|
+
const target = this.targets.get(sessionKey);
|
|
11540
|
+
if (!target)
|
|
11541
|
+
return false;
|
|
11542
|
+
this.clearRetry(target);
|
|
11543
|
+
this.clearPlanTimer(target);
|
|
11544
|
+
this.totalBytes -= target.bodyBytes;
|
|
11545
|
+
this.targets.delete(sessionKey);
|
|
11546
|
+
if (reason !== null && target.hasWarmed && this.adapter.onWarmStopped) {
|
|
11547
|
+
this.report(() => this.adapter.onWarmStopped?.(sessionKey, { at: this.now(), reason }));
|
|
11548
|
+
}
|
|
11549
|
+
return true;
|
|
11550
|
+
}
|
|
11551
|
+
}
|
|
10758
11552
|
// src/claustrum-enrollment.ts
|
|
10759
11553
|
import { createHash as createHash6, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "node:crypto";
|
|
10760
11554
|
import { constants as fsConstants2 } from "node:fs";
|
|
@@ -12487,8 +13281,8 @@ function nativeLocalAccountRefusal(result) {
|
|
|
12487
13281
|
}
|
|
12488
13282
|
|
|
12489
13283
|
// src/cachekeep-failure.ts
|
|
12490
|
-
var
|
|
12491
|
-
var
|
|
13284
|
+
var ERROR_NAMES2 = ["AbortError", "TimeoutError", "TypeError"];
|
|
13285
|
+
var NETWORK_CODES2 = [
|
|
12492
13286
|
"ECONNRESET",
|
|
12493
13287
|
"ECONNREFUSED",
|
|
12494
13288
|
"ETIMEDOUT",
|
|
@@ -12540,7 +13334,7 @@ var REFUSAL_CODES = [
|
|
|
12540
13334
|
"account-unavailable",
|
|
12541
13335
|
"credential-changed"
|
|
12542
13336
|
];
|
|
12543
|
-
function
|
|
13337
|
+
function allowed2(values, value) {
|
|
12544
13338
|
return typeof value === "string" && values.includes(value);
|
|
12545
13339
|
}
|
|
12546
13340
|
function httpFailure(value) {
|
|
@@ -12557,17 +13351,17 @@ function classifyCacheKeepFailure(error, stage, status) {
|
|
|
12557
13351
|
const value = error.class;
|
|
12558
13352
|
return {
|
|
12559
13353
|
stage: safeStage,
|
|
12560
|
-
class: httpFailure(value) ||
|
|
13354
|
+
class: httpFailure(value) || allowed2(ERROR_NAMES2, value) || allowed2(NETWORK_CODES2, value) || allowed2(CUSTODY_CODES, value) || allowed2(REFUSAL_CODES, value) ? value : "unknown"
|
|
12561
13355
|
};
|
|
12562
13356
|
}
|
|
12563
13357
|
if (error instanceof NativeAccountRefusal) {
|
|
12564
13358
|
const reason = error.reason;
|
|
12565
|
-
if (
|
|
13359
|
+
if (allowed2(REFUSAL_CODES, reason))
|
|
12566
13360
|
return { stage: "authorization", class: reason };
|
|
12567
13361
|
}
|
|
12568
13362
|
if (error instanceof NativeCustodyError) {
|
|
12569
13363
|
const code2 = error.code;
|
|
12570
|
-
if (
|
|
13364
|
+
if (allowed2(CUSTODY_CODES, code2))
|
|
12571
13365
|
return { stage: "authorization", class: code2 };
|
|
12572
13366
|
}
|
|
12573
13367
|
if (typeof error !== "object" || error === null)
|
|
@@ -12577,12 +13371,12 @@ function classifyCacheKeepFailure(error, stage, status) {
|
|
|
12577
13371
|
if (name === "AbortError" || name === "TimeoutError")
|
|
12578
13372
|
return { stage, class: name };
|
|
12579
13373
|
const code = fields2.code;
|
|
12580
|
-
if (
|
|
13374
|
+
if (allowed2(NETWORK_CODES2, code))
|
|
12581
13375
|
return { stage, class: code };
|
|
12582
13376
|
const causeCode = fields2.cause?.code;
|
|
12583
|
-
if (
|
|
13377
|
+
if (allowed2(NETWORK_CODES2, causeCode))
|
|
12584
13378
|
return { stage, class: causeCode };
|
|
12585
|
-
if (
|
|
13379
|
+
if (allowed2(ERROR_NAMES2, name))
|
|
12586
13380
|
return { stage, class: name };
|
|
12587
13381
|
} catch {}
|
|
12588
13382
|
return unknown;
|
|
@@ -14559,7 +15353,7 @@ function keepField(target, key, value, walk) {
|
|
|
14559
15353
|
function isStatus(value) {
|
|
14560
15354
|
return Number.isInteger(value) && Number(value) >= 0 && Number(value) <= 999;
|
|
14561
15355
|
}
|
|
14562
|
-
function addHeader(
|
|
15356
|
+
function addHeader(record3, name, value, walk) {
|
|
14563
15357
|
const length = name.length + value.length;
|
|
14564
15358
|
if (length > walk.bytes)
|
|
14565
15359
|
return;
|
|
@@ -14570,11 +15364,11 @@ function addHeader(record2, name, value, walk) {
|
|
|
14570
15364
|
const scrubbed = scrubText(value, walk.secrets);
|
|
14571
15365
|
const bytes = () => Buffer2.byteLength(name, "utf8") + Buffer2.byteLength(scrubbed, "utf8");
|
|
14572
15366
|
if (spendScanned(walk, length, bytes))
|
|
14573
|
-
defineField(
|
|
15367
|
+
defineField(record3, name, scrubbed);
|
|
14574
15368
|
}
|
|
14575
15369
|
var STOP_HEADER_WALK = Object.freeze({});
|
|
14576
15370
|
function platformHeaderRecord(headers, walk) {
|
|
14577
|
-
const
|
|
15371
|
+
const record3 = {};
|
|
14578
15372
|
let examined = 0;
|
|
14579
15373
|
try {
|
|
14580
15374
|
Reflect.apply(HEADERS_FOR_EACH, headers, [
|
|
@@ -14583,17 +15377,17 @@ function platformHeaderRecord(headers, walk) {
|
|
|
14583
15377
|
throw STOP_HEADER_WALK;
|
|
14584
15378
|
examined += 1;
|
|
14585
15379
|
if (typeof name === "string" && typeof value === "string")
|
|
14586
|
-
addHeader(
|
|
15380
|
+
addHeader(record3, name, value, walk);
|
|
14587
15381
|
}
|
|
14588
15382
|
]);
|
|
14589
15383
|
} catch (error) {
|
|
14590
15384
|
if (error === STOP_HEADER_WALK)
|
|
14591
|
-
return
|
|
15385
|
+
return record3;
|
|
14592
15386
|
if (error instanceof TypeError)
|
|
14593
15387
|
return;
|
|
14594
15388
|
throw error;
|
|
14595
15389
|
}
|
|
14596
|
-
return
|
|
15390
|
+
return record3;
|
|
14597
15391
|
}
|
|
14598
15392
|
function projectHeaders(value, walk) {
|
|
14599
15393
|
if (value === null || typeof value !== "object" || !hasProxyFreeChain(value))
|
|
@@ -14604,13 +15398,13 @@ function projectHeaders(value, walk) {
|
|
|
14604
15398
|
const keys = Reflect.ownKeys(value);
|
|
14605
15399
|
if (keys.length > MAX_OBJECT_KEYS)
|
|
14606
15400
|
return;
|
|
14607
|
-
const
|
|
15401
|
+
const record3 = {};
|
|
14608
15402
|
for (const key of keys) {
|
|
14609
15403
|
const entry = typeof key === "string" ? ownData(value, key) : undefined;
|
|
14610
15404
|
if (typeof key === "string" && typeof entry === "string")
|
|
14611
|
-
addHeader(
|
|
15405
|
+
addHeader(record3, key, entry, walk);
|
|
14612
15406
|
}
|
|
14613
|
-
return
|
|
15407
|
+
return record3;
|
|
14614
15408
|
}
|
|
14615
15409
|
function projectField(kind, value, walk, depth) {
|
|
14616
15410
|
switch (kind) {
|
|
@@ -14758,13 +15552,13 @@ function project(value, walk, depth) {
|
|
|
14758
15552
|
const statusText = readSlot(RESPONSE_STATUS_TEXT, value);
|
|
14759
15553
|
if (typeof statusText !== "string")
|
|
14760
15554
|
throw new TypeError("Response slots could not be read");
|
|
14761
|
-
const
|
|
14762
|
-
walk.memo.set(value,
|
|
14763
|
-
keepField(
|
|
14764
|
-
keepField(
|
|
15555
|
+
const record4 = {};
|
|
15556
|
+
walk.memo.set(value, record4);
|
|
15557
|
+
keepField(record4, "status", status, walk);
|
|
15558
|
+
keepField(record4, "statusText", boundedText(statusText, walk) ?? "", walk);
|
|
14765
15559
|
const headers = readSlot(RESPONSE_HEADERS, value);
|
|
14766
|
-
keepField(
|
|
14767
|
-
return
|
|
15560
|
+
keepField(record4, "headers", platformHeaderRecord(headers, walk) ?? {}, walk);
|
|
15561
|
+
return record4;
|
|
14768
15562
|
}
|
|
14769
15563
|
const exceptionMessage = branded(() => readSlot(DOM_EXCEPTION_MESSAGE, value));
|
|
14770
15564
|
if (typeof exceptionMessage === "string") {
|
|
@@ -14781,10 +15575,10 @@ function project(value, walk, depth) {
|
|
|
14781
15575
|
return projectError(value, walk, depth);
|
|
14782
15576
|
if (Array.isArray(value))
|
|
14783
15577
|
return projectArray(value, walk, depth);
|
|
14784
|
-
const
|
|
14785
|
-
walk.memo.set(value,
|
|
14786
|
-
projectFields(value,
|
|
14787
|
-
return
|
|
15578
|
+
const record3 = {};
|
|
15579
|
+
walk.memo.set(value, record3);
|
|
15580
|
+
projectFields(value, record3, walk, depth, NO_SKIP);
|
|
15581
|
+
return record3;
|
|
14788
15582
|
}
|
|
14789
15583
|
function genericError(original, message) {
|
|
14790
15584
|
const error = new Error(message);
|
|
@@ -15335,10 +16129,191 @@ function stripServerFallbackUsageMarkers(body) {
|
|
|
15335
16129
|
return removed;
|
|
15336
16130
|
}
|
|
15337
16131
|
|
|
16132
|
+
// src/session-cache-policy.ts
|
|
16133
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
|
|
16134
|
+
|
|
16135
|
+
// src/session-cache-activity.ts
|
|
16136
|
+
var PROMPT_CACHE_DEFAULT_TTL_MS = 5 * 60000;
|
|
16137
|
+
var PROMPT_CACHE_1H_TTL_MS = 60 * 60000;
|
|
16138
|
+
|
|
16139
|
+
class SessionCacheActivity {
|
|
16140
|
+
maxSessions;
|
|
16141
|
+
entries = new Map;
|
|
16142
|
+
constructor(maxSessions = 4096) {
|
|
16143
|
+
this.maxSessions = maxSessions;
|
|
16144
|
+
}
|
|
16145
|
+
record(sessionId, accountId, ttlMs, lastAcceptedAt = Date.now()) {
|
|
16146
|
+
if (ttlMs === 0) {
|
|
16147
|
+
this.forget(sessionId);
|
|
16148
|
+
return;
|
|
16149
|
+
}
|
|
16150
|
+
this.entries.delete(sessionId);
|
|
16151
|
+
this.entries.set(sessionId, {
|
|
16152
|
+
accountId,
|
|
16153
|
+
lastAcceptedAt,
|
|
16154
|
+
ttlMs: ttlMs && Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : PROMPT_CACHE_DEFAULT_TTL_MS
|
|
16155
|
+
});
|
|
16156
|
+
if (this.entries.size > this.maxSessions) {
|
|
16157
|
+
const oldest = this.entries.keys().next().value;
|
|
16158
|
+
if (oldest !== undefined)
|
|
16159
|
+
this.entries.delete(oldest);
|
|
16160
|
+
}
|
|
16161
|
+
}
|
|
16162
|
+
holdUntil(sessionId, accountId, now = Date.now(), maxWait = "15") {
|
|
16163
|
+
if (!sessionId)
|
|
16164
|
+
return;
|
|
16165
|
+
const activity = this.entries.get(sessionId);
|
|
16166
|
+
if (!activity || activity.accountId !== accountId)
|
|
16167
|
+
return;
|
|
16168
|
+
return Math.min(activity.lastAcceptedAt + activity.ttlMs, maxWait === "max" ? Infinity : now + Number(maxWait) * 60000);
|
|
16169
|
+
}
|
|
16170
|
+
recordPrewarm(sessionId, accountId, acceptedAt = Date.now(), ttlMs = PROMPT_CACHE_1H_TTL_MS) {
|
|
16171
|
+
const activity = this.entries.get(sessionId);
|
|
16172
|
+
if (activity && activity.accountId !== accountId)
|
|
16173
|
+
return;
|
|
16174
|
+
this.record(sessionId, accountId, ttlMs, acceptedAt);
|
|
16175
|
+
}
|
|
16176
|
+
forget(sessionId) {
|
|
16177
|
+
this.entries.delete(sessionId);
|
|
16178
|
+
}
|
|
16179
|
+
ttlMs(sessionId) {
|
|
16180
|
+
return sessionId && this.entries.get(sessionId)?.ttlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
|
|
16181
|
+
}
|
|
16182
|
+
}
|
|
16183
|
+
var sessionCacheActivity = new SessionCacheActivity;
|
|
16184
|
+
|
|
16185
|
+
// src/session-cache-policy.ts
|
|
16186
|
+
function readSessionCachePolicy(sessionId, isOAuth) {
|
|
16187
|
+
return isOAuth && sessionId ? sessionCachePolicy(sessionId) : null;
|
|
16188
|
+
}
|
|
16189
|
+
var reportHandoffs = new AsyncLocalStorage2;
|
|
16190
|
+
function scheduleReport(send) {
|
|
16191
|
+
reportHandoffs.exit(() => setTimeout(() => {
|
|
16192
|
+
try {
|
|
16193
|
+
send();
|
|
16194
|
+
} catch {}
|
|
16195
|
+
}, 0).unref?.());
|
|
16196
|
+
}
|
|
16197
|
+
function detachReport(send, responseTouch = false, background = false) {
|
|
16198
|
+
if (background) {
|
|
16199
|
+
scheduleReport(send);
|
|
16200
|
+
return true;
|
|
16201
|
+
}
|
|
16202
|
+
const handoff = reportHandoffs.getStore();
|
|
16203
|
+
if (handoff?.failed && responseTouch)
|
|
16204
|
+
return false;
|
|
16205
|
+
if (handoff && !handoff.released)
|
|
16206
|
+
handoff.pending.push({ send, responseTouch });
|
|
16207
|
+
else
|
|
16208
|
+
scheduleReport(send);
|
|
16209
|
+
return true;
|
|
16210
|
+
}
|
|
16211
|
+
function withSessionCacheReportHandoff(work) {
|
|
16212
|
+
return (...args) => {
|
|
16213
|
+
const handoff = {
|
|
16214
|
+
released: false,
|
|
16215
|
+
failed: false,
|
|
16216
|
+
pending: []
|
|
16217
|
+
};
|
|
16218
|
+
return reportHandoffs.run(handoff, async () => {
|
|
16219
|
+
try {
|
|
16220
|
+
return await work(...args);
|
|
16221
|
+
} catch (error) {
|
|
16222
|
+
handoff.failed = true;
|
|
16223
|
+
throw error;
|
|
16224
|
+
} finally {
|
|
16225
|
+
handoff.released = true;
|
|
16226
|
+
const pending = handoff.pending.splice(0);
|
|
16227
|
+
for (const { send, responseTouch } of pending)
|
|
16228
|
+
if (!handoff.failed || !responseTouch)
|
|
16229
|
+
scheduleReport(send);
|
|
16230
|
+
}
|
|
16231
|
+
});
|
|
16232
|
+
};
|
|
16233
|
+
}
|
|
16234
|
+
function reportSessionCacheTouch(sessionId, input) {
|
|
16235
|
+
detachReport(() => reportCacheTouch(sessionId, input), input.source === "response", input.source === "warm");
|
|
16236
|
+
}
|
|
16237
|
+
function reportSessionCacheWarmStopped(sessionId, input) {
|
|
16238
|
+
return detachReport(() => reportCacheWarmStopped(sessionId, input));
|
|
16239
|
+
}
|
|
16240
|
+
function record3(value) {
|
|
16241
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
16242
|
+
}
|
|
16243
|
+
function cacheHolders(body, visit) {
|
|
16244
|
+
visit(body);
|
|
16245
|
+
for (const field of ["tools", "system"]) {
|
|
16246
|
+
const value = body[field];
|
|
16247
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
16248
|
+
if (record3(item))
|
|
16249
|
+
visit(item);
|
|
16250
|
+
}
|
|
16251
|
+
}
|
|
16252
|
+
if (!Array.isArray(body.messages))
|
|
16253
|
+
return;
|
|
16254
|
+
for (const message of body.messages) {
|
|
16255
|
+
if (!record3(message))
|
|
16256
|
+
continue;
|
|
16257
|
+
visit(message);
|
|
16258
|
+
if (Array.isArray(message.content)) {
|
|
16259
|
+
for (const block of message.content)
|
|
16260
|
+
if (record3(block))
|
|
16261
|
+
visit(block);
|
|
16262
|
+
}
|
|
16263
|
+
}
|
|
16264
|
+
}
|
|
16265
|
+
function applySessionCacheTtl(body, ttl) {
|
|
16266
|
+
if (ttl === undefined)
|
|
16267
|
+
return;
|
|
16268
|
+
cacheHolders(body, (holder) => {
|
|
16269
|
+
if (ttl === "none") {
|
|
16270
|
+
delete holder.cache_control;
|
|
16271
|
+
delete holder.cacheControl;
|
|
16272
|
+
return;
|
|
16273
|
+
}
|
|
16274
|
+
const control = holder.cache_control ?? holder.cacheControl;
|
|
16275
|
+
if (!record3(control) || control.type !== "ephemeral")
|
|
16276
|
+
return;
|
|
16277
|
+
holder.cache_control = control;
|
|
16278
|
+
delete holder.cacheControl;
|
|
16279
|
+
if (ttl === "long")
|
|
16280
|
+
control.ttl = "1h";
|
|
16281
|
+
else
|
|
16282
|
+
delete control.ttl;
|
|
16283
|
+
});
|
|
16284
|
+
}
|
|
16285
|
+
function requestCacheLifetimeMs(input) {
|
|
16286
|
+
let body = input;
|
|
16287
|
+
if (typeof input === "string") {
|
|
16288
|
+
try {
|
|
16289
|
+
body = JSON.parse(input);
|
|
16290
|
+
} catch {
|
|
16291
|
+
return 0;
|
|
16292
|
+
}
|
|
16293
|
+
}
|
|
16294
|
+
if (!record3(body))
|
|
16295
|
+
return 0;
|
|
16296
|
+
let ttlMs = 0;
|
|
16297
|
+
cacheHolders(body, (holder) => {
|
|
16298
|
+
for (const key of ["cache_control", "cacheControl"]) {
|
|
16299
|
+
const control = holder[key];
|
|
16300
|
+
if (!record3(control) || control.type !== "ephemeral")
|
|
16301
|
+
continue;
|
|
16302
|
+
ttlMs = Math.max(ttlMs, control.ttl === "1h" ? PROMPT_CACHE_1H_TTL_MS : PROMPT_CACHE_DEFAULT_TTL_MS);
|
|
16303
|
+
}
|
|
16304
|
+
});
|
|
16305
|
+
return ttlMs;
|
|
16306
|
+
}
|
|
16307
|
+
|
|
15338
16308
|
// src/cachekeep.ts
|
|
15339
16309
|
var CLAUDE_CACHE_KEEP_COMMAND_NAME = "claude-cachekeep";
|
|
15340
16310
|
var CACHE_KEEP_TTL_MS = 60 * 60000;
|
|
15341
16311
|
var CACHE_KEEP_PREWARM_LEAD_MS = 5 * 60000;
|
|
16312
|
+
function replayPrewarmLeadMs(ttlMs, planned) {
|
|
16313
|
+
if (!planned && ttlMs === CACHE_KEEP_TTL_MS)
|
|
16314
|
+
return CACHE_KEEP_PREWARM_LEAD_MS;
|
|
16315
|
+
return Math.min(30000, ttlMs / 2);
|
|
16316
|
+
}
|
|
15342
16317
|
var CACHE_KEEP_TICK_MS = 60000;
|
|
15343
16318
|
var CACHE_KEEP_EXTENDED_TTL_BETA = "extended-cache-ttl-2025-04-11";
|
|
15344
16319
|
var CACHE_KEEP_MAX_TARGETS = 32;
|
|
@@ -15397,7 +16372,7 @@ function isCacheKeepPersistentlyEnabled(storage) {
|
|
|
15397
16372
|
function isCacheKeepHybridActive(storage) {
|
|
15398
16373
|
return isCacheKeepPersistentlyEnabled(storage) && storage?.claudeCache?.enabled === true && storage.claudeCache.mode === "hybrid";
|
|
15399
16374
|
}
|
|
15400
|
-
function
|
|
16375
|
+
function isWithinCacheKeepWindow2(window, now = new Date) {
|
|
15401
16376
|
if (!window)
|
|
15402
16377
|
return false;
|
|
15403
16378
|
const hour = now.getHours();
|
|
@@ -15409,7 +16384,7 @@ function isWithinCacheKeepWindow(window, now = new Date) {
|
|
|
15409
16384
|
function isCacheKeepActiveNow(storage, now = new Date) {
|
|
15410
16385
|
if (storage?.cacheKeep?.enabled !== true)
|
|
15411
16386
|
return false;
|
|
15412
|
-
return isCacheKeepAlways(storage) ||
|
|
16387
|
+
return isCacheKeepAlways(storage) || isWithinCacheKeepWindow2(getCacheKeepWindow(storage), now);
|
|
15413
16388
|
}
|
|
15414
16389
|
function localDayKey(now = new Date) {
|
|
15415
16390
|
return `${now.getFullYear()}-${padHour(now.getMonth() + 1)}-${padHour(now.getDate())}`;
|
|
@@ -15517,12 +16492,12 @@ function hasExplicitCacheControl(value) {
|
|
|
15517
16492
|
return false;
|
|
15518
16493
|
if (Array.isArray(value))
|
|
15519
16494
|
return value.some(hasExplicitCacheControl);
|
|
15520
|
-
const
|
|
15521
|
-
const cacheControl =
|
|
16495
|
+
const record4 = value;
|
|
16496
|
+
const cacheControl = record4.cache_control;
|
|
15522
16497
|
if (cacheControl && typeof cacheControl === "object" && cacheControl.type === "ephemeral") {
|
|
15523
16498
|
return true;
|
|
15524
16499
|
}
|
|
15525
|
-
return Object.values(
|
|
16500
|
+
return Object.values(record4).some(hasExplicitCacheControl);
|
|
15526
16501
|
}
|
|
15527
16502
|
async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
|
|
15528
16503
|
let body;
|
|
@@ -15561,6 +16536,23 @@ async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
|
|
|
15561
16536
|
const signedBodyText = await signRequestBody(JSON.stringify(orderClaudeCodeBody(warm)));
|
|
15562
16537
|
return { ok: true, bodyText: signedBodyText };
|
|
15563
16538
|
}
|
|
16539
|
+
function updateAcceptedUsage(target, bodyText, usage) {
|
|
16540
|
+
const state = target.policyState;
|
|
16541
|
+
if (!state || target.bodyText !== bodyText || usage.cache_read_input_tokens === undefined && usage.cache_creation_input_tokens === undefined)
|
|
16542
|
+
return false;
|
|
16543
|
+
const read = usage.cache_read_input_tokens ?? 0;
|
|
16544
|
+
const write = usage.cache_creation_input_tokens ?? 0;
|
|
16545
|
+
const uncached = usage.input_tokens ?? 0;
|
|
16546
|
+
if (![read, write, uncached].every((n) => Number.isFinite(n) && n >= 0))
|
|
16547
|
+
return false;
|
|
16548
|
+
const prefix = read + write;
|
|
16549
|
+
const input = prefix + uncached;
|
|
16550
|
+
if (state.prefixTokens === prefix && state.inputTokens === input)
|
|
16551
|
+
return false;
|
|
16552
|
+
state.prefixTokens = prefix;
|
|
16553
|
+
state.inputTokens = input;
|
|
16554
|
+
return true;
|
|
16555
|
+
}
|
|
15564
16556
|
function sessionMetadata(target) {
|
|
15565
16557
|
return {
|
|
15566
16558
|
id: target.id,
|
|
@@ -15592,6 +16584,38 @@ function stopReason(reason) {
|
|
|
15592
16584
|
return "policy-refused";
|
|
15593
16585
|
}
|
|
15594
16586
|
}
|
|
16587
|
+
function reportStopReason(reason) {
|
|
16588
|
+
switch (reason) {
|
|
16589
|
+
case "cost-cap":
|
|
16590
|
+
case "count-cap":
|
|
16591
|
+
case "outside-hours":
|
|
16592
|
+
case "session-ended":
|
|
16593
|
+
case "unsupported":
|
|
16594
|
+
case "evicted":
|
|
16595
|
+
case "stopped":
|
|
16596
|
+
case "account-changed":
|
|
16597
|
+
case "expired":
|
|
16598
|
+
case "idle":
|
|
16599
|
+
return reason;
|
|
16600
|
+
case "budget":
|
|
16601
|
+
case "count":
|
|
16602
|
+
return "evicted";
|
|
16603
|
+
case "schedule":
|
|
16604
|
+
case "schedule-period-ended":
|
|
16605
|
+
return "outside-hours";
|
|
16606
|
+
case "session-forgotten":
|
|
16607
|
+
return "session-ended";
|
|
16608
|
+
case "retry-window-ended":
|
|
16609
|
+
return "expired";
|
|
16610
|
+
case "source-warm-idle-cap":
|
|
16611
|
+
return "cost-cap";
|
|
16612
|
+
case "credential-changed":
|
|
16613
|
+
case "account-unavailable":
|
|
16614
|
+
return "account-changed";
|
|
16615
|
+
default:
|
|
16616
|
+
return "unsupported";
|
|
16617
|
+
}
|
|
16618
|
+
}
|
|
15595
16619
|
function isRecord9(value) {
|
|
15596
16620
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
15597
16621
|
}
|
|
@@ -15668,14 +16692,28 @@ function cacheKeepSentCredentials(headers) {
|
|
|
15668
16692
|
credentials.push(apiKey);
|
|
15669
16693
|
return credentials;
|
|
15670
16694
|
}
|
|
16695
|
+
var PLANNED_UNPRICED_MAIN_IDLE_MS = 60 * 60000;
|
|
16696
|
+
var PLANNED_UNPRICED_SUBAGENT_IDLE_MS = 30 * 60000;
|
|
15671
16697
|
|
|
15672
|
-
class
|
|
16698
|
+
class CacheKeepWarmRefusal extends Error {
|
|
16699
|
+
reason;
|
|
16700
|
+
constructor(reason) {
|
|
16701
|
+
super("CacheKeep policy refused");
|
|
16702
|
+
this.reason = reason;
|
|
16703
|
+
}
|
|
16704
|
+
}
|
|
16705
|
+
|
|
16706
|
+
class CacheKeepManager2 {
|
|
15673
16707
|
options;
|
|
15674
16708
|
targets = new Map;
|
|
16709
|
+
immediateTargets = new Map;
|
|
15675
16710
|
stoppedSessions = new Map;
|
|
15676
16711
|
timer = null;
|
|
16712
|
+
dueTimer = null;
|
|
15677
16713
|
tickPromise = null;
|
|
15678
16714
|
nextPrewarmAttemptId = 0;
|
|
16715
|
+
reportedStops = new WeakSet;
|
|
16716
|
+
admittedWarmCosts = new WeakMap;
|
|
15679
16717
|
constructor(options) {
|
|
15680
16718
|
this.options = options;
|
|
15681
16719
|
}
|
|
@@ -15690,8 +16728,17 @@ class CacheKeepManager {
|
|
|
15690
16728
|
}, CACHE_KEEP_TICK_MS);
|
|
15691
16729
|
if ("unref" in this.timer)
|
|
15692
16730
|
this.timer.unref();
|
|
16731
|
+
this.scheduleDueTimer();
|
|
15693
16732
|
}
|
|
15694
16733
|
stop() {
|
|
16734
|
+
this.immediateTargets.clear();
|
|
16735
|
+
const now = this.options.now?.() ?? Date.now();
|
|
16736
|
+
for (const target of this.targets.values())
|
|
16737
|
+
this.reportStop(target, "stopped", now);
|
|
16738
|
+
if (this.dueTimer) {
|
|
16739
|
+
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
16740
|
+
this.dueTimer = null;
|
|
16741
|
+
}
|
|
15695
16742
|
if (!this.timer)
|
|
15696
16743
|
return;
|
|
15697
16744
|
logger2.debug("cachekeep", "stopped");
|
|
@@ -15745,9 +16792,11 @@ class CacheKeepManager {
|
|
|
15745
16792
|
};
|
|
15746
16793
|
}
|
|
15747
16794
|
untrack(id, reason = "session-forgotten") {
|
|
16795
|
+
this.immediateTargets.delete(id);
|
|
15748
16796
|
const target = this.targets.get(id);
|
|
15749
16797
|
if (!target)
|
|
15750
16798
|
return false;
|
|
16799
|
+
this.reportStop(target, reason, this.options.now?.() ?? Date.now());
|
|
15751
16800
|
this.retainStopped(target, reason, this.options.now?.() ?? Date.now());
|
|
15752
16801
|
this.targets.delete(id);
|
|
15753
16802
|
this.options.onTargetRemoved?.(id);
|
|
@@ -15757,6 +16806,168 @@ class CacheKeepManager {
|
|
|
15757
16806
|
trackedCount() {
|
|
15758
16807
|
return this.targets.size;
|
|
15759
16808
|
}
|
|
16809
|
+
isCurrentTarget(target) {
|
|
16810
|
+
const current = this.targets.get(target.id);
|
|
16811
|
+
return current ? current.policyState === target.policyState : this.immediateTargets.get(target.id) === target;
|
|
16812
|
+
}
|
|
16813
|
+
trackedPolicyState(id) {
|
|
16814
|
+
return this.targets.get(id)?.policyState;
|
|
16815
|
+
}
|
|
16816
|
+
hasPlannedTarget(id) {
|
|
16817
|
+
return this.targets.get(id)?.policyState?.planned === true;
|
|
16818
|
+
}
|
|
16819
|
+
updateSubagent(id, isSubagent) {
|
|
16820
|
+
const target = this.targets.get(id);
|
|
16821
|
+
if (!target || target.isSubagent === isSubagent)
|
|
16822
|
+
return;
|
|
16823
|
+
target.isSubagent = isSubagent;
|
|
16824
|
+
this.options.onTargetChanged?.(target);
|
|
16825
|
+
this.scheduleDueTimer();
|
|
16826
|
+
}
|
|
16827
|
+
recordAcceptedUsage(id, bodyText, usage) {
|
|
16828
|
+
const target = this.targets.get(id);
|
|
16829
|
+
if (!target || !updateAcceptedUsage(target, bodyText, usage))
|
|
16830
|
+
return;
|
|
16831
|
+
this.options.onTargetChanged?.(target);
|
|
16832
|
+
this.scheduleDueTimer();
|
|
16833
|
+
}
|
|
16834
|
+
costs(target) {
|
|
16835
|
+
const state = target.policyState;
|
|
16836
|
+
if (state?.prefixTokens === undefined)
|
|
16837
|
+
return;
|
|
16838
|
+
let model;
|
|
16839
|
+
try {
|
|
16840
|
+
model = JSON.parse(target.bodyText).model;
|
|
16841
|
+
} catch {
|
|
16842
|
+
return;
|
|
16843
|
+
}
|
|
16844
|
+
if (typeof model !== "string")
|
|
16845
|
+
return;
|
|
16846
|
+
let catalogue;
|
|
16847
|
+
try {
|
|
16848
|
+
catalogue = getClaudeModelCatalogue(model);
|
|
16849
|
+
} catch {
|
|
16850
|
+
return;
|
|
16851
|
+
}
|
|
16852
|
+
if (!catalogue)
|
|
16853
|
+
return;
|
|
16854
|
+
const prices = catalogue.longContext && (state.inputTokens ?? 0) > catalogue.longContext.inputTokensAbove ? catalogue.longContext.pricing : catalogue.pricing;
|
|
16855
|
+
const read = prices.cacheRead;
|
|
16856
|
+
const write = target.ttlMs === 3600000 ? prices.cacheWrite1h : prices.cacheWrite5m;
|
|
16857
|
+
if (![read, write].every((price) => Number.isFinite(price) && price >= 0))
|
|
16858
|
+
return;
|
|
16859
|
+
return {
|
|
16860
|
+
nextWarmCost: read * state.prefixTokens,
|
|
16861
|
+
rewriteCost: write * state.prefixTokens,
|
|
16862
|
+
warmCostSoFar: state.warmCostSoFar
|
|
16863
|
+
};
|
|
16864
|
+
}
|
|
16865
|
+
policyDecision(target, now, ownReservation = false) {
|
|
16866
|
+
const state = target.policyState;
|
|
16867
|
+
if (!state)
|
|
16868
|
+
return;
|
|
16869
|
+
const policy = readSessionCachePolicy(state.ownerSessionId, true);
|
|
16870
|
+
if (!policy && state.planned)
|
|
16871
|
+
return { action: "stop", reason: "session-ended" };
|
|
16872
|
+
if (!policy)
|
|
16873
|
+
return;
|
|
16874
|
+
if (policy.ttl === "none" || policy.keep_warm === "off")
|
|
16875
|
+
return { action: "stop", reason: "unsupported" };
|
|
16876
|
+
if (policy.ttl && (policy.ttl === "long" ? 3600000 : 300000) !== target.ttlMs)
|
|
16877
|
+
return { action: "stop", reason: "unsupported" };
|
|
16878
|
+
if (policy.keep_warm === undefined)
|
|
16879
|
+
return state.planned ? { action: "stop", reason: "session-ended" } : undefined;
|
|
16880
|
+
if (state.needsRealRequest)
|
|
16881
|
+
return { action: "stop", reason: "unsupported" };
|
|
16882
|
+
state.planned = true;
|
|
16883
|
+
const mode = policy.keep_warm;
|
|
16884
|
+
const plan = mode === "hours" ? policy.hours && { mode, hours: policy.hours } : { mode };
|
|
16885
|
+
if (!plan)
|
|
16886
|
+
return { action: "stop", reason: "unsupported" };
|
|
16887
|
+
const costs = this.costs(target);
|
|
16888
|
+
if (mode === "auto" && !costs && state.lastRealRequestAt < now - (target.isSubagent ? PLANNED_UNPRICED_SUBAGENT_IDLE_MS : PLANNED_UNPRICED_MAIN_IDLE_MS))
|
|
16889
|
+
return { action: "stop", reason: "idle" };
|
|
16890
|
+
return decideCacheKeep({
|
|
16891
|
+
...plan,
|
|
16892
|
+
now,
|
|
16893
|
+
ttlMs: target.ttlMs ?? 0,
|
|
16894
|
+
lastRealRequestAt: state.lastRealRequestAt,
|
|
16895
|
+
lastWarmAt: state.lastWarmAt,
|
|
16896
|
+
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest - Number(ownReservation),
|
|
16897
|
+
...costs
|
|
16898
|
+
});
|
|
16899
|
+
}
|
|
16900
|
+
countDecision(target) {
|
|
16901
|
+
const state = target.policyState;
|
|
16902
|
+
if (!state || state.needsRealRequest)
|
|
16903
|
+
return { action: "stop", reason: "unsupported" };
|
|
16904
|
+
const result = decideCacheKeep({
|
|
16905
|
+
mode: "always",
|
|
16906
|
+
now: state.lastRealRequestAt,
|
|
16907
|
+
ttlMs: CACHE_KEEP_TTL_MS,
|
|
16908
|
+
lastRealRequestAt: state.lastRealRequestAt,
|
|
16909
|
+
warmsSinceLastRealRequest: state.warmsSinceLastRealRequest
|
|
16910
|
+
});
|
|
16911
|
+
return result.action === "stop" && result.reason === "count-cap" ? result : undefined;
|
|
16912
|
+
}
|
|
16913
|
+
async reserveWarmDispatch(target) {
|
|
16914
|
+
const current = this.targets.get(target.id);
|
|
16915
|
+
if (!current || !this.isCurrentTarget(target))
|
|
16916
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
16917
|
+
const state = current.policyState;
|
|
16918
|
+
const storage = await this.options.loadStorage();
|
|
16919
|
+
if (!this.isCurrentTarget(target))
|
|
16920
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
16921
|
+
const now = this.options.now?.() ?? Date.now();
|
|
16922
|
+
const decision = this.policyDecision(current, now) ?? (isCacheKeepAlways(storage) ? this.countDecision(current) : undefined);
|
|
16923
|
+
if (decision?.action === "stop")
|
|
16924
|
+
throw new CacheKeepWarmRefusal(decision.reason);
|
|
16925
|
+
if (decision?.action === "wait")
|
|
16926
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
16927
|
+
const admittedCost = this.costs(current)?.nextWarmCost ?? 0;
|
|
16928
|
+
const pendingCost = state?.pendingWarmCost;
|
|
16929
|
+
if (state) {
|
|
16930
|
+
state.warmsSinceLastRealRequest++;
|
|
16931
|
+
state.pendingWarmCost = (pendingCost ?? 0) + admittedCost;
|
|
16932
|
+
}
|
|
16933
|
+
if (this.options.reserveWarm) {
|
|
16934
|
+
let committed = false;
|
|
16935
|
+
try {
|
|
16936
|
+
committed = await this.options.reserveWarm(current);
|
|
16937
|
+
} catch {}
|
|
16938
|
+
if (!committed && (state?.planned || isCacheKeepAlways(storage))) {
|
|
16939
|
+
if (state) {
|
|
16940
|
+
state.warmsSinceLastRealRequest--;
|
|
16941
|
+
state.pendingWarmCost = pendingCost;
|
|
16942
|
+
}
|
|
16943
|
+
throw new CacheKeepPrewarmError("authorization", undefined);
|
|
16944
|
+
}
|
|
16945
|
+
}
|
|
16946
|
+
if (state)
|
|
16947
|
+
this.admittedWarmCosts.set(state, admittedCost);
|
|
16948
|
+
if (!this.isCurrentTarget(target))
|
|
16949
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
16950
|
+
const fresh = this.policyDecision(current, this.options.now?.() ?? Date.now(), true);
|
|
16951
|
+
if (fresh?.action === "stop")
|
|
16952
|
+
throw new CacheKeepWarmRefusal(fresh.reason);
|
|
16953
|
+
if (fresh?.action === "wait")
|
|
16954
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
16955
|
+
}
|
|
16956
|
+
scheduleDueTimer() {
|
|
16957
|
+
if (this.dueTimer)
|
|
16958
|
+
(this.options.clearTimeoutImpl ?? clearTimeout)(this.dueTimer);
|
|
16959
|
+
this.dueTimer = null;
|
|
16960
|
+
let due = Infinity;
|
|
16961
|
+
for (const target of this.targets.values())
|
|
16962
|
+
due = Math.min(due, target.nextPrewarmAt);
|
|
16963
|
+
if (!Number.isFinite(due))
|
|
16964
|
+
return;
|
|
16965
|
+
this.dueTimer = (this.options.setTimeoutImpl ?? setTimeout)(() => {
|
|
16966
|
+
this.dueTimer = null;
|
|
16967
|
+
return this.tick().catch(() => logger2.warn("cachekeep", "tick failed"));
|
|
16968
|
+
}, Math.max(1, due - (this.options.now?.() ?? Date.now())));
|
|
16969
|
+
this.dueTimer.unref?.();
|
|
16970
|
+
}
|
|
15760
16971
|
dropExpiredTargets(now = this.options.now?.() ?? Date.now()) {
|
|
15761
16972
|
this.pruneTargets(now);
|
|
15762
16973
|
let earliest;
|
|
@@ -15782,8 +16993,9 @@ class CacheKeepManager {
|
|
|
15782
16993
|
removeTarget(target, reason, now, details = {}) {
|
|
15783
16994
|
if (this.targets.get(target.id) !== target)
|
|
15784
16995
|
return;
|
|
16996
|
+
this.reportStop(target, reason, now);
|
|
15785
16997
|
if (now < target.cacheExpiresAt)
|
|
15786
|
-
logger2
|
|
16998
|
+
logger2[reason === "count-cap" ? "debug" : "warn"]("cachekeep", "stopped warming session", {
|
|
15787
16999
|
session: target.id,
|
|
15788
17000
|
reason,
|
|
15789
17001
|
bodyBytes: target.bodyBytes,
|
|
@@ -15807,6 +17019,16 @@ class CacheKeepManager {
|
|
|
15807
17019
|
warmStopped: { at: now, reason }
|
|
15808
17020
|
});
|
|
15809
17021
|
}
|
|
17022
|
+
reportStop(target, reason, at) {
|
|
17023
|
+
const state = target.policyState;
|
|
17024
|
+
if (target.sourceWarm || !state?.hasWarmed || this.reportedStops.has(state))
|
|
17025
|
+
return;
|
|
17026
|
+
if (reportSessionCacheWarmStopped(state.ownerSessionId, {
|
|
17027
|
+
at,
|
|
17028
|
+
reason: reportStopReason(reason)
|
|
17029
|
+
}))
|
|
17030
|
+
this.reportedStops.add(state);
|
|
17031
|
+
}
|
|
15810
17032
|
evictOldestTarget(now, reason) {
|
|
15811
17033
|
const oldest = this.targets.values().next().value;
|
|
15812
17034
|
if (!oldest)
|
|
@@ -15819,11 +17041,12 @@ class CacheKeepManager {
|
|
|
15819
17041
|
}
|
|
15820
17042
|
pruneTargets(now, today) {
|
|
15821
17043
|
for (const [id, target] of this.targets) {
|
|
15822
|
-
if (today && target.dayKey !== today) {
|
|
17044
|
+
if (today && !target.policyState?.planned && target.dayKey !== today) {
|
|
15823
17045
|
this.removeTarget(target, "schedule-period-ended", now);
|
|
15824
17046
|
continue;
|
|
15825
17047
|
}
|
|
15826
17048
|
if (now >= target.cacheExpiresAt) {
|
|
17049
|
+
this.reportStop(target, target.policyState?.planned ? "cost-cap" : "expired", now);
|
|
15827
17050
|
this.targets.delete(id);
|
|
15828
17051
|
this.options.onTargetRemoved?.(id);
|
|
15829
17052
|
}
|
|
@@ -15839,6 +17062,7 @@ class CacheKeepManager {
|
|
|
15839
17062
|
}
|
|
15840
17063
|
track(input) {
|
|
15841
17064
|
const now = this.options.now?.() ?? Date.now();
|
|
17065
|
+
const acceptedAt = input.acceptedAt ?? now;
|
|
15842
17066
|
if (input.retained && input.retained.cacheExpiresAt <= now)
|
|
15843
17067
|
return { tracked: false, reason: "cache expired" };
|
|
15844
17068
|
let bodyBytes;
|
|
@@ -15864,27 +17088,65 @@ class CacheKeepManager {
|
|
|
15864
17088
|
};
|
|
15865
17089
|
if (!input.sessionId)
|
|
15866
17090
|
return refuse("missing session id", "missing-session");
|
|
15867
|
-
|
|
17091
|
+
this.immediateTargets.delete(input.sessionId);
|
|
17092
|
+
let previous = this.targets.get(input.sessionId);
|
|
17093
|
+
if (previous && (previous.oauthAccountId !== input.oauthAccountId || previous.oauthAccountIdentity !== input.oauthAccountIdentity)) {
|
|
17094
|
+
this.removeTarget(previous, "account-changed", now);
|
|
17095
|
+
previous = undefined;
|
|
17096
|
+
}
|
|
17097
|
+
const ownerSessionId = input.ownerSessionId ?? input.retained?.policyState?.ownerSessionId ?? input.sessionId;
|
|
17098
|
+
const policy = readSessionCachePolicy(ownerSessionId, true);
|
|
17099
|
+
const planned = policy?.keep_warm !== undefined;
|
|
17100
|
+
const retire = (reason) => {
|
|
17101
|
+
if (previous)
|
|
17102
|
+
this.removeTarget(previous, reason, now);
|
|
17103
|
+
return refuse(reason, reason);
|
|
17104
|
+
};
|
|
17105
|
+
if (input.retained && (planned || isCacheKeepAlways(input.storage)) && (!input.retained.policyState || input.retained.policyState.needsRealRequest))
|
|
17106
|
+
return retire("unsupported");
|
|
17107
|
+
if (!policy && (input.retained?.policyState?.planned || previous?.policyState?.planned))
|
|
17108
|
+
return retire("session-ended");
|
|
17109
|
+
if (policy?.ttl === "none" || policy?.keep_warm === "off")
|
|
17110
|
+
return retire("unsupported");
|
|
17111
|
+
if (!planned && !isCacheKeepPersistentlyEnabled(input.storage)) {
|
|
15868
17112
|
return refuse("cachekeep disabled", "disabled");
|
|
15869
17113
|
}
|
|
15870
|
-
if (input.cacheMode !== "hybrid") {
|
|
17114
|
+
if (!planned && input.cacheMode !== "hybrid") {
|
|
15871
17115
|
return refuse("cache mode is not hybrid", "not-hybrid");
|
|
15872
17116
|
}
|
|
15873
17117
|
bodyBytes = Buffer.byteLength(input.bodyText, "utf8");
|
|
15874
17118
|
if (bodyBytes > CACHE_KEEP_MAX_BODY_BYTES) {
|
|
17119
|
+
if (planned)
|
|
17120
|
+
return retire("evicted");
|
|
15875
17121
|
return refuse("body exceeds cachekeep memory budget", "body-budget");
|
|
15876
17122
|
}
|
|
15877
17123
|
if (input.bodyText.includes('"thread"')) {
|
|
15878
17124
|
try {
|
|
15879
17125
|
const body = JSON.parse(input.bodyText);
|
|
15880
|
-
if (body.thread)
|
|
17126
|
+
if (body.thread) {
|
|
17127
|
+
if (planned)
|
|
17128
|
+
return retire("unsupported");
|
|
15881
17129
|
return refuse("thread wire bodies are not full stateless cache prefixes", "message-thread-wire-body");
|
|
17130
|
+
}
|
|
15882
17131
|
} catch {}
|
|
15883
17132
|
}
|
|
15884
17133
|
const window = getCacheKeepWindow(input.storage);
|
|
15885
|
-
|
|
17134
|
+
const appliedTtlMs = requestCacheLifetimeMs(input.bodyText);
|
|
17135
|
+
const replayTtlMs = planned || input.sourceWarm ? appliedTtlMs : input.ttlMs;
|
|
17136
|
+
if (planned && appliedTtlMs === 0)
|
|
17137
|
+
return retire("unsupported");
|
|
17138
|
+
if (!planned && !isCacheKeepActiveNow(input.storage, new Date(now))) {
|
|
15886
17139
|
return refuse("outside configured schedule", "outside-schedule");
|
|
15887
17140
|
}
|
|
17141
|
+
if (input.sourceWarm && previous?.sourceWarm && previous.bodyText === input.bodyText && previous.oauthAccountIdentity === input.oauthAccountIdentity && previous.policyState?.lastRealRequestAt === acceptedAt) {
|
|
17142
|
+
const decision = this.policyDecision(previous, now);
|
|
17143
|
+
if (decision?.action === "stop")
|
|
17144
|
+
return retire(decision.reason);
|
|
17145
|
+
if (decision?.action === "wait")
|
|
17146
|
+
previous.nextPrewarmAt = Math.max(previous.nextPrewarmAt, decision.until);
|
|
17147
|
+
this.scheduleDueTimer();
|
|
17148
|
+
return { tracked: true };
|
|
17149
|
+
}
|
|
15888
17150
|
const today = cacheKeepPeriodKey(input.storage, window, new Date(now));
|
|
15889
17151
|
this.pruneTargets(now, today);
|
|
15890
17152
|
if (this.targets.has(input.sessionId))
|
|
@@ -15904,19 +17166,32 @@ class CacheKeepManager {
|
|
|
15904
17166
|
ttlMs: input.retained.ttlMs,
|
|
15905
17167
|
lastTouchAt: input.retained.lastTouchAt,
|
|
15906
17168
|
lastTouchKind: input.retained.lastTouchKind
|
|
15907
|
-
} : input.sourceWarm ? {} : {
|
|
17169
|
+
} : input.sourceWarm ? { ttlMs: replayTtlMs } : {
|
|
15908
17170
|
ttlMs: input.ttlMs ?? CACHE_KEEP_TTL_MS,
|
|
15909
|
-
lastTouchAt:
|
|
17171
|
+
lastTouchAt: acceptedAt,
|
|
15910
17172
|
lastTouchKind: "response"
|
|
15911
17173
|
},
|
|
15912
|
-
cacheExpiresAt: input.retained?.cacheExpiresAt ??
|
|
15913
|
-
nextPrewarmAt: input.retained?.nextPrewarmAt ??
|
|
17174
|
+
cacheExpiresAt: input.retained?.cacheExpiresAt ?? acceptedAt + (replayTtlMs ?? CACHE_KEEP_TTL_MS),
|
|
17175
|
+
nextPrewarmAt: input.retained?.nextPrewarmAt ?? (planned || input.sourceWarm ? acceptedAt + (replayTtlMs ?? CACHE_KEEP_TTL_MS) - replayPrewarmLeadMs(replayTtlMs ?? CACHE_KEEP_TTL_MS, planned) : acceptedAt + (policy?.ttl ? CACHE_KEEP_TTL_MS : replayTtlMs ?? CACHE_KEEP_TTL_MS) - CACHE_KEEP_PREWARM_LEAD_MS),
|
|
15914
17176
|
consecutiveFailures: 0,
|
|
15915
17177
|
dayKey: today,
|
|
15916
17178
|
oauthAccountId: input.oauthAccountId,
|
|
15917
17179
|
oauthAccountIdentity: input.oauthAccountIdentity,
|
|
15918
17180
|
accountStoragePath: input.accountStoragePath,
|
|
15919
17181
|
isSubagent: input.isSubagent ?? false,
|
|
17182
|
+
policyState: input.retained?.policyState ? {
|
|
17183
|
+
...input.retained.policyState,
|
|
17184
|
+
warmCostSoFar: input.retained.policyState.warmCostSoFar + (input.retained.policyState.pendingWarmCost ?? 0),
|
|
17185
|
+
pendingWarmCost: undefined
|
|
17186
|
+
} : {
|
|
17187
|
+
ownerSessionId,
|
|
17188
|
+
planned,
|
|
17189
|
+
lastRealRequestAt: acceptedAt,
|
|
17190
|
+
warmsSinceLastRealRequest: 0,
|
|
17191
|
+
warmCostSoFar: 0,
|
|
17192
|
+
hasWarmed: previous?.policyState?.hasWarmed ?? false,
|
|
17193
|
+
...input.retained && { needsRealRequest: true }
|
|
17194
|
+
},
|
|
15920
17195
|
...input.sourceWarm === true && { sourceWarm: true }
|
|
15921
17196
|
});
|
|
15922
17197
|
this.pruneTargets(now, today);
|
|
@@ -15924,11 +17199,29 @@ class CacheKeepManager {
|
|
|
15924
17199
|
const target = this.targets.get(input.sessionId);
|
|
15925
17200
|
if (!target)
|
|
15926
17201
|
return { tracked: false, reason: "evicted by cachekeep limits" };
|
|
17202
|
+
if (input.acceptedUsage)
|
|
17203
|
+
updateAcceptedUsage(target, input.bodyText, input.acceptedUsage);
|
|
17204
|
+
if (planned) {
|
|
17205
|
+
target.ttlMs = appliedTtlMs;
|
|
17206
|
+
if (!input.retained)
|
|
17207
|
+
target.cacheExpiresAt = acceptedAt + appliedTtlMs;
|
|
17208
|
+
const decision = this.policyDecision(target, now);
|
|
17209
|
+
if (decision?.action === "stop") {
|
|
17210
|
+
this.removeTarget(target, decision.reason, now);
|
|
17211
|
+
return { tracked: false, reason: decision.reason };
|
|
17212
|
+
}
|
|
17213
|
+
if (decision?.action === "wait")
|
|
17214
|
+
target.nextPrewarmAt = decision.until;
|
|
17215
|
+
}
|
|
15927
17216
|
this.options.onTargetChanged?.(target);
|
|
15928
17217
|
this.start();
|
|
17218
|
+
this.scheduleDueTimer();
|
|
15929
17219
|
return { tracked: true };
|
|
15930
17220
|
}
|
|
15931
17221
|
async prewarmNow(input) {
|
|
17222
|
+
const current = this.targets.get(input.sessionId);
|
|
17223
|
+
if (current && (current.bodyText !== input.bodyText || current.url !== input.url || current.oauthAccountId !== input.oauthAccountId || current.oauthAccountIdentity !== input.oauthAccountIdentity))
|
|
17224
|
+
return { ok: false, refused: true, reason: "stopped" };
|
|
15932
17225
|
const headers = {};
|
|
15933
17226
|
input.headers.forEach((value, key) => {
|
|
15934
17227
|
headers[key] = value;
|
|
@@ -15936,7 +17229,6 @@ class CacheKeepManager {
|
|
|
15936
17229
|
const target = {
|
|
15937
17230
|
id: input.sessionId,
|
|
15938
17231
|
url: input.url,
|
|
15939
|
-
headers,
|
|
15940
17232
|
bodyText: input.bodyText,
|
|
15941
17233
|
bodyBytes: Buffer.byteLength(input.bodyText, "utf8"),
|
|
15942
17234
|
cacheExpiresAt: this.options.now?.() ?? Date.now(),
|
|
@@ -15946,9 +17238,26 @@ class CacheKeepManager {
|
|
|
15946
17238
|
oauthAccountId: input.oauthAccountId,
|
|
15947
17239
|
oauthAccountIdentity: input.oauthAccountIdentity,
|
|
15948
17240
|
accountStoragePath: input.accountStoragePath,
|
|
15949
|
-
isSubagent: input.isSubagent ?? false
|
|
17241
|
+
isSubagent: input.isSubagent ?? false,
|
|
17242
|
+
...current,
|
|
17243
|
+
headers
|
|
15950
17244
|
};
|
|
15951
|
-
|
|
17245
|
+
if (!current)
|
|
17246
|
+
this.immediateTargets.set(target.id, target);
|
|
17247
|
+
try {
|
|
17248
|
+
let acceptedAt;
|
|
17249
|
+
const result = await this.sendPrewarm(target, (receivedAt) => {
|
|
17250
|
+
acceptedAt = receivedAt;
|
|
17251
|
+
});
|
|
17252
|
+
if (result.ok && current && this.isCurrentTarget(target)) {
|
|
17253
|
+
this.acceptWarm(current, result, acceptedAt ?? this.options.now?.() ?? Date.now());
|
|
17254
|
+
this.scheduleDueTimer();
|
|
17255
|
+
}
|
|
17256
|
+
return result;
|
|
17257
|
+
} finally {
|
|
17258
|
+
if (this.immediateTargets.get(target.id) === target)
|
|
17259
|
+
this.immediateTargets.delete(target.id);
|
|
17260
|
+
}
|
|
15952
17261
|
}
|
|
15953
17262
|
tick() {
|
|
15954
17263
|
if (this.tickPromise)
|
|
@@ -15957,6 +17266,7 @@ class CacheKeepManager {
|
|
|
15957
17266
|
run = this.runTick().finally(() => {
|
|
15958
17267
|
if (this.tickPromise === run)
|
|
15959
17268
|
this.tickPromise = null;
|
|
17269
|
+
this.scheduleDueTimer();
|
|
15960
17270
|
});
|
|
15961
17271
|
this.tickPromise = run;
|
|
15962
17272
|
return run;
|
|
@@ -15977,25 +17287,42 @@ class CacheKeepManager {
|
|
|
15977
17287
|
this.stop();
|
|
15978
17288
|
return;
|
|
15979
17289
|
}
|
|
15980
|
-
if (!isCacheKeepHybridActive(storage)) {
|
|
15981
|
-
for (const target of this.targets.values())
|
|
15982
|
-
this.removeTarget(target, "cachekeep-hybrid-inactive", now);
|
|
15983
|
-
this.publishTrackedSessions();
|
|
15984
|
-
return;
|
|
15985
|
-
}
|
|
15986
|
-
if (!isCacheKeepActiveNow(storage, new Date(now))) {
|
|
15987
|
-
for (const target of this.targets.values())
|
|
15988
|
-
this.removeTarget(target, "schedule-period-ended", now);
|
|
15989
|
-
this.publishTrackedSessions();
|
|
15990
|
-
return;
|
|
15991
|
-
}
|
|
15992
17290
|
logger2.debug("cachekeep", "fired", { targets: this.targets.size });
|
|
15993
|
-
|
|
17291
|
+
const targets = [...this.targets.values()].sort((a, b) => this.lastPrewarmStart(a) - this.lastPrewarmStart(b));
|
|
17292
|
+
for (const target of targets) {
|
|
17293
|
+
if (this.targets.get(target.id) !== target)
|
|
17294
|
+
continue;
|
|
15994
17295
|
const attemptAt = this.options.now?.() ?? Date.now();
|
|
17296
|
+
const decision = this.policyDecision(target, attemptAt);
|
|
17297
|
+
if (decision?.action === "stop") {
|
|
17298
|
+
this.removeTarget(target, decision.reason, attemptAt);
|
|
17299
|
+
continue;
|
|
17300
|
+
}
|
|
17301
|
+
if (decision?.action === "wait") {
|
|
17302
|
+
target.nextPrewarmAt = Math.max(target.nextPrewarmAt, decision.until);
|
|
17303
|
+
continue;
|
|
17304
|
+
}
|
|
17305
|
+
if (!target.policyState?.planned) {
|
|
17306
|
+
if (!isCacheKeepHybridActive(storage)) {
|
|
17307
|
+
this.removeTarget(target, "cachekeep-hybrid-inactive", attemptAt);
|
|
17308
|
+
continue;
|
|
17309
|
+
}
|
|
17310
|
+
if (!isCacheKeepActiveNow(storage, new Date(attemptAt))) {
|
|
17311
|
+
this.removeTarget(target, "schedule-period-ended", attemptAt);
|
|
17312
|
+
continue;
|
|
17313
|
+
}
|
|
17314
|
+
if (isCacheKeepAlways(storage)) {
|
|
17315
|
+
const count = this.countDecision(target);
|
|
17316
|
+
if (count?.action === "stop") {
|
|
17317
|
+
this.removeTarget(target, count.reason, attemptAt);
|
|
17318
|
+
continue;
|
|
17319
|
+
}
|
|
17320
|
+
}
|
|
17321
|
+
}
|
|
15995
17322
|
if (target.nextPrewarmAt > attemptAt)
|
|
15996
17323
|
continue;
|
|
15997
17324
|
if (attemptAt > this.lastPrewarmStart(target)) {
|
|
15998
|
-
this.removeTarget(target, "retry-window-ended", attemptAt);
|
|
17325
|
+
this.removeTarget(target, target.policyState?.planned ? "cost-cap" : "retry-window-ended", attemptAt);
|
|
15999
17326
|
continue;
|
|
16000
17327
|
}
|
|
16001
17328
|
try {
|
|
@@ -16016,13 +17343,13 @@ class CacheKeepManager {
|
|
|
16016
17343
|
this.publishTrackedSessions();
|
|
16017
17344
|
}
|
|
16018
17345
|
lastPrewarmStart(target) {
|
|
16019
|
-
return target.cacheExpiresAt - (this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS) - CACHE_KEEP_EXPIRY_SAFETY_MS;
|
|
17346
|
+
return target.cacheExpiresAt - (target.policyState?.planned || target.sourceWarm ? 0 : this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS) - CACHE_KEEP_EXPIRY_SAFETY_MS;
|
|
16020
17347
|
}
|
|
16021
17348
|
scheduleRetry(target, transient) {
|
|
16022
17349
|
const now = this.options.now?.() ?? Date.now();
|
|
16023
17350
|
const deadline = this.lastPrewarmStart(target);
|
|
16024
17351
|
if (now >= deadline) {
|
|
16025
|
-
this.removeTarget(target, "retry-window-ended", now);
|
|
17352
|
+
this.removeTarget(target, target.policyState?.planned ? "cost-cap" : "retry-window-ended", now);
|
|
16026
17353
|
return;
|
|
16027
17354
|
}
|
|
16028
17355
|
target.consecutiveFailures += 1;
|
|
@@ -16031,9 +17358,13 @@ class CacheKeepManager {
|
|
|
16031
17358
|
target.nextPrewarmAt = Math.min(now + delay3, deadline);
|
|
16032
17359
|
}
|
|
16033
17360
|
async sendPrewarm(target, onAccepted) {
|
|
17361
|
+
const remaining = target.cacheExpiresAt - (this.options.now?.() ?? Date.now()) - CACHE_KEEP_EXPIRY_SAFETY_MS;
|
|
17362
|
+
const timeout = Math.min(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS, target.policyState?.planned || target.sourceWarm ? remaining : Infinity);
|
|
17363
|
+
if (timeout <= 0)
|
|
17364
|
+
return { ok: false, refused: true, reason: "cost-cap" };
|
|
16034
17365
|
const attempt = {
|
|
16035
17366
|
id: ++this.nextPrewarmAttemptId,
|
|
16036
|
-
signal: AbortSignal.timeout(
|
|
17367
|
+
signal: AbortSignal.timeout(timeout)
|
|
16037
17368
|
};
|
|
16038
17369
|
let stage = "authorization";
|
|
16039
17370
|
let responseStatus;
|
|
@@ -16092,6 +17423,13 @@ class CacheKeepManager {
|
|
|
16092
17423
|
stage = "send";
|
|
16093
17424
|
let response;
|
|
16094
17425
|
const send = async (attemptHeaders) => {
|
|
17426
|
+
if (!this.isCurrentTarget(target))
|
|
17427
|
+
throw new CacheKeepWarmRefusal("stopped");
|
|
17428
|
+
if (this.targets.has(target.id) || target.policyState) {
|
|
17429
|
+
if (!this.options.deferWarmReservation)
|
|
17430
|
+
await this.reserveWarmDispatch(target);
|
|
17431
|
+
}
|
|
17432
|
+
attempt.signal.throwIfAborted();
|
|
16095
17433
|
const scope = createProviderErrorResponseScope(cacheKeepSentCredentials(attemptHeaders), "http");
|
|
16096
17434
|
try {
|
|
16097
17435
|
const sent = await fetchImpl(target.url, {
|
|
@@ -16100,6 +17438,13 @@ class CacheKeepManager {
|
|
|
16100
17438
|
body: prewarm.bodyText,
|
|
16101
17439
|
signal: attempt.signal
|
|
16102
17440
|
});
|
|
17441
|
+
if (!sent.ok && this.isCurrentTarget(target) && target.policyState) {
|
|
17442
|
+
const state = target.policyState;
|
|
17443
|
+
const cost = this.admittedWarmCosts.get(state) ?? 0;
|
|
17444
|
+
target.policyState.pendingWarmCost = Math.max(0, (target.policyState.pendingWarmCost ?? 0) - cost) || undefined;
|
|
17445
|
+
this.admittedWarmCosts.delete(state);
|
|
17446
|
+
await this.options.settleWarm?.(target);
|
|
17447
|
+
}
|
|
16103
17448
|
return scope.redactResponse(sent);
|
|
16104
17449
|
} catch (error) {
|
|
16105
17450
|
if (nativeAccountRefusal(error)) {
|
|
@@ -16138,6 +17483,7 @@ class CacheKeepManager {
|
|
|
16138
17483
|
responseStatus = response.status;
|
|
16139
17484
|
const receivedAt = this.options.now?.() ?? Date.now();
|
|
16140
17485
|
const raw = await response.text();
|
|
17486
|
+
attempt.signal.throwIfAborted();
|
|
16141
17487
|
let data = null;
|
|
16142
17488
|
try {
|
|
16143
17489
|
data = raw ? JSON.parse(raw) : null;
|
|
@@ -16183,8 +17529,14 @@ class CacheKeepManager {
|
|
|
16183
17529
|
const objectData = data && typeof data === "object" && !Array.isArray(data) ? data : null;
|
|
16184
17530
|
const usage = objectData?.usage;
|
|
16185
17531
|
onAccepted?.(receivedAt);
|
|
16186
|
-
return {
|
|
17532
|
+
return {
|
|
17533
|
+
ok: true,
|
|
17534
|
+
ttlMs: this.options.responseTtlMs?.(response) ?? requestCacheLifetimeMs(prewarm.bodyText),
|
|
17535
|
+
...usage && { usage }
|
|
17536
|
+
};
|
|
16187
17537
|
} catch (error) {
|
|
17538
|
+
if (error instanceof CacheKeepWarmRefusal)
|
|
17539
|
+
return { ok: false, refused: true, reason: error.reason };
|
|
16188
17540
|
const failure = classifyCacheKeepFailure(error, stage, responseStatus);
|
|
16189
17541
|
const refusal = nativeAccountRefusal(error);
|
|
16190
17542
|
if (refusal)
|
|
@@ -16245,16 +17597,38 @@ class CacheKeepManager {
|
|
|
16245
17597
|
if (this.targets.get(target.id) !== target)
|
|
16246
17598
|
return;
|
|
16247
17599
|
acceptedAt ??= this.options.now?.() ?? Date.now();
|
|
16248
|
-
target
|
|
17600
|
+
this.acceptWarm(target, result, acceptedAt);
|
|
17601
|
+
}
|
|
17602
|
+
acceptWarm(target, result, acceptedAt) {
|
|
17603
|
+
const state = target.policyState;
|
|
17604
|
+
if (state) {
|
|
17605
|
+
state.hasWarmed = true;
|
|
17606
|
+
state.lastWarmAt = acceptedAt;
|
|
17607
|
+
const cost = this.admittedWarmCosts.get(state) ?? 0;
|
|
17608
|
+
state.warmCostSoFar += cost;
|
|
17609
|
+
state.pendingWarmCost = Math.max(0, (state.pendingWarmCost ?? 0) - cost) || undefined;
|
|
17610
|
+
this.admittedWarmCosts.delete(state);
|
|
17611
|
+
this.reportedStops.delete(state);
|
|
17612
|
+
if (!target.sourceWarm)
|
|
17613
|
+
reportSessionCacheTouch(state.ownerSessionId, {
|
|
17614
|
+
at: acceptedAt,
|
|
17615
|
+
ttlMs: result.ttlMs ?? requestCacheLifetimeMs(target.bodyText),
|
|
17616
|
+
source: "warm"
|
|
17617
|
+
});
|
|
17618
|
+
}
|
|
17619
|
+
target.ttlMs = state?.planned || target.sourceWarm ? target.ttlMs : CACHE_KEEP_TTL_MS;
|
|
16249
17620
|
target.lastTouchAt = acceptedAt;
|
|
16250
17621
|
target.lastTouchKind = "warm";
|
|
16251
|
-
target.cacheExpiresAt = acceptedAt + CACHE_KEEP_TTL_MS;
|
|
16252
|
-
target.nextPrewarmAt = target.cacheExpiresAt - CACHE_KEEP_PREWARM_LEAD_MS;
|
|
17622
|
+
target.cacheExpiresAt = acceptedAt + (target.ttlMs ?? CACHE_KEEP_TTL_MS);
|
|
17623
|
+
target.nextPrewarmAt = state?.planned || target.sourceWarm ? target.cacheExpiresAt - replayPrewarmLeadMs(target.ttlMs ?? CACHE_KEEP_TTL_MS, state?.planned === true) : (readSessionCachePolicy(state?.ownerSessionId ?? target.id, true)?.ttl ? acceptedAt + CACHE_KEEP_TTL_MS : target.cacheExpiresAt) - CACHE_KEEP_PREWARM_LEAD_MS;
|
|
16253
17624
|
target.consecutiveFailures = 0;
|
|
16254
17625
|
logger2.debug("cachekeep", "prewarm succeeded", {
|
|
16255
17626
|
session: target.id,
|
|
16256
17627
|
...result.usage && { usage: result.usage }
|
|
16257
17628
|
});
|
|
17629
|
+
const decision = this.policyDecision(target, acceptedAt);
|
|
17630
|
+
if (decision?.action === "stop")
|
|
17631
|
+
this.removeTarget(target, decision.reason, acceptedAt);
|
|
16258
17632
|
}
|
|
16259
17633
|
}
|
|
16260
17634
|
// src/cachekeep-registry.ts
|
|
@@ -16282,8 +17656,8 @@ import { uptime } from "node:os";
|
|
|
16282
17656
|
import { basename as basename9, dirname as dirname17, join as join20 } from "node:path";
|
|
16283
17657
|
|
|
16284
17658
|
// src/native-lock-observer.ts
|
|
16285
|
-
import { AsyncLocalStorage as
|
|
16286
|
-
var detachedLocks = new
|
|
17659
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
|
|
17660
|
+
var detachedLocks = new AsyncLocalStorage3;
|
|
16287
17661
|
function withDetachedNativeLocks(work) {
|
|
16288
17662
|
return detachedLocks.run(true, work);
|
|
16289
17663
|
}
|
|
@@ -16412,9 +17786,9 @@ function recordIdentityIn(tx, id, identity2) {
|
|
|
16412
17786
|
return disableIdentityDuplicates(tx, identity2);
|
|
16413
17787
|
}
|
|
16414
17788
|
// ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
|
|
16415
|
-
import { AsyncLocalStorage as
|
|
16416
|
-
var insideHook = new
|
|
16417
|
-
var insideCodec = new
|
|
17789
|
+
import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
|
|
17790
|
+
var insideHook = new AsyncLocalStorage4;
|
|
17791
|
+
var insideCodec = new AsyncLocalStorage4;
|
|
16418
17792
|
function assertNotInsideHook(operation) {
|
|
16419
17793
|
if (insideHook.getStore() !== undefined)
|
|
16420
17794
|
throw new PoolReentryError(operation);
|
|
@@ -17918,7 +19292,7 @@ async function protectIn(tx, id, protect) {
|
|
|
17918
19292
|
if (!protect)
|
|
17919
19293
|
return;
|
|
17920
19294
|
const rows = tx.rows().map((row) => {
|
|
17921
|
-
const { id: id2, type, label, enabled, disabledReason, identity: identity2, credentialEpoch, stamp, staged, torn, invalid } = row;
|
|
19295
|
+
const { id: id2, type, label, enabled, disabledReason, identity: identity2, credentialEpoch, stamp, staged, torn, invalid: invalid2 } = row;
|
|
17922
19296
|
return {
|
|
17923
19297
|
id: id2,
|
|
17924
19298
|
type,
|
|
@@ -17930,7 +19304,7 @@ async function protectIn(tx, id, protect) {
|
|
|
17930
19304
|
stamp,
|
|
17931
19305
|
staged,
|
|
17932
19306
|
torn,
|
|
17933
|
-
invalid
|
|
19307
|
+
invalid: invalid2
|
|
17934
19308
|
};
|
|
17935
19309
|
});
|
|
17936
19310
|
const reason = await runInsideHook(tx.info.operation, () => protect({
|
|
@@ -19727,8 +21101,8 @@ function openPoolStore(options) {
|
|
|
19727
21101
|
firePull: (id, reason) => pulls.fire(id, reason)
|
|
19728
21102
|
};
|
|
19729
21103
|
const quotaWriter = options.coalesceQuota ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs, options.quotaCommitTimer) : undefined;
|
|
19730
|
-
const
|
|
19731
|
-
rt.publishQuota =
|
|
21104
|
+
const record4 = (id, attribution, observation) => quotaWriter ? quotaWriter.record(id, attribution, observation) : recordQuota(rt, id, attribution, observation);
|
|
21105
|
+
rt.publishQuota = record4;
|
|
19732
21106
|
const overlay = (result) => {
|
|
19733
21107
|
if (result.status === "ready" && quotaWriter)
|
|
19734
21108
|
return { ...result, rows: quotaWriter.overlay(result.rows) };
|
|
@@ -19765,7 +21139,7 @@ function openPoolStore(options) {
|
|
|
19765
21139
|
updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
|
|
19766
21140
|
recordIdentity: (id, identity2, attribution, callOptions) => recordRowIdentity(rt, id, identity2, attribution, callOptions),
|
|
19767
21141
|
refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
|
|
19768
|
-
recordQuota:
|
|
21142
|
+
recordQuota: record4,
|
|
19769
21143
|
close: () => quotaWriter?.close() ?? Promise.resolve(),
|
|
19770
21144
|
dispose: () => quotaWriter?.close() ?? Promise.resolve(),
|
|
19771
21145
|
requestReading: (id) => pulls.fire(id, "admission"),
|
|
@@ -19983,7 +21357,7 @@ function nativeMigrationCanonicalJson(value) {
|
|
|
19983
21357
|
function nativeMigrationDigest(value) {
|
|
19984
21358
|
return createHash12("sha256").update(nativeMigrationCanonicalJson(value)).digest("hex");
|
|
19985
21359
|
}
|
|
19986
|
-
function
|
|
21360
|
+
function record4(value) {
|
|
19987
21361
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
19988
21362
|
}
|
|
19989
21363
|
function optionalField(value, key, kind) {
|
|
@@ -19995,7 +21369,7 @@ function optionalField(value, key, kind) {
|
|
|
19995
21369
|
}
|
|
19996
21370
|
function nativeMigrationCredentialDigest(credential) {
|
|
19997
21371
|
const value = captureNativeMigrationJson(credential);
|
|
19998
|
-
if (!
|
|
21372
|
+
if (!record4(value))
|
|
19999
21373
|
refuse();
|
|
20000
21374
|
if (value.type === "oauth" && typeof value.refresh === "string") {
|
|
20001
21375
|
if (Object.keys(value).some((key) => !["type", "access", "refresh", "expires", "lastRefreshedAt"].includes(key)))
|
|
@@ -20057,10 +21431,10 @@ function captureNativeMigrationPreparedProof(rows, runtimeProjection) {
|
|
|
20057
21431
|
function decodeNativeMigrationPreparedProof(input) {
|
|
20058
21432
|
const value = captureNativeMigrationJson(input);
|
|
20059
21433
|
const digest = (item) => typeof item === "string" && /^[a-f0-9]{64}$/.test(item);
|
|
20060
|
-
if (!
|
|
21434
|
+
if (!record4(value) || Object.keys(value).length !== 3 || value.version !== 1 || !Array.isArray(value.rows) || !digest(value.runtimeDigest))
|
|
20061
21435
|
refuse();
|
|
20062
21436
|
const rows = value.rows.map((item) => {
|
|
20063
|
-
if (!
|
|
21437
|
+
if (!record4(item) || Object.keys(item).length !== 5 || typeof item.id !== "string" || !item.id || typeof item.credentialEpoch !== "number" || !Number.isSafeInteger(item.credentialEpoch) || item.credentialEpoch <= 0 || !(item.identity === null || typeof item.identity === "string" && item.identity.length > 0) || item.stamp !== "bound" || typeof item.credentialDigest !== "string" || !digest(item.credentialDigest))
|
|
20064
21438
|
refuse();
|
|
20065
21439
|
return {
|
|
20066
21440
|
id: item.id,
|
|
@@ -20086,7 +21460,7 @@ class NativeQuotaCodecError extends Error {
|
|
|
20086
21460
|
this.name = "NativeQuotaCodecError";
|
|
20087
21461
|
}
|
|
20088
21462
|
}
|
|
20089
|
-
function
|
|
21463
|
+
function record5(value) {
|
|
20090
21464
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20091
21465
|
}
|
|
20092
21466
|
function keys(value, required, optional2 = []) {
|
|
@@ -20108,13 +21482,13 @@ function source(value) {
|
|
|
20108
21482
|
return value === "poll" || value === "headers";
|
|
20109
21483
|
}
|
|
20110
21484
|
function money(value) {
|
|
20111
|
-
return
|
|
21485
|
+
return record5(value) && keys(value, ["amountMinor", "currency", "exponent"]) && finite(value.amountMinor) && text(value.currency) && /^[A-Za-z]{3}$/.test(value.currency) && finite(value.exponent) && Number.isInteger(value.exponent) && value.exponent >= 0 && value.exponent <= 20;
|
|
20112
21486
|
}
|
|
20113
21487
|
function extraUsage(value) {
|
|
20114
|
-
return
|
|
21488
|
+
return record5(value) && keys(value, ["used", "limit", "exhausted"], ["utilizationPercent", "severity"]) && money(value.used) && money(value.limit) && typeof value.exhausted === "boolean" && optional2(value, "utilizationPercent", finite) && optional2(value, "severity", (entry) => typeof entry === "string");
|
|
20115
21489
|
}
|
|
20116
21490
|
function fieldSources(value) {
|
|
20117
|
-
return
|
|
21491
|
+
return record5(value) && keys(value, [], QUOTA_FIELD_NAMES) && Object.values(value).every(source);
|
|
20118
21492
|
}
|
|
20119
21493
|
var metadataKeys = [
|
|
20120
21494
|
"checkedAt",
|
|
@@ -20130,7 +21504,7 @@ function metadataFields(value) {
|
|
|
20130
21504
|
return optional2(value, "checkedAt", time) && optional2(value, "accountIdentity", text) && optional2(value, "extraUsage", extraUsage) && optional2(value, "bindingWindow", text) && optional2(value, "bindingWindowSource", source) && optional2(value, "fieldSources", fieldSources) && optional2(value, "fallbackAdvised", (entry) => typeof entry === "boolean") && optional2(value, "source", source);
|
|
20131
21505
|
}
|
|
20132
21506
|
function window(value, scoped) {
|
|
20133
|
-
if (!
|
|
21507
|
+
if (!record5(value) || !keys(value, scoped ? [
|
|
20134
21508
|
"usedPercent",
|
|
20135
21509
|
"remainingPercent",
|
|
20136
21510
|
"checkedAt",
|
|
@@ -20142,13 +21516,13 @@ function window(value, scoped) {
|
|
|
20142
21516
|
return finite(value.usedPercent) && finite(value.remainingPercent) && time(value.checkedAt) && optional2(value, "resetsAt", (entry) => typeof entry === "string") && (!scoped || text(value.id) && text(value.title) && text(value.modelName) && optional2(value, "modelId", text));
|
|
20143
21517
|
}
|
|
20144
21518
|
function isNativeOAuthQuotaSnapshot(value) {
|
|
20145
|
-
return
|
|
21519
|
+
return record5(value) && keys(value, [], ["five_hour", "seven_day", "scoped", ...metadataKeys]) && metadataFields(value) && optional2(value, "five_hour", (entry) => window(entry, false)) && optional2(value, "seven_day", (entry) => window(entry, false)) && optional2(value, "scoped", (entry) => Array.isArray(entry) && entry.every((item) => window(item, true)) && new Set(entry.map((item) => item.id)).size === entry.length);
|
|
20146
21520
|
}
|
|
20147
21521
|
function scopedMetadata(value) {
|
|
20148
|
-
return
|
|
21522
|
+
return record5(value) && keys(value, ["id", "title", "modelName", "remainingPercent"], ["modelId"]) && text(value.id) && text(value.title) && text(value.modelName) && optional2(value, "modelId", text) && finite(value.remainingPercent);
|
|
20149
21523
|
}
|
|
20150
21524
|
function nativeMetadata(value) {
|
|
20151
|
-
return
|
|
21525
|
+
return record5(value) && keys(value, ["version", "remainingPercent"], ["scoped", ...metadataKeys]) && value.version === 1 && metadataFields(value) && record5(value.remainingPercent) && keys(value.remainingPercent, [], ["five_hour", "seven_day"]) && Object.values(value.remainingPercent).every(finite) && optional2(value, "scoped", (entry) => Array.isArray(entry) && entry.every(scopedMetadata));
|
|
20152
21526
|
}
|
|
20153
21527
|
function nativeQuotaModelScope(model) {
|
|
20154
21528
|
const normalized = model.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
@@ -20230,7 +21604,7 @@ function encodeNativeQuotaMap(json) {
|
|
|
20230
21604
|
return result;
|
|
20231
21605
|
}
|
|
20232
21606
|
function reading(value) {
|
|
20233
|
-
return
|
|
21607
|
+
return record5(value) && keys(value, ["scope", "label", "kind", "checkedAt", "usedPercent"], ["resetsAt"]) && text(value.scope) && text(value.label) && value.kind === "reading" && time(value.checkedAt) && finite(value.usedPercent) && optional2(value, "resetsAt", (entry) => typeof entry === "string");
|
|
20234
21608
|
}
|
|
20235
21609
|
function equalJson(a, b) {
|
|
20236
21610
|
if (Array.isArray(a) && Array.isArray(b)) {
|
|
@@ -20242,12 +21616,12 @@ function equalJson(a, b) {
|
|
|
20242
21616
|
}
|
|
20243
21617
|
return true;
|
|
20244
21618
|
}
|
|
20245
|
-
if (
|
|
21619
|
+
if (record5(a) && record5(b))
|
|
20246
21620
|
return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => Object.hasOwn(b, key) && equalJson(a[key], b[key]));
|
|
20247
21621
|
return a !== undefined && a === b;
|
|
20248
21622
|
}
|
|
20249
21623
|
function fromNativeQuotaMap(value) {
|
|
20250
|
-
if (!
|
|
21624
|
+
if (!record5(value) || !keys(value, ["limits", "anthropic"], ["budget"]) || !isQuotaMap(value) || !value.limits.every(reading) || !nativeMetadata(value.anthropic))
|
|
20251
21625
|
throw new NativeQuotaCodecError;
|
|
20252
21626
|
const {
|
|
20253
21627
|
version: _version,
|
|
@@ -20346,8 +21720,8 @@ function validEpoch(value) {
|
|
|
20346
21720
|
function isNativeLocalPoolBinding(value) {
|
|
20347
21721
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
20348
21722
|
return false;
|
|
20349
|
-
const
|
|
20350
|
-
return
|
|
21723
|
+
const record6 = value;
|
|
21724
|
+
return record6.kind === "local" && typeof record6.storageId === "string" && /^[a-f0-9]{64}$/.test(record6.storageId) && nonempty(record6.rowId) && validEpoch(record6.credentialEpoch) && (record6.identity === undefined || nonempty(record6.identity)) && ["kind", "storageId", "rowId", "credentialEpoch"].every((key) => Object.hasOwn(record6, key)) && (record6.identity === undefined || Object.hasOwn(record6, "identity")) && Object.keys(record6).every((key) => ["kind", "storageId", "rowId", "credentialEpoch", "identity"].includes(key));
|
|
20351
21725
|
}
|
|
20352
21726
|
function coherent(row) {
|
|
20353
21727
|
return row.stamp === "bound" && !row.invalid && !row.torn && !row.unbound && nonempty(row.id) && validEpoch(row.credentialEpoch) && (row.identity === undefined || nonempty(row.identity));
|
|
@@ -20388,7 +21762,7 @@ function tokenFingerprint(token) {
|
|
|
20388
21762
|
}
|
|
20389
21763
|
|
|
20390
21764
|
// src/native-credential-validation.ts
|
|
20391
|
-
function
|
|
21765
|
+
function record6(value) {
|
|
20392
21766
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20393
21767
|
}
|
|
20394
21768
|
function keys2(value, required, optional3 = []) {
|
|
@@ -20401,12 +21775,12 @@ function token(value) {
|
|
|
20401
21775
|
return typeof value === "string" && value.length > 0 && value.trim() === value;
|
|
20402
21776
|
}
|
|
20403
21777
|
function isNativeLocalCredentialValidation(value) {
|
|
20404
|
-
if (!
|
|
21778
|
+
if (!record6(value) || !keys2(value, ["binding", "credentialFingerprint", "version"]) || !isNativeLocalPoolBinding(value.binding) || value.binding.identity === undefined || typeof value.credentialFingerprint !== "string" || !/^[a-f0-9]{64}$/.test(value.credentialFingerprint) || !record6(value.version) || !keys2(value.version, ["accessFingerprint", "expires"], ["lastRefreshedAt"]))
|
|
20405
21779
|
return false;
|
|
20406
21780
|
return typeof value.version.accessFingerprint === "string" && /^[a-f0-9]{16}$/.test(value.version.accessFingerprint) && timestamp(value.version.expires) && value.version.expires > 0 && (!Object.hasOwn(value.version, "lastRefreshedAt") || timestamp(value.version.lastRefreshedAt));
|
|
20407
21781
|
}
|
|
20408
21782
|
function nativeLocalCredentialValidationMatches(validation, binding, material) {
|
|
20409
|
-
if (!isNativeLocalCredentialValidation(validation) || !isNativeLocalPoolBinding(binding) || binding.identity === undefined || !
|
|
21783
|
+
if (!isNativeLocalCredentialValidation(validation) || !isNativeLocalPoolBinding(binding) || binding.identity === undefined || !record6(material) || material.type !== "oauth" || !token(material.access) || !token(material.refresh) || !timestamp(material.expires) || material.expires <= 0 || Object.hasOwn(material, "lastRefreshedAt") && !timestamp(material.lastRefreshedAt))
|
|
20410
21784
|
return false;
|
|
20411
21785
|
return validation.binding.storageId === binding.storageId && validation.binding.rowId === binding.rowId && validation.binding.credentialEpoch === binding.credentialEpoch && validation.binding.identity === binding.identity && validation.credentialFingerprint === fingerprintOf({ type: "oauth", refresh: material.refresh }) && validation.version.accessFingerprint === tokenFingerprint(material.access) && validation.version.expires === material.expires && Object.hasOwn(validation.version, "lastRefreshedAt") === Object.hasOwn(material, "lastRefreshedAt") && validation.version.lastRefreshedAt === material.lastRefreshedAt;
|
|
20412
21786
|
}
|
|
@@ -20586,7 +21960,7 @@ class NativeRuntimeError extends Error {
|
|
|
20586
21960
|
}
|
|
20587
21961
|
}
|
|
20588
21962
|
}
|
|
20589
|
-
function
|
|
21963
|
+
function record7(value) {
|
|
20590
21964
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
20591
21965
|
}
|
|
20592
21966
|
function keys3(value, required, optional3 = []) {
|
|
@@ -20614,7 +21988,7 @@ function accountUuid(value) {
|
|
|
20614
21988
|
return typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(value);
|
|
20615
21989
|
}
|
|
20616
21990
|
function binding(value) {
|
|
20617
|
-
return isNativeLocalPoolBinding(value) ||
|
|
21991
|
+
return isNativeLocalPoolBinding(value) || record7(value) && keys3(value, [
|
|
20618
21992
|
"kind",
|
|
20619
21993
|
"storageId",
|
|
20620
21994
|
"routeId",
|
|
@@ -20624,7 +21998,7 @@ function binding(value) {
|
|
|
20624
21998
|
]) && value.kind === "custody" && digest(value.storageId) && text2(value.routeId) && text2(value.credentialId) && text2(value.accountIdentity) && counter(value.recordVersion);
|
|
20625
21999
|
}
|
|
20626
22000
|
function operationError(value, extraKeys = []) {
|
|
20627
|
-
return
|
|
22001
|
+
return record7(value) && keys3(value, ["message", "checkedAt"], [
|
|
20628
22002
|
"nextRetryAt",
|
|
20629
22003
|
"retryCount",
|
|
20630
22004
|
"accountIdentity",
|
|
@@ -20636,16 +22010,16 @@ function operationError(value, extraKeys = []) {
|
|
|
20636
22010
|
]) && typeof value.message === "string" && time2(value.checkedAt) && optional3(value, "nextRetryAt", time2) && optional3(value, "retryCount", counter) && optional3(value, "accountIdentity", text2) && optional3(value, "tokenHash", digest) && optional3(value, "refreshTokenFingerprint", tokenFingerprintValue) && optional3(value, "status", (entry) => counter(entry) && entry >= 100 && entry <= 599) && optional3(value, "permanent", (entry) => typeof entry === "boolean");
|
|
20637
22011
|
}
|
|
20638
22012
|
function localRefreshError(value) {
|
|
20639
|
-
return operationError(value, ["credentialFingerprint"]) &&
|
|
22013
|
+
return operationError(value, ["credentialFingerprint"]) && record7(value) && optional3(value, "credentialFingerprint", digest);
|
|
20640
22014
|
}
|
|
20641
22015
|
function localValidationRetry(value, observedBinding) {
|
|
20642
|
-
return
|
|
22016
|
+
return record7(value) && keys3(value, ["subject", "checkedAt", "nextRetryAt"]) && observedBinding.kind === "local" && observedBinding.identity !== undefined && isNativeLocalCredentialValidation(value.subject) && value.subject.binding.storageId === observedBinding.storageId && value.subject.binding.rowId === observedBinding.rowId && value.subject.binding.credentialEpoch === observedBinding.credentialEpoch && value.subject.binding.identity === observedBinding.identity && counter(value.checkedAt) && counter(value.nextRetryAt) && value.nextRetryAt >= value.checkedAt;
|
|
20643
22017
|
}
|
|
20644
22018
|
function profile(value) {
|
|
20645
|
-
return
|
|
22019
|
+
return record7(value) && keys3(value, ["tier", "orgType", "checkedAt"], ["accountIdentity", "providerAccountUuid", "tokenFingerprint"]) && text2(value.tier) && text2(value.orgType) && time2(value.checkedAt) && optional3(value, "accountIdentity", text2) && optional3(value, "providerAccountUuid", text2) && optional3(value, "tokenFingerprint", tokenFingerprintValue);
|
|
20646
22020
|
}
|
|
20647
22021
|
function prime(value) {
|
|
20648
|
-
return
|
|
22022
|
+
return record7(value) && keys3(value, ["count", "inputTokens", "outputTokens", "since"]) && counter(value.count) && counter(value.inputTokens) && counter(value.outputTokens) && time2(value.since);
|
|
20649
22023
|
}
|
|
20650
22024
|
var entryKeys = [
|
|
20651
22025
|
"credentialValidation",
|
|
@@ -20670,7 +22044,7 @@ var entryKeys = [
|
|
|
20670
22044
|
"primeAuthLineageRefreshTokenFingerprint"
|
|
20671
22045
|
];
|
|
20672
22046
|
function entry(value, id, storageId) {
|
|
20673
|
-
if (!
|
|
22047
|
+
if (!record7(value) || !keys3(value, ["binding"], entryKeys) || !binding(value.binding) || value.binding.storageId !== storageId || (value.binding.kind === "local" ? value.binding.rowId : value.binding.routeId) !== id)
|
|
20674
22048
|
return false;
|
|
20675
22049
|
const observedBinding = value.binding;
|
|
20676
22050
|
if (!optional3(value, "validationRetry", (retry) => localValidationRetry(retry, observedBinding)))
|
|
@@ -20703,7 +22077,7 @@ function entry(value, id, storageId) {
|
|
|
20703
22077
|
value.lastRefreshError,
|
|
20704
22078
|
value.lastQuotaRefreshError
|
|
20705
22079
|
]) {
|
|
20706
|
-
if (
|
|
22080
|
+
if (record7(observation) && (observation.accountIdentity !== undefined && observation.accountIdentity !== identity2 || observation.providerAccountUuid !== undefined && observation.providerAccountUuid !== identity2))
|
|
20707
22081
|
return false;
|
|
20708
22082
|
}
|
|
20709
22083
|
if (Object.hasOwn(value, "quota")) {
|
|
@@ -20730,7 +22104,7 @@ function entry(value, id, storageId) {
|
|
|
20730
22104
|
return true;
|
|
20731
22105
|
}
|
|
20732
22106
|
function decodeNativeRuntime(value, storageId) {
|
|
20733
|
-
if (!
|
|
22107
|
+
if (!record7(value) || !keys3(value, ["version", "storageId", "accounts"], ["relay", "relayGeneration"]) || value.version !== 1 || !digest(storageId) || value.storageId !== storageId || !record7(value.accounts) || !optional3(value, "relayGeneration", text2) || !optional3(value, "relay", (entry2) => record7(entry2) && keys3(entry2, ["token"]) && typeof entry2.token === "string"))
|
|
20734
22108
|
throw new NativeRuntimeError("invalid-runtime");
|
|
20735
22109
|
const accounts = Object.create(null);
|
|
20736
22110
|
for (const [id, item] of Object.entries(value.accounts)) {
|
|
@@ -20743,7 +22117,7 @@ function decodeNativeRuntime(value, storageId) {
|
|
|
20743
22117
|
storageId,
|
|
20744
22118
|
accounts,
|
|
20745
22119
|
...typeof value.relayGeneration === "string" ? { relayGeneration: value.relayGeneration } : {},
|
|
20746
|
-
...
|
|
22120
|
+
...record7(value.relay) && typeof value.relay.token === "string" ? { relay: { token: value.relay.token } } : {}
|
|
20747
22121
|
};
|
|
20748
22122
|
}
|
|
20749
22123
|
function missing(error) {
|
|
@@ -21018,7 +22392,7 @@ async function writeNativeRuntimeOutcome(path2, storageId, change, hooks, firstI
|
|
|
21018
22392
|
}
|
|
21019
22393
|
}
|
|
21020
22394
|
function dispatchVersion(value) {
|
|
21021
|
-
return
|
|
22395
|
+
return record7(value) && keys3(value, [], ["accessFingerprint", "expires", "lastRefreshedAt"]) && optional3(value, "accessFingerprint", (item) => item === undefined || tokenFingerprintValue(item)) && optional3(value, "expires", (item) => item === undefined || counter(item)) && optional3(value, "lastRefreshedAt", counter);
|
|
21022
22396
|
}
|
|
21023
22397
|
function sameVersion(a, b) {
|
|
21024
22398
|
return ["accessFingerprint", "expires", "lastRefreshedAt"].every((key) => Object.hasOwn(a, key) === Object.hasOwn(b, key) && a[key] === b[key]);
|
|
@@ -21027,7 +22401,7 @@ function captureLocalValidation(paths, observation) {
|
|
|
21027
22401
|
const refuse2 = () => new NativeRuntimeError("publication-refused");
|
|
21028
22402
|
const event = structuredClone(observation);
|
|
21029
22403
|
const context = event.context;
|
|
21030
|
-
if (!["persisted", "validation-observed"].includes(event.status) || event.bootstrap !== "resolved" || !("identity" in event) || !accountUuid(event.identity) || !isNativeLocalPoolBinding(event.binding) || event.binding.storageId !== paths.storageId || event.binding.identity !== undefined && event.binding.identity !== event.identity || !digest(event.credentialFingerprint) || !dispatchVersion(event.credentialVersion) || !context || !
|
|
22404
|
+
if (!["persisted", "validation-observed"].includes(event.status) || event.bootstrap !== "resolved" || !("identity" in event) || !accountUuid(event.identity) || !isNativeLocalPoolBinding(event.binding) || event.binding.storageId !== paths.storageId || event.binding.identity !== undefined && event.binding.identity !== event.identity || !digest(event.credentialFingerprint) || !dispatchVersion(event.credentialVersion) || !context || !record7(context.subject) || !isNativeLocalPoolBinding(context.subject.binding) || !sameLocalBinding(context.subject.binding, event.binding) || context.subject.credentialFingerprint !== event.credentialFingerprint || !dispatchVersion(context.subject.version) || !sameVersion(context.subject.version, event.credentialVersion) || ![
|
|
21031
22405
|
context.refreshErrorClearedAt,
|
|
21032
22406
|
context.quotaErrorClearedAt,
|
|
21033
22407
|
context.quotaErrorGeneration
|
|
@@ -21041,7 +22415,7 @@ function captureLocalValidation(paths, observation) {
|
|
|
21041
22415
|
credentialFingerprint: event.successorFingerprint,
|
|
21042
22416
|
version: event.successorVersion
|
|
21043
22417
|
};
|
|
21044
|
-
if (!isNativeLocalCredentialValidation(proof) || !
|
|
22418
|
+
if (!isNativeLocalCredentialValidation(proof) || !record7(event.committed) || !keys3(event.committed, ["credentialFingerprint", "version"]) || event.committed.credentialFingerprint !== proof.credentialFingerprint || !dispatchVersion(event.committed.version) || !sameVersion(event.committed.version, { ...proof.version }))
|
|
21045
22419
|
throw refuse2();
|
|
21046
22420
|
} else if (event.status === "validation-observed") {
|
|
21047
22421
|
if (event.binding.identity !== event.identity)
|
|
@@ -21180,16 +22554,16 @@ function classifyCapturedLocalFailure(event) {
|
|
|
21180
22554
|
return { kind: "none", reason: "not-a-failure" };
|
|
21181
22555
|
if (event.context === undefined)
|
|
21182
22556
|
return { kind: "none", reason: "no-context" };
|
|
21183
|
-
if (!
|
|
22557
|
+
if (!record7(event.context))
|
|
21184
22558
|
throw new NativeRuntimeError("publication-refused");
|
|
21185
|
-
if (event.status === "failed" && (!
|
|
22559
|
+
if (event.status === "failed" && (!record7(event.failure) || !keys3(event.failure, ["kind", "classification"], ["status", "retryAfter"]) || !text2(event.failure.kind) || !["transient", "invalid-grant", "permanent"].includes(event.failure.classification) || event.failure.status !== undefined && (!counter(event.failure.status) || event.failure.status < 100 || event.failure.status > 599) || event.failure.retryAfter !== undefined && !time2(event.failure.retryAfter) || typeof event.persisted !== "boolean"))
|
|
21186
22560
|
throw new NativeRuntimeError("publication-refused");
|
|
21187
22561
|
if (event.status === "failed" && event.persisted && !event.committed)
|
|
21188
22562
|
return { kind: "none", reason: "missing-committed" };
|
|
21189
22563
|
if (event.bootstrap === "resolved" || event.status === "failed" && (event.failure.kind === "caller-hook" || !event.persisted && !["provider", "validation"].includes(event.failure.kind)))
|
|
21190
22564
|
return { kind: "none", reason: "not-attributable" };
|
|
21191
22565
|
const context = event.context;
|
|
21192
|
-
if (!isNativeLocalPoolBinding(event.binding) || !digest(event.credentialFingerprint) || !dispatchVersion(event.credentialVersion) || !
|
|
22566
|
+
if (!isNativeLocalPoolBinding(event.binding) || !digest(event.credentialFingerprint) || !dispatchVersion(event.credentialVersion) || !record7(context.subject) || !isNativeLocalPoolBinding(context.subject.binding) || !sameLocalBinding(context.subject.binding, event.binding) || context.subject.credentialFingerprint !== event.credentialFingerprint || !dispatchVersion(context.subject.version) || !sameVersion(context.subject.version, event.credentialVersion) || context.runtimeBinding !== null && !isNativeLocalPoolBinding(context.runtimeBinding) || ![
|
|
21193
22567
|
context.refreshErrorClearedAt,
|
|
21194
22568
|
context.quotaErrorClearedAt,
|
|
21195
22569
|
context.quotaErrorGeneration
|
|
@@ -21197,7 +22571,7 @@ function classifyCapturedLocalFailure(event) {
|
|
|
21197
22571
|
throw new NativeRuntimeError("publication-refused");
|
|
21198
22572
|
const saved = event.status === "persisted" || event.persisted;
|
|
21199
22573
|
const committed = event.committed;
|
|
21200
|
-
if (saved && (!
|
|
22574
|
+
if (saved && (!record7(committed) || !keys3(committed, ["credentialFingerprint", "version"]) || !digest(committed.credentialFingerprint) || !completeFailureVersion(committed.version)))
|
|
21201
22575
|
throw new NativeRuntimeError("publication-refused");
|
|
21202
22576
|
if (event.status === "persisted" && (!dispatchVersion(event.successorVersion) || event.successorFingerprint !== committed?.credentialFingerprint || !sameVersion(event.successorVersion, { ...committed?.version })))
|
|
21203
22577
|
throw new NativeRuntimeError("publication-refused");
|
|
@@ -21390,13 +22764,13 @@ class NativeMigrationProjectionError extends Error {
|
|
|
21390
22764
|
function refuse2() {
|
|
21391
22765
|
throw new NativeMigrationProjectionError;
|
|
21392
22766
|
}
|
|
21393
|
-
function
|
|
22767
|
+
function record8(value) {
|
|
21394
22768
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
21395
22769
|
}
|
|
21396
22770
|
function object(value) {
|
|
21397
22771
|
if (value === undefined)
|
|
21398
22772
|
return Object.create(null);
|
|
21399
|
-
if (!
|
|
22773
|
+
if (!record8(value))
|
|
21400
22774
|
refuse2();
|
|
21401
22775
|
return value;
|
|
21402
22776
|
}
|
|
@@ -21446,7 +22820,7 @@ var settingFields = {
|
|
|
21446
22820
|
killswitch: ["enabled", "main", "accounts"]
|
|
21447
22821
|
};
|
|
21448
22822
|
function validateNativeMigrationSettings(settings) {
|
|
21449
|
-
const threshold = (value) =>
|
|
22823
|
+
const threshold = (value) => record8(value) && Object.entries(value).every(([key, amount]) => ["five_hour", "seven_day", "5h", "1w", "scoped"].includes(key) && typeof amount === "number" && Number.isFinite(amount) && amount >= 0 && amount <= 100);
|
|
21450
22824
|
const enums = {
|
|
21451
22825
|
"routing.mode": ["main-first", "fallback-first", "sticky-balanced"],
|
|
21452
22826
|
"routing.maxSameAccountWait": ["0", "15", "max"],
|
|
@@ -21492,7 +22866,7 @@ function validateNativeMigrationSettings(settings) {
|
|
|
21492
22866
|
if (!threshold(value[key]))
|
|
21493
22867
|
refuse2();
|
|
21494
22868
|
} else if (key === "accounts") {
|
|
21495
|
-
if (!
|
|
22869
|
+
if (!record8(value[key]) || !Object.entries(value[key]).every(([route, thresholds]) => text3(route) && threshold(thresholds)))
|
|
21496
22870
|
refuse2();
|
|
21497
22871
|
} else if (typeof value[key] !== "number" || !Number.isFinite(value[key]) || value[key] < 0)
|
|
21498
22872
|
refuse2();
|
|
@@ -21539,7 +22913,7 @@ function runtime(source2, accountIdentity, current) {
|
|
|
21539
22913
|
if (source2.quotaCheckedAt !== undefined)
|
|
21540
22914
|
result.quotaCheckedAt = source2.quotaCheckedAt;
|
|
21541
22915
|
}
|
|
21542
|
-
if (
|
|
22916
|
+
if (record8(source2.profile) && accountIdentity !== undefined && (source2.profile.providerAccountUuid === accountIdentity || source2.profile.accountIdentity === accountIdentity)) {
|
|
21543
22917
|
result.profile = pick(source2.profile, [
|
|
21544
22918
|
"tier",
|
|
21545
22919
|
"orgType",
|
|
@@ -21552,7 +22926,7 @@ function runtime(source2, accountIdentity, current) {
|
|
|
21552
22926
|
for (const field of ["lastRefreshError", "lastQuotaRefreshError"]) {
|
|
21553
22927
|
const error = source2[field];
|
|
21554
22928
|
const clear = result[field === "lastRefreshError" ? "refreshErrorClearedAt" : "quotaErrorClearedAt"];
|
|
21555
|
-
if (!
|
|
22929
|
+
if (!record8(error) || typeof clear === "number" && time3(error.checkedAt) <= clear || error.accountIdentity !== undefined && error.accountIdentity !== accountIdentity)
|
|
21556
22930
|
continue;
|
|
21557
22931
|
const safe = pick(error, [
|
|
21558
22932
|
"checkedAt",
|
|
@@ -21644,7 +23018,7 @@ function projectNativeMigrationSource(input) {
|
|
|
21644
23018
|
authHeader: "x-api-key"
|
|
21645
23019
|
});
|
|
21646
23020
|
}
|
|
21647
|
-
const mainIdentity = custodyPrimary?.accountIdentity ?? (
|
|
23021
|
+
const mainIdentity = custodyPrimary?.accountIdentity ?? (record8(main.profile) && current?.type === "oauth" && (main.profileToken === tokenFingerprint(current.access ?? "") || main.profile.tokenFingerprint === tokenFingerprint(current.access ?? "")) ? identity2(main.profile.providerAccountUuid) : undefined);
|
|
21648
23022
|
const quotaConfig = object(config.quota);
|
|
21649
23023
|
const refreshConfig = object(config.refresh);
|
|
21650
23024
|
const primeConfig = object(config.prime);
|
|
@@ -21856,7 +23230,7 @@ function projectNativeMigrationRuntime(paths, projection, rows, seed) {
|
|
|
21856
23230
|
}
|
|
21857
23231
|
|
|
21858
23232
|
// src/native-vault-seed.ts
|
|
21859
|
-
function
|
|
23233
|
+
function record9(value) {
|
|
21860
23234
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
21861
23235
|
}
|
|
21862
23236
|
async function readNativeVaultLegacyJson(path2) {
|
|
@@ -21896,18 +23270,18 @@ var preferenceFields = {
|
|
|
21896
23270
|
async function readNativeVaultLegacySettings(path2) {
|
|
21897
23271
|
const source2 = await readNativeVaultLegacyJson(path2);
|
|
21898
23272
|
const result = {};
|
|
21899
|
-
if (!
|
|
23273
|
+
if (!record9(source2) || source2.version !== undefined && source2.version !== 1)
|
|
21900
23274
|
return result;
|
|
21901
23275
|
for (const [section, fields2] of Object.entries(preferenceFields)) {
|
|
21902
23276
|
const value = source2[section];
|
|
21903
|
-
if (!
|
|
23277
|
+
if (!record9(value))
|
|
21904
23278
|
continue;
|
|
21905
23279
|
const selected = {};
|
|
21906
23280
|
for (const field of fields2) {
|
|
21907
23281
|
const item = value[field];
|
|
21908
23282
|
if (item === undefined)
|
|
21909
23283
|
continue;
|
|
21910
|
-
if ((field === "minimumRemaining" || section === "killswitch" && field === "main") &&
|
|
23284
|
+
if ((field === "minimumRemaining" || section === "killswitch" && field === "main") && record9(item)) {
|
|
21911
23285
|
const thresholds = {};
|
|
21912
23286
|
for (const name of ["five_hour", "seven_day", "5h", "1w", "scoped"]) {
|
|
21913
23287
|
if (item[name] === undefined)
|
|
@@ -21940,7 +23314,7 @@ function uuid(value) {
|
|
|
21940
23314
|
}
|
|
21941
23315
|
function nativeVaultLegacyRoutes(source2, roster) {
|
|
21942
23316
|
const routes = new Map;
|
|
21943
|
-
if (!
|
|
23317
|
+
if (!record9(source2) || source2.version !== undefined && source2.version !== 1)
|
|
21944
23318
|
return routes;
|
|
21945
23319
|
const verified = new Map;
|
|
21946
23320
|
const ambiguous = new Set;
|
|
@@ -21958,13 +23332,13 @@ function nativeVaultLegacyRoutes(source2, roster) {
|
|
|
21958
23332
|
if (routeId)
|
|
21959
23333
|
routes.set(id2, { routeId, accountIdentity: identity3 });
|
|
21960
23334
|
}
|
|
21961
|
-
const custody =
|
|
21962
|
-
const primary =
|
|
23335
|
+
const custody = record9(source2.claustrum) ? source2.claustrum : undefined;
|
|
23336
|
+
const primary = record9(custody?.primaryAccount) ? custody.primaryAccount : undefined;
|
|
21963
23337
|
const main = uuid(primary?.accountId) ? primary.accountId : source2.mainAccountId;
|
|
21964
23338
|
add("main", main);
|
|
21965
23339
|
add(source2.mainAccountId, main);
|
|
21966
23340
|
for (const row of Array.isArray(source2.accounts) ? source2.accounts : []) {
|
|
21967
|
-
if (
|
|
23341
|
+
if (record9(row) && row.type === "oauth")
|
|
21968
23342
|
add(row.id, row.anthropicAccountUuid);
|
|
21969
23343
|
}
|
|
21970
23344
|
return routes;
|
|
@@ -22146,52 +23520,6 @@ function createQuotaRefusalResponse(reason, timing, _now) {
|
|
|
22146
23520
|
return response;
|
|
22147
23521
|
}
|
|
22148
23522
|
|
|
22149
|
-
// src/session-cache-activity.ts
|
|
22150
|
-
var PROMPT_CACHE_DEFAULT_TTL_MS = 5 * 60000;
|
|
22151
|
-
var PROMPT_CACHE_1H_TTL_MS = 60 * 60000;
|
|
22152
|
-
|
|
22153
|
-
class SessionCacheActivity {
|
|
22154
|
-
maxSessions;
|
|
22155
|
-
entries = new Map;
|
|
22156
|
-
constructor(maxSessions = 4096) {
|
|
22157
|
-
this.maxSessions = maxSessions;
|
|
22158
|
-
}
|
|
22159
|
-
record(sessionId, accountId, ttlMs, lastAcceptedAt = Date.now()) {
|
|
22160
|
-
this.entries.delete(sessionId);
|
|
22161
|
-
this.entries.set(sessionId, {
|
|
22162
|
-
accountId,
|
|
22163
|
-
lastAcceptedAt,
|
|
22164
|
-
ttlMs: ttlMs && Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : PROMPT_CACHE_DEFAULT_TTL_MS
|
|
22165
|
-
});
|
|
22166
|
-
if (this.entries.size > this.maxSessions) {
|
|
22167
|
-
const oldest = this.entries.keys().next().value;
|
|
22168
|
-
if (oldest !== undefined)
|
|
22169
|
-
this.entries.delete(oldest);
|
|
22170
|
-
}
|
|
22171
|
-
}
|
|
22172
|
-
holdUntil(sessionId, accountId, now = Date.now(), maxWait = "15") {
|
|
22173
|
-
if (!sessionId)
|
|
22174
|
-
return;
|
|
22175
|
-
const activity = this.entries.get(sessionId);
|
|
22176
|
-
if (!activity || activity.accountId !== accountId)
|
|
22177
|
-
return;
|
|
22178
|
-
return Math.min(activity.lastAcceptedAt + activity.ttlMs, maxWait === "max" ? Infinity : now + Number(maxWait) * 60000);
|
|
22179
|
-
}
|
|
22180
|
-
recordPrewarm(sessionId, accountId, acceptedAt = Date.now()) {
|
|
22181
|
-
const activity = this.entries.get(sessionId);
|
|
22182
|
-
if (activity && activity.accountId !== accountId)
|
|
22183
|
-
return;
|
|
22184
|
-
this.record(sessionId, accountId, PROMPT_CACHE_1H_TTL_MS, acceptedAt);
|
|
22185
|
-
}
|
|
22186
|
-
forget(sessionId) {
|
|
22187
|
-
this.entries.delete(sessionId);
|
|
22188
|
-
}
|
|
22189
|
-
ttlMs(sessionId) {
|
|
22190
|
-
return sessionId && this.entries.get(sessionId)?.ttlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
|
|
22191
|
-
}
|
|
22192
|
-
}
|
|
22193
|
-
var sessionCacheActivity = new SessionCacheActivity;
|
|
22194
|
-
|
|
22195
23523
|
// src/sticky-routing.ts
|
|
22196
23524
|
var STICKY_ROUTING_MAIN_ACCOUNT_ID = "main";
|
|
22197
23525
|
var STICKY_ROUTING_ASSIGNMENT_TTL_MS = 7 * 24 * 60 * 60000;
|
|
@@ -23539,15 +24867,15 @@ async function readStateLayoutRecord(sub) {
|
|
|
23539
24867
|
} catch {
|
|
23540
24868
|
throw new StateLayoutFileError("invalid", path2);
|
|
23541
24869
|
}
|
|
23542
|
-
const
|
|
23543
|
-
if (!
|
|
24870
|
+
const record10 = parseRecord(value);
|
|
24871
|
+
if (!record10)
|
|
23544
24872
|
throw new StateLayoutFileError("invalid", path2);
|
|
23545
|
-
return
|
|
24873
|
+
return record10;
|
|
23546
24874
|
}
|
|
23547
|
-
async function publishStateLayoutRecord(
|
|
23548
|
-
const path2 = layoutRecordPath(
|
|
23549
|
-
const stage = `${path2}.${
|
|
23550
|
-
await createOwnerOnlyFile(fs3, stage, Buffer.from(`${JSON.stringify(
|
|
24875
|
+
async function publishStateLayoutRecord(record10, guard, fs3) {
|
|
24876
|
+
const path2 = layoutRecordPath(record10.sub);
|
|
24877
|
+
const stage = `${path2}.${record10.attempt}.${randomUUID13()}.tmp`;
|
|
24878
|
+
await createOwnerOnlyFile(fs3, stage, Buffer.from(`${JSON.stringify(record10, null, 2)}
|
|
23551
24879
|
`, "utf8"));
|
|
23552
24880
|
try {
|
|
23553
24881
|
const outcome = await publishOwned({ kind: "rename", from: stage, to: path2 }, guard, fs3);
|
|
@@ -23557,7 +24885,7 @@ async function publishStateLayoutRecord(record8, guard, fs3) {
|
|
|
23557
24885
|
await unlink6(stage).catch(() => {});
|
|
23558
24886
|
throw error;
|
|
23559
24887
|
}
|
|
23560
|
-
await fs3.syncDirectory(
|
|
24888
|
+
await fs3.syncDirectory(record10.sub);
|
|
23561
24889
|
}
|
|
23562
24890
|
function isLayoutRecordStage(name, attempt) {
|
|
23563
24891
|
const prefix = `${STATE_HOME_FILE_NAMES.layoutMarker}.`;
|
|
@@ -23587,14 +24915,14 @@ var METADATA_ROLES = [
|
|
|
23587
24915
|
async function exists(path2) {
|
|
23588
24916
|
return await identityOf(path2) !== "absent";
|
|
23589
24917
|
}
|
|
23590
|
-
async function reappearedMetadataFiles(
|
|
24918
|
+
async function reappearedMetadataFiles(record10) {
|
|
23591
24919
|
const found = [];
|
|
23592
|
-
for (const file of
|
|
24920
|
+
for (const file of record10.files) {
|
|
23593
24921
|
if (!METADATA_ROLES.includes(file.role))
|
|
23594
24922
|
continue;
|
|
23595
|
-
if (
|
|
24923
|
+
if (record10.cleanup === "pending" && file.sha256 !== null)
|
|
23596
24924
|
continue;
|
|
23597
|
-
if (
|
|
24925
|
+
if (record10.kept?.includes(file.from))
|
|
23598
24926
|
continue;
|
|
23599
24927
|
if (await exists(file.from))
|
|
23600
24928
|
found.push(file.from);
|
|
@@ -23602,18 +24930,18 @@ async function reappearedMetadataFiles(record8) {
|
|
|
23602
24930
|
return found;
|
|
23603
24931
|
}
|
|
23604
24932
|
var warnedReappeared = new Set;
|
|
23605
|
-
async function warnReappearedMetadata(
|
|
24933
|
+
async function warnReappearedMetadata(record10) {
|
|
23606
24934
|
let found;
|
|
23607
24935
|
try {
|
|
23608
|
-
found = await reappearedMetadataFiles(
|
|
24936
|
+
found = await reappearedMetadataFiles(record10);
|
|
23609
24937
|
} catch (error) {
|
|
23610
|
-
throw guardIoFailure(
|
|
24938
|
+
throw guardIoFailure(record10.sub, error);
|
|
23611
24939
|
}
|
|
23612
24940
|
for (const path2 of found) {
|
|
23613
24941
|
if (warnedReappeared.has(path2))
|
|
23614
24942
|
continue;
|
|
23615
24943
|
warnedReappeared.add(path2);
|
|
23616
|
-
logger2.warn("state-layout", `anthropic-auth found ${path2} in the config folder after moving its state to ${
|
|
24944
|
+
logger2.warn("state-layout", `anthropic-auth found ${path2} in the config folder after moving its state to ${record10.sub}. It holds no credentials and is not used; delete it when convenient.`, { path: path2 });
|
|
23617
24945
|
}
|
|
23618
24946
|
}
|
|
23619
24947
|
async function identityOf(path2) {
|
|
@@ -23635,27 +24963,27 @@ async function observe(path2) {
|
|
|
23635
24963
|
throw error;
|
|
23636
24964
|
}
|
|
23637
24965
|
}
|
|
23638
|
-
function stateHomeConflictFrom(
|
|
23639
|
-
if (
|
|
23640
|
-
return new StateLayoutRefusalError("restore-unfinished", `anthropic-auth state for ${
|
|
23641
|
-
if (
|
|
23642
|
-
const first =
|
|
24966
|
+
function stateHomeConflictFrom(record10, files, observed) {
|
|
24967
|
+
if (record10.phase !== "committed")
|
|
24968
|
+
return new StateLayoutRefusalError("restore-unfinished", `anthropic-auth state for ${record10.oldDir} is being restored to the old folder, so this process stopped using ${files.sub}. Restart OpenCode once the restore has finished.`, [files.sub]);
|
|
24969
|
+
if (record10.cleanup === "conflict") {
|
|
24970
|
+
const first = record10.conflict?.[0];
|
|
23643
24971
|
return stateLayoutConflict(first?.old ?? files.oldPoolState, first?.new ?? files.newPoolState);
|
|
23644
24972
|
}
|
|
23645
24973
|
if (observed.oldJournal)
|
|
23646
24974
|
return stateLayoutConflict(files.oldJournal, files.newJournal);
|
|
23647
|
-
const recorded = (role) =>
|
|
23648
|
-
const second = (seen, sha256) => seen !== "absent" && (
|
|
24975
|
+
const recorded = (role) => record10.files.find((file) => file.role === role)?.sha256 ?? null;
|
|
24976
|
+
const second = (seen, sha256) => seen !== "absent" && (record10.cleanup !== "pending" || sha256 === null || seen !== sha256);
|
|
23649
24977
|
if (second(observed.oldPoolState, recorded("localPoolState")))
|
|
23650
24978
|
return stateLayoutConflict(files.oldPoolState, files.newPoolState);
|
|
23651
|
-
if (
|
|
23652
|
-
return stateLayoutConflict(movingJournalPath(files.oldJournal,
|
|
24979
|
+
if (record10.cleanup === "pending" && second(observed.movingJournal, recorded("journal")))
|
|
24980
|
+
return stateLayoutConflict(movingJournalPath(files.oldJournal, record10.attempt), files.newJournal);
|
|
23653
24981
|
return;
|
|
23654
24982
|
}
|
|
23655
24983
|
async function evaluate(files) {
|
|
23656
|
-
let
|
|
24984
|
+
let record10;
|
|
23657
24985
|
try {
|
|
23658
|
-
|
|
24986
|
+
record10 = await readStateLayoutRecord(files.sub);
|
|
23659
24987
|
} catch (error) {
|
|
23660
24988
|
return {
|
|
23661
24989
|
refusal: markerRefusal(files.sub, error),
|
|
@@ -23664,14 +24992,14 @@ async function evaluate(files) {
|
|
|
23664
24992
|
movingIdentity: undefined
|
|
23665
24993
|
};
|
|
23666
24994
|
}
|
|
23667
|
-
if (!
|
|
24995
|
+
if (!record10)
|
|
23668
24996
|
return {
|
|
23669
24997
|
refusal: markerRefusal(files.sub),
|
|
23670
|
-
record:
|
|
24998
|
+
record: record10,
|
|
23671
24999
|
moving: undefined,
|
|
23672
25000
|
movingIdentity: undefined
|
|
23673
25001
|
};
|
|
23674
|
-
const moving = movingJournalPath(files.oldJournal,
|
|
25002
|
+
const moving = movingJournalPath(files.oldJournal, record10.attempt);
|
|
23675
25003
|
const movingIdentity = await identityOf(moving);
|
|
23676
25004
|
const oldJournal = await identityOf(files.oldJournal) !== "absent";
|
|
23677
25005
|
const [oldPoolState, movingJournal] = await Promise.all([
|
|
@@ -23679,12 +25007,12 @@ async function evaluate(files) {
|
|
|
23679
25007
|
observe(moving)
|
|
23680
25008
|
]);
|
|
23681
25009
|
return {
|
|
23682
|
-
refusal: stateHomeConflictFrom(
|
|
25010
|
+
refusal: stateHomeConflictFrom(record10, files, {
|
|
23683
25011
|
oldJournal,
|
|
23684
25012
|
oldPoolState,
|
|
23685
25013
|
movingJournal
|
|
23686
25014
|
}),
|
|
23687
|
-
record:
|
|
25015
|
+
record: record10,
|
|
23688
25016
|
moving,
|
|
23689
25017
|
movingIdentity
|
|
23690
25018
|
};
|
|
@@ -23709,7 +25037,7 @@ var probe;
|
|
|
23709
25037
|
function createStateHomeServingGuard(files) {
|
|
23710
25038
|
const marker = join19(files.sub, STATE_HOME_FILE_NAMES.layoutMarker);
|
|
23711
25039
|
const dataset = JSON.stringify(files);
|
|
23712
|
-
function
|
|
25040
|
+
function report2(refusal2) {
|
|
23713
25041
|
if (refusal2 && !reported.has(refusal2.message)) {
|
|
23714
25042
|
reported.add(refusal2.message);
|
|
23715
25043
|
logger2.error("state-layout", refusal2.message, {
|
|
@@ -23721,9 +25049,9 @@ function createStateHomeServingGuard(files) {
|
|
|
23721
25049
|
}
|
|
23722
25050
|
async function check() {
|
|
23723
25051
|
try {
|
|
23724
|
-
return
|
|
25052
|
+
return report2(await observeDataset());
|
|
23725
25053
|
} catch (error) {
|
|
23726
|
-
return
|
|
25054
|
+
return report2(guardIoFailure(files.sub, error));
|
|
23727
25055
|
}
|
|
23728
25056
|
}
|
|
23729
25057
|
async function observeDataset() {
|
|
@@ -24078,7 +25406,7 @@ async function assertUnmanagedInjectedPaths(paths) {
|
|
|
24078
25406
|
var instance = randomUUID14();
|
|
24079
25407
|
var ownIncarnation;
|
|
24080
25408
|
var published = new Set;
|
|
24081
|
-
var
|
|
25409
|
+
var warned2 = new Set;
|
|
24082
25410
|
function registrationKey(holderFile, entry2) {
|
|
24083
25411
|
return JSON.stringify([holderFile, entry2.kind, entry2.role, entry2.files]);
|
|
24084
25412
|
}
|
|
@@ -24215,9 +25543,9 @@ function deferNativePoolHolderRegistration(options, failure) {
|
|
|
24215
25543
|
}, options);
|
|
24216
25544
|
}
|
|
24217
25545
|
function warnRegistrationFailure(dir, error) {
|
|
24218
|
-
if (
|
|
25546
|
+
if (warned2.has(dir))
|
|
24219
25547
|
return;
|
|
24220
|
-
|
|
25548
|
+
warned2.add(dir);
|
|
24221
25549
|
logger2.warn("state-layout", `anthropic-auth could not record that it is using ${dir}; if a newer version moves these files while this process runs, this process will stop and ask for a restart`, {
|
|
24222
25550
|
code: error instanceof HolderRegistrationError ? error.code : error instanceof LockContentionError ? "lock-timeout" : error?.code ?? "unknown"
|
|
24223
25551
|
});
|
|
@@ -24284,7 +25612,7 @@ function retryInBackground(attempt, options) {
|
|
|
24284
25612
|
}
|
|
24285
25613
|
function resetNativeHolderRegistryForTests() {
|
|
24286
25614
|
published.clear();
|
|
24287
|
-
|
|
25615
|
+
warned2.clear();
|
|
24288
25616
|
ownIncarnation = undefined;
|
|
24289
25617
|
}
|
|
24290
25618
|
|
|
@@ -24313,22 +25641,22 @@ var CACHE_KEEP_STOP_REASONS = [
|
|
|
24313
25641
|
function normalizeSession(value) {
|
|
24314
25642
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
24315
25643
|
return;
|
|
24316
|
-
const
|
|
24317
|
-
if (typeof
|
|
25644
|
+
const record10 = value;
|
|
25645
|
+
if (typeof record10.id !== "string" || record10.id.length === 0 || typeof record10.cacheExpiresAt !== "number" || !Number.isFinite(record10.cacheExpiresAt) || typeof record10.nextPrewarmAt !== "number" || !Number.isFinite(record10.nextPrewarmAt)) {
|
|
24318
25646
|
return;
|
|
24319
25647
|
}
|
|
24320
25648
|
return {
|
|
24321
|
-
id:
|
|
24322
|
-
cacheExpiresAt:
|
|
24323
|
-
nextPrewarmAt:
|
|
24324
|
-
...typeof
|
|
24325
|
-
...typeof
|
|
24326
|
-
lastTouchAt:
|
|
25649
|
+
id: record10.id,
|
|
25650
|
+
cacheExpiresAt: record10.cacheExpiresAt,
|
|
25651
|
+
nextPrewarmAt: record10.nextPrewarmAt,
|
|
25652
|
+
...typeof record10.ttlMs === "number" && Number.isFinite(record10.ttlMs) && record10.ttlMs > 0 && { ttlMs: record10.ttlMs },
|
|
25653
|
+
...typeof record10.lastTouchAt === "number" && Number.isFinite(record10.lastTouchAt) && {
|
|
25654
|
+
lastTouchAt: record10.lastTouchAt
|
|
24327
25655
|
},
|
|
24328
|
-
...(
|
|
24329
|
-
lastTouchKind:
|
|
25656
|
+
...(record10.lastTouchKind === "response" || record10.lastTouchKind === "warm") && {
|
|
25657
|
+
lastTouchKind: record10.lastTouchKind
|
|
24330
25658
|
},
|
|
24331
|
-
...normalizeStopped(
|
|
25659
|
+
...normalizeStopped(record10.warmStopped)
|
|
24332
25660
|
};
|
|
24333
25661
|
}
|
|
24334
25662
|
function normalizeStopped(value) {
|
|
@@ -24347,21 +25675,21 @@ function normalizeStopped(value) {
|
|
|
24347
25675
|
function normalizeRecord(value) {
|
|
24348
25676
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
24349
25677
|
return;
|
|
24350
|
-
const
|
|
24351
|
-
if (
|
|
25678
|
+
const record10 = value;
|
|
25679
|
+
if (record10.version !== 1 || typeof record10.updatedAt !== "number" || !Number.isFinite(record10.updatedAt) || !Array.isArray(record10.sessions)) {
|
|
24352
25680
|
return;
|
|
24353
25681
|
}
|
|
24354
25682
|
return {
|
|
24355
25683
|
version: 1,
|
|
24356
|
-
updatedAt:
|
|
24357
|
-
sessions:
|
|
25684
|
+
updatedAt: record10.updatedAt,
|
|
25685
|
+
sessions: record10.sessions.flatMap((session) => {
|
|
24358
25686
|
const normalized = normalizeSession(session);
|
|
24359
25687
|
return normalized ? [normalized] : [];
|
|
24360
25688
|
})
|
|
24361
25689
|
};
|
|
24362
25690
|
}
|
|
24363
|
-
function isExpiredRecord(
|
|
24364
|
-
return
|
|
25691
|
+
function isExpiredRecord(record10, now, leaseMs) {
|
|
25692
|
+
return record10.updatedAt <= now && now - record10.updatedAt > leaseMs;
|
|
24365
25693
|
}
|
|
24366
25694
|
function getLegacyCacheKeepRegistryDirectory(scope) {
|
|
24367
25695
|
return join21(tmpdir6(), "opencode-anthropic-auth", "cachekeep-sessions", scope);
|
|
@@ -24396,7 +25724,7 @@ class CacheKeepSessionRegistry {
|
|
|
24396
25724
|
this.writeChain = this.writeChain.catch(() => {}).then(async () => {
|
|
24397
25725
|
const now = this.options.now?.() ?? Date.now();
|
|
24398
25726
|
const leaseMs = this.options.leaseMs ?? CACHE_KEEP_REGISTRY_LEASE_MS;
|
|
24399
|
-
const
|
|
25727
|
+
const record10 = {
|
|
24400
25728
|
version: 1,
|
|
24401
25729
|
updatedAt: now,
|
|
24402
25730
|
sessions: snapshot,
|
|
@@ -24416,7 +25744,7 @@ class CacheKeepSessionRegistry {
|
|
|
24416
25744
|
throw new Error("Unsafe CacheKeep registry directory");
|
|
24417
25745
|
const tempPath = `${filePath}.${randomUUID15()}.tmp`;
|
|
24418
25746
|
try {
|
|
24419
|
-
const bytes = `${JSON.stringify(
|
|
25747
|
+
const bytes = `${JSON.stringify(record10)}
|
|
24420
25748
|
`;
|
|
24421
25749
|
if (!await createWindowsOwnerOnly(tempPath, bytes, this.options.ownerOnly))
|
|
24422
25750
|
await writeFile4(tempPath, bytes, { flag: "wx", mode: 384 });
|
|
@@ -24445,11 +25773,11 @@ class CacheKeepSessionRegistry {
|
|
|
24445
25773
|
}
|
|
24446
25774
|
}));
|
|
24447
25775
|
const sessions = new Map;
|
|
24448
|
-
for (const
|
|
24449
|
-
if (!
|
|
25776
|
+
for (const record10 of records) {
|
|
25777
|
+
if (!record10 || now - record10.updatedAt > leaseMs || record10.updatedAt > now) {
|
|
24450
25778
|
continue;
|
|
24451
25779
|
}
|
|
24452
|
-
for (const session of
|
|
25780
|
+
for (const session of record10.sessions) {
|
|
24453
25781
|
const existing = sessions.get(session.id);
|
|
24454
25782
|
if (!existing || session.cacheExpiresAt > existing.cacheExpiresAt) {
|
|
24455
25783
|
sessions.set(session.id, session);
|
|
@@ -24477,13 +25805,13 @@ class CacheKeepSessionRegistry {
|
|
|
24477
25805
|
}
|
|
24478
25806
|
}))).flat();
|
|
24479
25807
|
}
|
|
24480
|
-
async mayRemove(recordPath,
|
|
24481
|
-
if (!isExpiredRecord(
|
|
25808
|
+
async mayRemove(recordPath, record10, now, leaseMs) {
|
|
25809
|
+
if (!isExpiredRecord(record10, now, leaseMs))
|
|
24482
25810
|
return false;
|
|
24483
25811
|
const pid = Number(/(?:^|[/\\])(\d+)-[^/\\]+\.json(?:\..+\.sweep)?$/.exec(recordPath)?.[1]);
|
|
24484
25812
|
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
24485
25813
|
return false;
|
|
24486
|
-
return !await holderEntryIsLive({ pid, incarnation: null, registeredAt:
|
|
25814
|
+
return !await holderEntryIsLive({ pid, incarnation: null, registeredAt: record10.updatedAt }, this.options.liveness);
|
|
24487
25815
|
}
|
|
24488
25816
|
async sweepExpiredRecords(now, leaseMs) {
|
|
24489
25817
|
if (this.lastSweepAt !== undefined && now - this.lastSweepAt < leaseMs) {
|
|
@@ -24509,12 +25837,12 @@ class CacheKeepSessionRegistry {
|
|
|
24509
25837
|
return;
|
|
24510
25838
|
}
|
|
24511
25839
|
let raw;
|
|
24512
|
-
let
|
|
25840
|
+
let record10;
|
|
24513
25841
|
try {
|
|
24514
25842
|
raw = await readFile12(sweptPath, "utf8");
|
|
24515
|
-
|
|
25843
|
+
record10 = normalizeRecord(JSON.parse(raw));
|
|
24516
25844
|
} catch {}
|
|
24517
|
-
if (
|
|
25845
|
+
if (record10 && await this.mayRemove(recordPath, record10, now, leaseMs)) {
|
|
24518
25846
|
try {
|
|
24519
25847
|
await rm7(sweptPath, { force: true });
|
|
24520
25848
|
} catch {}
|
|
@@ -24575,7 +25903,7 @@ function cacheKeepStoreDirectory(storageId, root = getHostDataHome(), host) {
|
|
|
24575
25903
|
function legacyCacheKeepStoreDirectory(storageId, root = tmpdir7()) {
|
|
24576
25904
|
return join22(root, `cortexkit-anthropic-auth-cachekeep-${hash3(storageId).slice(0, 16)}`);
|
|
24577
25905
|
}
|
|
24578
|
-
function
|
|
25906
|
+
function record10(target, pluginVersion) {
|
|
24579
25907
|
return {
|
|
24580
25908
|
v: RECORD_FORMAT_VERSION,
|
|
24581
25909
|
pluginVersion,
|
|
@@ -24588,7 +25916,22 @@ function record8(target, pluginVersion) {
|
|
|
24588
25916
|
isSubagent: target.isSubagent,
|
|
24589
25917
|
ttlMs: target.ttlMs,
|
|
24590
25918
|
lastTouchAt: target.lastTouchAt,
|
|
24591
|
-
lastTouchKind: target.lastTouchKind
|
|
25919
|
+
lastTouchKind: target.lastTouchKind,
|
|
25920
|
+
...target.policyState && {
|
|
25921
|
+
policyState: {
|
|
25922
|
+
ownerSessionId: target.policyState.ownerSessionId,
|
|
25923
|
+
planned: target.policyState.planned,
|
|
25924
|
+
lastRealRequestAt: target.policyState.lastRealRequestAt,
|
|
25925
|
+
lastWarmAt: target.policyState.lastWarmAt,
|
|
25926
|
+
warmsSinceLastRealRequest: target.policyState.warmsSinceLastRealRequest,
|
|
25927
|
+
warmCostSoFar: target.policyState.warmCostSoFar,
|
|
25928
|
+
pendingWarmCost: target.policyState.pendingWarmCost,
|
|
25929
|
+
prefixTokens: target.policyState.prefixTokens,
|
|
25930
|
+
inputTokens: target.policyState.inputTokens,
|
|
25931
|
+
hasWarmed: target.policyState.hasWarmed,
|
|
25932
|
+
needsRealRequest: target.policyState.needsRealRequest
|
|
25933
|
+
}
|
|
25934
|
+
}
|
|
24592
25935
|
};
|
|
24593
25936
|
}
|
|
24594
25937
|
function sanitizedBody(text5) {
|
|
@@ -24613,6 +25956,9 @@ function invalidReason(value, name, now) {
|
|
|
24613
25956
|
return "invalid";
|
|
24614
25957
|
if (value.cacheExpiresAt <= now)
|
|
24615
25958
|
return "expired";
|
|
25959
|
+
const state = value.policyState;
|
|
25960
|
+
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))))
|
|
25961
|
+
return "invalid";
|
|
24616
25962
|
if (sanitizedBody(value.bodyText) !== value.bodyText)
|
|
24617
25963
|
return "invalid";
|
|
24618
25964
|
}
|
|
@@ -24621,6 +25967,9 @@ class CacheKeepStore {
|
|
|
24621
25967
|
options;
|
|
24622
25968
|
directory;
|
|
24623
25969
|
disabled = false;
|
|
25970
|
+
memoryOnly = false;
|
|
25971
|
+
persistenceEnabled = false;
|
|
25972
|
+
writeWarning = false;
|
|
24624
25973
|
legacyLoadAttempted = false;
|
|
24625
25974
|
chain = Promise.resolve();
|
|
24626
25975
|
pending = new Map;
|
|
@@ -24632,10 +25981,11 @@ class CacheKeepStore {
|
|
|
24632
25981
|
this.directory = cacheKeepStoreDirectory(options.storageId, options.root, options.host);
|
|
24633
25982
|
this.chain = previous?.drain() ?? Promise.resolve();
|
|
24634
25983
|
}
|
|
24635
|
-
refuse() {
|
|
25984
|
+
refuse(memoryOnly = false) {
|
|
24636
25985
|
if (this.disabled)
|
|
24637
25986
|
return;
|
|
24638
25987
|
this.disabled = true;
|
|
25988
|
+
this.memoryOnly = memoryOnly;
|
|
24639
25989
|
for (const timer of this.timers.values())
|
|
24640
25990
|
(this.options.clearTimeoutImpl ?? clearTimeout)(timer);
|
|
24641
25991
|
this.timers.clear();
|
|
@@ -24644,6 +25994,12 @@ class CacheKeepStore {
|
|
|
24644
25994
|
this.lastWrite.clear();
|
|
24645
25995
|
logger2.warn("cachekeep", "restart storage unavailable; retaining sessions in memory only");
|
|
24646
25996
|
}
|
|
25997
|
+
writeFailed() {
|
|
25998
|
+
if (this.writeWarning)
|
|
25999
|
+
return;
|
|
26000
|
+
this.writeWarning = true;
|
|
26001
|
+
logger2.warn("cachekeep", "restart write failed; persistent warm awaits a durable reservation");
|
|
26002
|
+
}
|
|
24647
26003
|
async directoryReady(directory = this.directory) {
|
|
24648
26004
|
if (this.disabled)
|
|
24649
26005
|
return false;
|
|
@@ -24659,9 +26015,13 @@ class CacheKeepStore {
|
|
|
24659
26015
|
const stat11 = await lstat14(directory);
|
|
24660
26016
|
if (!stat11.isDirectory() || stat11.isSymbolicLink() || !await isOwnerOnly(directory, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 448, this.options.ownerOnly))
|
|
24661
26017
|
throw new Error("Unsafe restart directory");
|
|
26018
|
+
this.persistenceEnabled = true;
|
|
24662
26019
|
return true;
|
|
24663
26020
|
} catch {
|
|
24664
|
-
this.
|
|
26021
|
+
if (!this.persistenceEnabled)
|
|
26022
|
+
this.refuse(true);
|
|
26023
|
+
else
|
|
26024
|
+
this.writeFailed();
|
|
24665
26025
|
return false;
|
|
24666
26026
|
}
|
|
24667
26027
|
}
|
|
@@ -24669,7 +26029,7 @@ class CacheKeepStore {
|
|
|
24669
26029
|
this.chain = this.chain.then(async () => {
|
|
24670
26030
|
if (await this.directoryReady())
|
|
24671
26031
|
await action();
|
|
24672
|
-
}).catch(() => this.
|
|
26032
|
+
}).catch(() => this.writeFailed());
|
|
24673
26033
|
}
|
|
24674
26034
|
async load(now, accept, claim) {
|
|
24675
26035
|
await this.chain;
|
|
@@ -24724,8 +26084,8 @@ class CacheKeepStore {
|
|
|
24724
26084
|
});
|
|
24725
26085
|
reason = "invalid";
|
|
24726
26086
|
const entry2 = JSON.parse(raw.toString("utf8"));
|
|
24727
|
-
const
|
|
24728
|
-
const accepted =
|
|
26087
|
+
const invalid2 = invalidReason(entry2, name, now);
|
|
26088
|
+
const accepted = invalid2 ?? accept(entry2);
|
|
24729
26089
|
if (accepted !== true && accepted !== undefined) {
|
|
24730
26090
|
reason = accepted || "invalid";
|
|
24731
26091
|
throw new Error("Stale restart file");
|
|
@@ -24766,9 +26126,9 @@ class CacheKeepStore {
|
|
|
24766
26126
|
changed(target) {
|
|
24767
26127
|
if (this.disabled)
|
|
24768
26128
|
return;
|
|
24769
|
-
const entry2 =
|
|
26129
|
+
const entry2 = record10(target, this.options.pluginVersion);
|
|
24770
26130
|
const previous = this.latest.get(entry2.id);
|
|
24771
|
-
if (previous && previous.bodyText === entry2.bodyText && previous.url === entry2.url && previous.oauthAccountIdentity === entry2.oauthAccountIdentity && previous.cacheExpiresAt === entry2.cacheExpiresAt && previous.nextPrewarmAt === entry2.nextPrewarmAt && previous.ttlMs === entry2.ttlMs && previous.lastTouchAt === entry2.lastTouchAt && previous.lastTouchKind === entry2.lastTouchKind && previous.isSubagent === entry2.isSubagent)
|
|
26131
|
+
if (previous && previous.bodyText === entry2.bodyText && previous.url === entry2.url && previous.oauthAccountIdentity === entry2.oauthAccountIdentity && previous.cacheExpiresAt === entry2.cacheExpiresAt && previous.nextPrewarmAt === entry2.nextPrewarmAt && previous.ttlMs === entry2.ttlMs && previous.lastTouchAt === entry2.lastTouchAt && previous.lastTouchKind === entry2.lastTouchKind && JSON.stringify(previous.policyState) === JSON.stringify(entry2.policyState) && previous.isSubagent === entry2.isSubagent)
|
|
24772
26132
|
return;
|
|
24773
26133
|
this.latest.set(entry2.id, entry2);
|
|
24774
26134
|
this.pending.set(entry2.id, entry2);
|
|
@@ -24792,6 +26152,27 @@ class CacheKeepStore {
|
|
|
24792
26152
|
this.enqueue(() => this.writeEntry(entry2));
|
|
24793
26153
|
return this.chain;
|
|
24794
26154
|
}
|
|
26155
|
+
async reserveWarm(target) {
|
|
26156
|
+
if (this.disabled)
|
|
26157
|
+
return this.memoryOnly;
|
|
26158
|
+
const entry2 = record10(target, this.options.pluginVersion);
|
|
26159
|
+
const timer = this.timers.get(entry2.id);
|
|
26160
|
+
if (timer)
|
|
26161
|
+
(this.options.clearTimeoutImpl ?? clearTimeout)(timer);
|
|
26162
|
+
this.timers.delete(entry2.id);
|
|
26163
|
+
this.pending.delete(entry2.id);
|
|
26164
|
+
this.latest.set(entry2.id, entry2);
|
|
26165
|
+
this.lastWrite.set(entry2.id, this.options.now?.() ?? Date.now());
|
|
26166
|
+
let committed = false;
|
|
26167
|
+
this.chain = this.chain.then(async () => {
|
|
26168
|
+
if (!await this.directoryReady())
|
|
26169
|
+
return;
|
|
26170
|
+
await this.writeEntry(entry2);
|
|
26171
|
+
committed = true;
|
|
26172
|
+
}).catch(() => this.writeFailed());
|
|
26173
|
+
await this.chain;
|
|
26174
|
+
return committed || this.memoryOnly;
|
|
26175
|
+
}
|
|
24795
26176
|
async writeEntry(entry2) {
|
|
24796
26177
|
const path2 = join22(this.directory, `${hash3(entry2.id)}.json.gz`);
|
|
24797
26178
|
const temp = `${path2}.${randomUUID16()}.tmp`;
|
|
@@ -28931,13 +30312,13 @@ var policyKeys = ["checkedAt", "nextRetryAt", "retryCount"];
|
|
|
28931
30312
|
function invalidOption(key) {
|
|
28932
30313
|
return new TypeError(`Native local credential service option ${key} is invalid`);
|
|
28933
30314
|
}
|
|
28934
|
-
function plainDescriptors(value,
|
|
30315
|
+
function plainDescriptors(value, allowed3) {
|
|
28935
30316
|
if (value === null || typeof value !== "object" || utilTypes6.isProxy(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
|
|
28936
30317
|
return;
|
|
28937
30318
|
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
28938
30319
|
for (const key of Reflect.ownKeys(descriptors)) {
|
|
28939
30320
|
const descriptor = descriptors[key];
|
|
28940
|
-
if (typeof key !== "string" || !
|
|
30321
|
+
if (typeof key !== "string" || !allowed3.includes(key) || !descriptor || !Object.hasOwn(descriptor, "value"))
|
|
28941
30322
|
return;
|
|
28942
30323
|
}
|
|
28943
30324
|
return descriptors;
|
|
@@ -29503,7 +30884,7 @@ import { randomUUID as randomUUID18 } from "node:crypto";
|
|
|
29503
30884
|
import { SubcClient as SubcClient2 } from "@cortexkit/subc-client";
|
|
29504
30885
|
|
|
29505
30886
|
// src/insula-quota.ts
|
|
29506
|
-
function
|
|
30887
|
+
function record11(value) {
|
|
29507
30888
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
29508
30889
|
}
|
|
29509
30890
|
function text5(value) {
|
|
@@ -29513,7 +30894,7 @@ function clampPercent3(value) {
|
|
|
29513
30894
|
return Math.min(100, Math.max(0, value));
|
|
29514
30895
|
}
|
|
29515
30896
|
function windowReading(window2, checkedAt, expected) {
|
|
29516
|
-
if (!
|
|
30897
|
+
if (!record11(window2))
|
|
29517
30898
|
return;
|
|
29518
30899
|
const usedPercent = window2.usedPercent;
|
|
29519
30900
|
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent))
|
|
@@ -29537,7 +30918,7 @@ function scopedReadings(windows, checkedAt) {
|
|
|
29537
30918
|
const seen = new Set;
|
|
29538
30919
|
const scoped = [];
|
|
29539
30920
|
for (const candidate of windows) {
|
|
29540
|
-
if (!
|
|
30921
|
+
if (!record11(candidate))
|
|
29541
30922
|
continue;
|
|
29542
30923
|
const identity3 = text5(candidate.id);
|
|
29543
30924
|
if (!identity3)
|
|
@@ -29563,7 +30944,7 @@ function scopedReadings(windows, checkedAt) {
|
|
|
29563
30944
|
return scoped;
|
|
29564
30945
|
}
|
|
29565
30946
|
function money2(value) {
|
|
29566
|
-
if (!
|
|
30947
|
+
if (!record11(value) || typeof value.minor !== "number" || !Number.isSafeInteger(value.minor) || value.minor < 0)
|
|
29567
30948
|
return null;
|
|
29568
30949
|
const exponent = value.exponent ?? 2;
|
|
29569
30950
|
if (typeof exponent !== "number" || !Number.isInteger(exponent) || exponent < 0 || exponent > 20)
|
|
@@ -29573,8 +30954,8 @@ function money2(value) {
|
|
|
29573
30954
|
function extraUsageReading(pools) {
|
|
29574
30955
|
if (!Array.isArray(pools))
|
|
29575
30956
|
return;
|
|
29576
|
-
const pool = pools.find((candidate) =>
|
|
29577
|
-
if (!
|
|
30957
|
+
const pool = pools.find((candidate) => record11(candidate) && candidate.title === "Extra usage");
|
|
30958
|
+
if (!record11(pool))
|
|
29578
30959
|
return;
|
|
29579
30960
|
const limit = money2(pool.total ?? pool.limit);
|
|
29580
30961
|
const remaining = money2(pool.remaining);
|
|
@@ -29589,7 +30970,7 @@ function extraUsageReading(pools) {
|
|
|
29589
30970
|
used = Math.max(0, limit.minor - remaining.minor);
|
|
29590
30971
|
if (used === undefined)
|
|
29591
30972
|
return;
|
|
29592
|
-
const unit = text5(pool.unit) ?? text5(
|
|
30973
|
+
const unit = text5(pool.unit) ?? text5(record11(pool.total) && pool.total.unit);
|
|
29593
30974
|
const currency = unit && /^[A-Za-z]{3}$/.test(unit) ? unit : "USD";
|
|
29594
30975
|
return {
|
|
29595
30976
|
used: { amountMinor: used, currency, exponent },
|
|
@@ -29745,12 +31126,12 @@ function expectedSeed(input, boundary, refuse3) {
|
|
|
29745
31126
|
const inventory = capture(top("inventory", "roster-incomplete"), ["view", "credentials", "skipped"], "roster-incomplete", refuse3);
|
|
29746
31127
|
const view = inventory.view;
|
|
29747
31128
|
const skipped = items(inventory.skipped, "roster-incomplete", refuse3);
|
|
29748
|
-
const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((
|
|
31129
|
+
const credentialRecords = items(inventory.credentials, "roster-incomplete", refuse3).map((record12) => capture(record12, ["credentialId", "credentialType", "accountIdentity", "state"], "roster-incomplete", refuse3));
|
|
29749
31130
|
if (!filled(view) || skipped.length > 0)
|
|
29750
31131
|
refuse3("roster-incomplete");
|
|
29751
31132
|
const listed = new Map;
|
|
29752
|
-
for (const
|
|
29753
|
-
const { credentialId, credentialType, accountIdentity, state } =
|
|
31133
|
+
for (const record12 of credentialRecords) {
|
|
31134
|
+
const { credentialId, credentialType, accountIdentity, state } = record12;
|
|
29754
31135
|
if (!filled(credentialId) || !filled(accountIdentity) || !filled(state) || listed.has(credentialId)) {
|
|
29755
31136
|
refuse3("roster-incomplete");
|
|
29756
31137
|
}
|
|
@@ -29761,7 +31142,7 @@ function expectedSeed(input, boundary, refuse3) {
|
|
|
29761
31142
|
const primaryIdentity = primary.accountIdentity;
|
|
29762
31143
|
boundary.fallback = "seed-conflict";
|
|
29763
31144
|
const primaryRouteId = top("primaryRouteId", "seed-conflict");
|
|
29764
|
-
const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((
|
|
31145
|
+
const legacyRecords = items(top("legacyRows", "seed-conflict"), "seed-conflict", refuse3).map((record12) => capture(record12, [
|
|
29765
31146
|
"routeId",
|
|
29766
31147
|
"scopedCredentialId",
|
|
29767
31148
|
"anthropicAccountUuid",
|
|
@@ -30981,8 +32362,8 @@ function createNativeVaultRuntime(options) {
|
|
|
30981
32362
|
if (polling)
|
|
30982
32363
|
return polling;
|
|
30983
32364
|
polling = withDetachedNativeLocks(async () => {
|
|
30984
|
-
const
|
|
30985
|
-
if (shutdown.signal.aborted || !
|
|
32365
|
+
const allowed3 = await Promise.all([...watchers].map(async (watch) => !watch.shouldRefresh || await watch.shouldRefresh()));
|
|
32366
|
+
if (shutdown.signal.aborted || !allowed3.some(Boolean))
|
|
30986
32367
|
return;
|
|
30987
32368
|
const roster = await runtime2.refresh(shutdown.signal);
|
|
30988
32369
|
if (shutdown.signal.aborted)
|
|
@@ -31175,9 +32556,9 @@ function createNativeVaultRuntime(options) {
|
|
|
31175
32556
|
custody: options.discover ? { discover: options.discover } : custody,
|
|
31176
32557
|
signal: shutdown.signal,
|
|
31177
32558
|
isActive: async () => {
|
|
31178
|
-
const
|
|
32559
|
+
const allowed3 = await active() && !await relocation.isRelocated();
|
|
31179
32560
|
assertHostAuthorityStable();
|
|
31180
|
-
return
|
|
32561
|
+
return allowed3;
|
|
31181
32562
|
},
|
|
31182
32563
|
projection: () => ({ reservedRouteIds })
|
|
31183
32564
|
}).then(async (roster) => {
|
|
@@ -31592,7 +32973,7 @@ function createNativeVaultRuntime(options) {
|
|
|
31592
32973
|
responseStatus = response.status;
|
|
31593
32974
|
if (response.status === 401 && !combined.aborted) {
|
|
31594
32975
|
await response.body?.cancel().catch(() => {});
|
|
31595
|
-
const
|
|
32976
|
+
const report2 = (receipt) => runtime2.reportFailure(receipt, 401, "direct").catch(() => {
|
|
31596
32977
|
check(combined);
|
|
31597
32978
|
});
|
|
31598
32979
|
const rejected = served;
|
|
@@ -31600,11 +32981,11 @@ function createNativeVaultRuntime(options) {
|
|
|
31600
32981
|
try {
|
|
31601
32982
|
retry = await runtime2.prepareRetry(rejected, combined, "quota-profile");
|
|
31602
32983
|
} catch (error) {
|
|
31603
|
-
await
|
|
32984
|
+
await report2(rejected);
|
|
31604
32985
|
throw error;
|
|
31605
32986
|
}
|
|
31606
32987
|
if (!retry.retry) {
|
|
31607
|
-
await
|
|
32988
|
+
await report2(rejected);
|
|
31608
32989
|
return response;
|
|
31609
32990
|
}
|
|
31610
32991
|
served = retry.receipt;
|
|
@@ -31614,7 +32995,7 @@ function createNativeVaultRuntime(options) {
|
|
|
31614
32995
|
response = await send(input, { ...init, headers });
|
|
31615
32996
|
responseStatus = response.status;
|
|
31616
32997
|
if (response.status === 401)
|
|
31617
|
-
await
|
|
32998
|
+
await report2(served);
|
|
31618
32999
|
}
|
|
31619
33000
|
return response;
|
|
31620
33001
|
}, { preconnect: fetchImpl.preconnect });
|
|
@@ -36798,7 +38179,7 @@ function refused(code, action, parameter) {
|
|
|
36798
38179
|
...parameter !== undefined ? { parameter } : {}
|
|
36799
38180
|
});
|
|
36800
38181
|
}
|
|
36801
|
-
function readPlain(value,
|
|
38182
|
+
function readPlain(value, allowed3) {
|
|
36802
38183
|
if (value === null || typeof value !== "object")
|
|
36803
38184
|
return "malformed";
|
|
36804
38185
|
if (utilTypes7.isProxy(value))
|
|
@@ -36814,7 +38195,7 @@ function readPlain(value, allowed2) {
|
|
|
36814
38195
|
const descriptor = Reflect.getOwnPropertyDescriptor(value, key);
|
|
36815
38196
|
if (!descriptor || !Object.hasOwn(descriptor, "value"))
|
|
36816
38197
|
return "malformed";
|
|
36817
|
-
if (!
|
|
38198
|
+
if (!allowed3.includes(key))
|
|
36818
38199
|
unknownKey = true;
|
|
36819
38200
|
else
|
|
36820
38201
|
fields2.set(key, descriptor.value);
|
|
@@ -36891,7 +38272,7 @@ function readKillswitchEntries(value) {
|
|
|
36891
38272
|
return Object.freeze(entries);
|
|
36892
38273
|
}
|
|
36893
38274
|
var missing2 = { ok: false, code: "missing-parameter" };
|
|
36894
|
-
var
|
|
38275
|
+
var invalid2 = { ok: false, code: "invalid-parameter" };
|
|
36895
38276
|
var absent2 = { ok: true, present: false };
|
|
36896
38277
|
function accept(value) {
|
|
36897
38278
|
return { ok: true, present: true, value };
|
|
@@ -36903,36 +38284,36 @@ function checkParameter(parameter, provided, value) {
|
|
|
36903
38284
|
if (empty)
|
|
36904
38285
|
return missing2;
|
|
36905
38286
|
if (typeof value !== "string")
|
|
36906
|
-
return
|
|
38287
|
+
return invalid2;
|
|
36907
38288
|
return hasContent(value) ? accept(value) : missing2;
|
|
36908
38289
|
case "text": {
|
|
36909
38290
|
if (empty)
|
|
36910
38291
|
return parameter.required ? missing2 : absent2;
|
|
36911
38292
|
if (typeof value !== "string")
|
|
36912
|
-
return
|
|
38293
|
+
return invalid2;
|
|
36913
38294
|
if (!hasContent(value))
|
|
36914
38295
|
return parameter.required ? missing2 : absent2;
|
|
36915
38296
|
if (parameter.id === "apiKey" && /\s/.test(value))
|
|
36916
|
-
return
|
|
38297
|
+
return invalid2;
|
|
36917
38298
|
if (parameter.id === "baseURL" && !isApiBaseURL(value))
|
|
36918
|
-
return
|
|
38299
|
+
return invalid2;
|
|
36919
38300
|
return accept(value);
|
|
36920
38301
|
}
|
|
36921
38302
|
case "choice":
|
|
36922
38303
|
if (empty)
|
|
36923
38304
|
return parameter.required ? missing2 : absent2;
|
|
36924
38305
|
if (typeof value !== "string")
|
|
36925
|
-
return
|
|
36926
|
-
return parameter.choices.includes(value) ? accept(value) :
|
|
38306
|
+
return invalid2;
|
|
38307
|
+
return parameter.choices.includes(value) ? accept(value) : invalid2;
|
|
36927
38308
|
case "number":
|
|
36928
38309
|
if (empty)
|
|
36929
38310
|
return missing2;
|
|
36930
|
-
return isHour(value) ? accept(value) :
|
|
38311
|
+
return isHour(value) ? accept(value) : invalid2;
|
|
36931
38312
|
case "limit-entries": {
|
|
36932
38313
|
if (empty)
|
|
36933
38314
|
return missing2;
|
|
36934
38315
|
const entries = readKillswitchEntries(value);
|
|
36935
|
-
return entries ? accept(entries) :
|
|
38316
|
+
return entries ? accept(entries) : invalid2;
|
|
36936
38317
|
}
|
|
36937
38318
|
default: {
|
|
36938
38319
|
const unhandled = parameter;
|
|
@@ -37019,8 +38400,8 @@ function plan(actions2, rawRequest, rawContext) {
|
|
|
37019
38400
|
if (action.interactive && !context.interactive)
|
|
37020
38401
|
return done(refused(action.headlessRefusal, action.id));
|
|
37021
38402
|
const rawValues = request2.get("values");
|
|
37022
|
-
const
|
|
37023
|
-
const values = rawValues === undefined ? new Map : readPlain(rawValues,
|
|
38403
|
+
const allowed3 = action.parameters.map((parameter) => parameter.id);
|
|
38404
|
+
const values = rawValues === undefined ? new Map : readPlain(rawValues, allowed3);
|
|
37024
38405
|
if (values === "malformed")
|
|
37025
38406
|
return done(refused("invalid-request", action.id));
|
|
37026
38407
|
if (values === "unknown-key")
|
|
@@ -38572,13 +39953,13 @@ class AnthropicOAuthOriginError extends Error {
|
|
|
38572
39953
|
}
|
|
38573
39954
|
}
|
|
38574
39955
|
function sameOrigin(url, origin) {
|
|
38575
|
-
let
|
|
39956
|
+
let allowed3;
|
|
38576
39957
|
try {
|
|
38577
|
-
|
|
39958
|
+
allowed3 = new URL(origin);
|
|
38578
39959
|
} catch {
|
|
38579
39960
|
return false;
|
|
38580
39961
|
}
|
|
38581
|
-
return url.protocol ===
|
|
39962
|
+
return url.protocol === allowed3.protocol && url.origin === allowed3.origin;
|
|
38582
39963
|
}
|
|
38583
39964
|
function requireAnthropicOAuthOrigin(value, options = {}) {
|
|
38584
39965
|
const refuse5 = options.refusal ?? (() => new AnthropicOAuthOriginError);
|
|
@@ -39534,9 +40915,9 @@ class QuotaHeaderFeedRegistry {
|
|
|
39534
40915
|
await this.reapStaleSiblingLeases(directory);
|
|
39535
40916
|
let entries = {};
|
|
39536
40917
|
try {
|
|
39537
|
-
const
|
|
39538
|
-
if (
|
|
39539
|
-
entries =
|
|
40918
|
+
const record12 = JSON.parse(await readFile13(this.filePath, "utf8"));
|
|
40919
|
+
if (record12.version === QUOTA_HEADER_FEED_SCHEMA_VERSION && record12.entries && typeof record12.entries === "object")
|
|
40920
|
+
entries = record12.entries;
|
|
39540
40921
|
} catch {}
|
|
39541
40922
|
entries[accountKey] = cleanEntry;
|
|
39542
40923
|
const tempPath = `${this.filePath}.${randomUUID21()}.tmp`;
|
|
@@ -39590,10 +40971,10 @@ class QuotaHeaderFeedRegistry {
|
|
|
39590
40971
|
const newest = new Map;
|
|
39591
40972
|
await Promise.all(names2.map(async (name) => {
|
|
39592
40973
|
try {
|
|
39593
|
-
const
|
|
39594
|
-
if (
|
|
40974
|
+
const record12 = JSON.parse(await readFile13(join26(directory, name), "utf8"));
|
|
40975
|
+
if (record12.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record12.entries || typeof record12.entries !== "object")
|
|
39595
40976
|
return;
|
|
39596
|
-
for (const [accountKey, candidate] of Object.entries(
|
|
40977
|
+
for (const [accountKey, candidate] of Object.entries(record12.entries)) {
|
|
39597
40978
|
if (!candidate || typeof candidate !== "object" || candidate.schema_version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || candidate.provider !== "anthropic" || !validIdentity(candidate))
|
|
39598
40979
|
continue;
|
|
39599
40980
|
const observed = candidate.observed_at_ms;
|
|
@@ -39986,13 +41367,13 @@ function isInvalidJsonBody(text6) {
|
|
|
39986
41367
|
}
|
|
39987
41368
|
if (!parsed || typeof parsed !== "object")
|
|
39988
41369
|
return false;
|
|
39989
|
-
const
|
|
39990
|
-
const error =
|
|
39991
|
-
if (
|
|
41370
|
+
const record12 = parsed;
|
|
41371
|
+
const error = record12.error;
|
|
41372
|
+
if (record12.type === "error" && error && typeof error === "object" && typeof error.type === "string" && typeof error.message === "string") {
|
|
39992
41373
|
const message = error.message;
|
|
39993
41374
|
return INVALID_JSON_MESSAGES.some((prefix) => message.startsWith(prefix));
|
|
39994
41375
|
}
|
|
39995
|
-
return typeof
|
|
41376
|
+
return typeof record12.error === "string" && record12.reason === "bad_json" && BAD_JSON_TEXT.test(record12.error);
|
|
39996
41377
|
}
|
|
39997
41378
|
async function classifyGzipRejection(response) {
|
|
39998
41379
|
const { status } = response;
|
|
@@ -40202,8 +41583,8 @@ async function holderFenceBlockers(input) {
|
|
|
40202
41583
|
}
|
|
40203
41584
|
for (const value of contents?.entries ?? []) {
|
|
40204
41585
|
const life = holderEntryLiveness(value);
|
|
40205
|
-
const
|
|
40206
|
-
const listed = Array.isArray(
|
|
41586
|
+
const record12 = value;
|
|
41587
|
+
const listed = Array.isArray(record12?.files) ? record12.files.filter((file) => typeof file === "string") : undefined;
|
|
40207
41588
|
if (!life || !listed) {
|
|
40208
41589
|
blockers.push({
|
|
40209
41590
|
kind: "holder",
|
|
@@ -40223,7 +41604,7 @@ async function holderFenceBlockers(input) {
|
|
|
40223
41604
|
kind: "holder",
|
|
40224
41605
|
holderFile,
|
|
40225
41606
|
pid: life.pid,
|
|
40226
|
-
role: typeof
|
|
41607
|
+
role: typeof record12.role === "string" ? record12.role : null,
|
|
40227
41608
|
file: overlap
|
|
40228
41609
|
});
|
|
40229
41610
|
}
|
|
@@ -40305,10 +41686,10 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
|
|
|
40305
41686
|
if (!/^port-\d+\.json$/.test(name))
|
|
40306
41687
|
continue;
|
|
40307
41688
|
const path2 = join28(dir, name);
|
|
40308
|
-
const
|
|
40309
|
-
if (
|
|
41689
|
+
const record12 = await readArtifact(path2, blockers);
|
|
41690
|
+
if (record12 === undefined || stamped(record12.value))
|
|
40310
41691
|
continue;
|
|
40311
|
-
const { value, startedAt } =
|
|
41692
|
+
const { value, startedAt } = record12;
|
|
40312
41693
|
const pid = value.pid;
|
|
40313
41694
|
if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) {
|
|
40314
41695
|
blockers.push({ kind: "artifact-scan", path: path2, reason: "invalid" });
|
|
@@ -40324,11 +41705,11 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
|
|
|
40324
41705
|
if (!match)
|
|
40325
41706
|
continue;
|
|
40326
41707
|
const path2 = join28(dir, name);
|
|
40327
|
-
const
|
|
40328
|
-
if (
|
|
41708
|
+
const record12 = await readArtifact(path2, blockers);
|
|
41709
|
+
if (record12 === undefined || stamped(record12.value))
|
|
40329
41710
|
continue;
|
|
40330
41711
|
const pid = Number(match[1]);
|
|
40331
|
-
if (!recordPredatesBoot(
|
|
41712
|
+
if (!recordPredatesBoot(record12.startedAt, clock) && pidAlive2(pid))
|
|
40332
41713
|
blockers.push({ kind: "pre-n-artifact", artifact: path2, pid });
|
|
40333
41714
|
}
|
|
40334
41715
|
}
|
|
@@ -40616,14 +41997,14 @@ async function drainCoalescedWrites(dataset) {
|
|
|
40616
41997
|
await drainVaultQuota(dataset.oldVault.roster);
|
|
40617
41998
|
forgetRelocationObservations();
|
|
40618
41999
|
}
|
|
40619
|
-
function relocationTombstone(
|
|
42000
|
+
function relocationTombstone(record12) {
|
|
40620
42001
|
return `${JSON.stringify({
|
|
40621
42002
|
version: 0,
|
|
40622
|
-
relocatedTo:
|
|
40623
|
-
stateRoot:
|
|
40624
|
-
identity:
|
|
40625
|
-
attempt:
|
|
40626
|
-
by:
|
|
42003
|
+
relocatedTo: record12.sub,
|
|
42004
|
+
stateRoot: record12.stateRoot,
|
|
42005
|
+
identity: record12.identity,
|
|
42006
|
+
attempt: record12.attempt,
|
|
42007
|
+
by: record12.by
|
|
40627
42008
|
})}
|
|
40628
42009
|
`;
|
|
40629
42010
|
}
|
|
@@ -40660,17 +42041,17 @@ async function removeOwnStaging(path2) {
|
|
|
40660
42041
|
throw error;
|
|
40661
42042
|
}
|
|
40662
42043
|
}
|
|
40663
|
-
function recordFilesProblem(
|
|
40664
|
-
if (
|
|
40665
|
-
return `it lists ${
|
|
42044
|
+
function recordFilesProblem(record12, dataset) {
|
|
42045
|
+
if (record12.files.length !== dataset.slots.length)
|
|
42046
|
+
return `it lists ${record12.files.length} files, not ${dataset.slots.length}`;
|
|
40666
42047
|
for (const slot of dataset.slots) {
|
|
40667
|
-
const file =
|
|
42048
|
+
const file = record12.files.find((candidate) => candidate.role === slot.role);
|
|
40668
42049
|
if (!file)
|
|
40669
42050
|
return `it has no ${slot.role} entry`;
|
|
40670
42051
|
if (file.from !== slot.from || file.to !== slot.to)
|
|
40671
42052
|
return `its ${slot.role} entry names ${file.from} and ${file.to}, not ${slot.from} and ${slot.to}`;
|
|
40672
42053
|
}
|
|
40673
|
-
for (const file of
|
|
42054
|
+
for (const file of record12.restore?.files ?? []) {
|
|
40674
42055
|
const slot = dataset.slots.find((candidate) => candidate.role === file.role);
|
|
40675
42056
|
if (!slot || file.from !== slot.from || file.to !== slot.to)
|
|
40676
42057
|
return `its restore lists ${file.from} and ${file.to} for ${file.role}`;
|
|
@@ -40787,15 +42168,15 @@ async function owned2(ctx, step, expect) {
|
|
|
40787
42168
|
if (outcome2 === "skipped")
|
|
40788
42169
|
throw new Error(`anthropic-auth stopped: ${step.kind === "rename" ? step.to : step.path} changed while it was being replaced`);
|
|
40789
42170
|
}
|
|
40790
|
-
async function rollbackPreparing(
|
|
40791
|
-
const { attempt } =
|
|
42171
|
+
async function rollbackPreparing(record12, dataset, ctx) {
|
|
42172
|
+
const { attempt } = record12;
|
|
40792
42173
|
const slot = (role) => {
|
|
40793
|
-
const found =
|
|
42174
|
+
const found = record12.files.find((file) => file.role === role);
|
|
40794
42175
|
if (!found)
|
|
40795
42176
|
throw new StateLayoutRollbackRefused(dataset.sub, `no ${role} entry`);
|
|
40796
42177
|
return found;
|
|
40797
42178
|
};
|
|
40798
|
-
if (
|
|
42179
|
+
if (record12.barriers.journal === "present") {
|
|
40799
42180
|
const journal = slot("journal");
|
|
40800
42181
|
const moving = movingJournalPath(journal.from, attempt);
|
|
40801
42182
|
const movingThere = await exists3(moving);
|
|
@@ -40810,7 +42191,7 @@ async function rollbackPreparing(record10, dataset, ctx) {
|
|
|
40810
42191
|
await stateLayoutStep(ctx, "rollback:journal");
|
|
40811
42192
|
for (const role of ["localRuntime", "vaultRuntime"]) {
|
|
40812
42193
|
const file = slot(role);
|
|
40813
|
-
const original =
|
|
42194
|
+
const original = record12.barriers[role].original;
|
|
40814
42195
|
await removeOwnStaging(relocatingPath(file.from, attempt));
|
|
40815
42196
|
const found = await tombstoneAttempt(file.from);
|
|
40816
42197
|
if (found !== undefined && found !== attempt)
|
|
@@ -40839,7 +42220,7 @@ async function rollbackPreparing(record10, dataset, ctx) {
|
|
|
40839
42220
|
}
|
|
40840
42221
|
await ctx.fs.syncDirectory(dataset.oldDir);
|
|
40841
42222
|
await stateLayoutStep(ctx, "rollback:old-dir-flushed");
|
|
40842
|
-
for (const file of
|
|
42223
|
+
for (const file of record12.files) {
|
|
40843
42224
|
await removeOwnStaging(relocatingPath(file.to, attempt));
|
|
40844
42225
|
if (file.sha256 === null)
|
|
40845
42226
|
continue;
|
|
@@ -40857,7 +42238,7 @@ async function rollbackPreparing(record10, dataset, ctx) {
|
|
|
40857
42238
|
await ctx.fs.syncDirectory(dataset.sub);
|
|
40858
42239
|
await stateLayoutStep(ctx, "rollback:sub-flushed");
|
|
40859
42240
|
const rolledBack = {
|
|
40860
|
-
...
|
|
42241
|
+
...record12,
|
|
40861
42242
|
phase: "rolled-back",
|
|
40862
42243
|
rolledBackAt: ctx.now()
|
|
40863
42244
|
};
|
|
@@ -40869,19 +42250,19 @@ async function rollbackPreparing(record10, dataset, ctx) {
|
|
|
40869
42250
|
forgetRelocationObservations();
|
|
40870
42251
|
return rolledBack;
|
|
40871
42252
|
}
|
|
40872
|
-
async function cleanupOldCopies(
|
|
42253
|
+
async function cleanupOldCopies(record12, dataset, ctx) {
|
|
40873
42254
|
const kept = [];
|
|
40874
42255
|
const conflict = [];
|
|
40875
42256
|
const publish = (next2) => publishStateLayoutRecord(next2, {
|
|
40876
42257
|
assertLeases: () => ctx.stack.assertAll(),
|
|
40877
42258
|
expect: expectRecord(dataset.sub, {
|
|
40878
42259
|
phase: "committed",
|
|
40879
|
-
attempt:
|
|
42260
|
+
attempt: record12.attempt
|
|
40880
42261
|
})
|
|
40881
42262
|
}, ctx.fs);
|
|
40882
42263
|
const outcome2 = () => {
|
|
40883
42264
|
const next2 = {
|
|
40884
|
-
...
|
|
42265
|
+
...record12,
|
|
40885
42266
|
cleanup: conflict.length ? "conflict" : kept.length ? "kept" : "done",
|
|
40886
42267
|
...kept.length ? { kept: [...kept] } : {},
|
|
40887
42268
|
...conflict.length ? { conflict: [...conflict] } : {}
|
|
@@ -40897,16 +42278,16 @@ async function cleanupOldCopies(record10, dataset, ctx) {
|
|
|
40897
42278
|
return stateLayoutConflict(first?.old ?? dataset.oldPaths.state, first?.new ?? dataset.newPaths.state, cause);
|
|
40898
42279
|
};
|
|
40899
42280
|
try {
|
|
40900
|
-
const journalSlot =
|
|
42281
|
+
const journalSlot = record12.files.find((file) => file.role === "journal");
|
|
40901
42282
|
if (journalSlot && await exists3(journalSlot.from))
|
|
40902
42283
|
conflict.push({ old: journalSlot.from, new: journalSlot.to });
|
|
40903
42284
|
for (const role of RELOCATION_ROLES) {
|
|
40904
42285
|
if (role === "localRuntime" || role === "vaultRuntime")
|
|
40905
42286
|
continue;
|
|
40906
|
-
const file =
|
|
42287
|
+
const file = record12.files.find((candidate) => candidate.role === role);
|
|
40907
42288
|
if (!file)
|
|
40908
42289
|
continue;
|
|
40909
|
-
const path2 = role === "journal" ? movingJournalPath(file.from,
|
|
42290
|
+
const path2 = role === "journal" ? movingJournalPath(file.from, record12.attempt) : file.from;
|
|
40910
42291
|
await ctx.stack.assertAll();
|
|
40911
42292
|
const credential2 = CREDENTIAL_AUTHORITY_ROLES.includes(role);
|
|
40912
42293
|
let digest3;
|
|
@@ -41068,8 +42449,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
|
|
|
41068
42449
|
logger2.error("state-layout", "anthropic-auth could not move its state; keeping the old folder", {
|
|
41069
42450
|
reason
|
|
41070
42451
|
});
|
|
41071
|
-
const
|
|
41072
|
-
return { status: "rolled-back", reason, record:
|
|
42452
|
+
const record12 = await rollbackAfterFailure(preparing, dataset, ctx);
|
|
42453
|
+
return { status: "rolled-back", reason, record: record12 };
|
|
41073
42454
|
}
|
|
41074
42455
|
const committed = {
|
|
41075
42456
|
...preparing,
|
|
@@ -41090,8 +42471,8 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
|
|
|
41090
42471
|
await syncCommitted(dataset, ctx);
|
|
41091
42472
|
} else if (onDisk?.phase === "preparing" && onDisk.attempt === attempt) {
|
|
41092
42473
|
const reason = error instanceof Error ? error.message : String(error);
|
|
41093
|
-
const
|
|
41094
|
-
return { status: "rolled-back", reason, record:
|
|
42474
|
+
const record12 = await rollbackAfterFailure(preparing, dataset, ctx);
|
|
42475
|
+
return { status: "rolled-back", reason, record: record12 };
|
|
41095
42476
|
} else
|
|
41096
42477
|
throw error;
|
|
41097
42478
|
}
|
|
@@ -41144,10 +42525,10 @@ function refused2(message, paths = [], cause) {
|
|
|
41144
42525
|
logger2.error("state-layout", message, { code: "restore-refused", paths });
|
|
41145
42526
|
return new StateLayoutRefusalError("restore-refused", message, paths, cause);
|
|
41146
42527
|
}
|
|
41147
|
-
function requireRestoreDetail(
|
|
41148
|
-
const restore =
|
|
42528
|
+
function requireRestoreDetail(record12) {
|
|
42529
|
+
const restore = record12.restore;
|
|
41149
42530
|
if (!restore?.attempt || !restore.files || !restore.runtimes)
|
|
41150
|
-
throw refused2(`${layoutRecordPath(
|
|
42531
|
+
throw refused2(`${layoutRecordPath(record12.sub)} records an unfinished restore without the files it moved, so anthropic-auth can't finish it.`, [layoutRecordPath(record12.sub)]);
|
|
41151
42532
|
return {
|
|
41152
42533
|
...restore,
|
|
41153
42534
|
attempt: restore.attempt,
|
|
@@ -41208,9 +42589,9 @@ async function syncObservedRestoreRecord(dataset, ctx) {
|
|
|
41208
42589
|
throw new StateLayoutRefusalError("unsafe", `anthropic-auth could not make ${path2} durable, so it won't finish restoring its state; run ${RESTORE_LEGACY_COMMAND} again.`, [path2], error);
|
|
41209
42590
|
}
|
|
41210
42591
|
}
|
|
41211
|
-
async function finishRestoreRetirement(
|
|
41212
|
-
const restore = requireRestoreDetail(
|
|
41213
|
-
const kept = [...
|
|
42592
|
+
async function finishRestoreRetirement(record12, dataset, ctx) {
|
|
42593
|
+
const restore = requireRestoreDetail(record12);
|
|
42594
|
+
const kept = [...record12.restore?.kept ?? []];
|
|
41214
42595
|
for (const file of restore.files) {
|
|
41215
42596
|
try {
|
|
41216
42597
|
const digest3 = await digestFile(file.to);
|
|
@@ -41235,7 +42616,7 @@ async function finishRestoreRetirement(record10, dataset, ctx) {
|
|
|
41235
42616
|
await ctx.fs.syncDirectory(dataset.sub);
|
|
41236
42617
|
await stateLayoutStep(ctx, "restore:sub-flushed");
|
|
41237
42618
|
const done2 = {
|
|
41238
|
-
...
|
|
42619
|
+
...record12,
|
|
41239
42620
|
restore: { ...restore, cleanup: "done", ...kept.length ? { kept } : {} }
|
|
41240
42621
|
};
|
|
41241
42622
|
await publishStateLayoutRecord(done2, {
|
|
@@ -41246,13 +42627,13 @@ async function finishRestoreRetirement(record10, dataset, ctx) {
|
|
|
41246
42627
|
forgetRelocationObservations();
|
|
41247
42628
|
return done2;
|
|
41248
42629
|
}
|
|
41249
|
-
async function discardAbandonedRestore(
|
|
41250
|
-
const restore = requireRestoreDetail(
|
|
42630
|
+
async function discardAbandonedRestore(record12, dataset, ctx) {
|
|
42631
|
+
const restore = requireRestoreDetail(record12);
|
|
41251
42632
|
for (const file of restore.files)
|
|
41252
42633
|
if (await exists3(file.staging))
|
|
41253
42634
|
await owned2(ctx, { kind: "unlink", path: file.staging }, expectPresent(file.staging));
|
|
41254
42635
|
await ctx.fs.syncDirectory(dataset.oldDir);
|
|
41255
|
-
const { restore: _abandoned, ...move } =
|
|
42636
|
+
const { restore: _abandoned, ...move } = record12;
|
|
41256
42637
|
const committed = { ...move, phase: "committed" };
|
|
41257
42638
|
await publishStateLayoutRecord(committed, {
|
|
41258
42639
|
assertLeases: () => ctx.stack.assertAll(),
|
|
@@ -41262,8 +42643,8 @@ async function discardAbandonedRestore(record10, dataset, ctx) {
|
|
|
41262
42643
|
forgetRelocationObservations();
|
|
41263
42644
|
return committed;
|
|
41264
42645
|
}
|
|
41265
|
-
async function classifyStagedRestore(
|
|
41266
|
-
const restore = requireRestoreDetail(
|
|
42646
|
+
async function classifyStagedRestore(record12, dataset) {
|
|
42647
|
+
const restore = requireRestoreDetail(record12);
|
|
41267
42648
|
const problems = [];
|
|
41268
42649
|
const listed = (role) => restore.files.find((file) => file.role === role);
|
|
41269
42650
|
const isStaged = async (file) => {
|
|
@@ -41323,7 +42704,7 @@ async function classifyStagedRestore(record10, dataset) {
|
|
|
41323
42704
|
if (!file)
|
|
41324
42705
|
continue;
|
|
41325
42706
|
const staged = await isStaged(file);
|
|
41326
|
-
if (staged && tombstone ===
|
|
42707
|
+
if (staged && tombstone === record12.attempt)
|
|
41327
42708
|
barriers.push({
|
|
41328
42709
|
role,
|
|
41329
42710
|
action: { kind: "rename", file, over: "tombstone" }
|
|
@@ -41335,7 +42716,7 @@ async function classifyStagedRestore(record10, dataset) {
|
|
|
41335
42716
|
problems.push(`${file.staging} is missing, so ${legacy} can't be restored`);
|
|
41336
42717
|
else
|
|
41337
42718
|
problems.push(`${legacy} is no longer this move's tombstone while ${file.staging} still waits to replace it`);
|
|
41338
|
-
} else if (tombstone ===
|
|
42719
|
+
} else if (tombstone === record12.attempt)
|
|
41339
42720
|
barriers.push({
|
|
41340
42721
|
role,
|
|
41341
42722
|
action: { kind: "unlink-tombstone", path: legacy }
|
|
@@ -41354,36 +42735,36 @@ async function classifyStagedRestore(record10, dataset) {
|
|
|
41354
42735
|
}
|
|
41355
42736
|
return { data, barriers, problems };
|
|
41356
42737
|
}
|
|
41357
|
-
async function act(action,
|
|
42738
|
+
async function act(action, record12, ctx) {
|
|
41358
42739
|
if (action.kind === "none")
|
|
41359
42740
|
return;
|
|
41360
42741
|
if (action.kind === "unlink-tombstone") {
|
|
41361
|
-
await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path,
|
|
42742
|
+
await owned2(ctx, { kind: "unlink", path: action.path }, expectTombstone(action.path, record12.attempt));
|
|
41362
42743
|
return;
|
|
41363
42744
|
}
|
|
41364
42745
|
const { file, over } = action;
|
|
41365
|
-
const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from,
|
|
42746
|
+
const target2 = over === "absent" ? expectAbsent(file.from) : over === "present" ? expectPresent(file.from) : expectTombstone(file.from, record12.attempt);
|
|
41366
42747
|
await owned2(ctx, { kind: "rename", from: file.staging, to: file.from }, both(expectDigest(file.staging, file.sha256), target2));
|
|
41367
42748
|
}
|
|
41368
|
-
async function finishStagedRestore(
|
|
41369
|
-
const restore = requireRestoreDetail(
|
|
41370
|
-
const plan2 = await classifyStagedRestore(
|
|
42749
|
+
async function finishStagedRestore(record12, dataset, ctx) {
|
|
42750
|
+
const restore = requireRestoreDetail(record12);
|
|
42751
|
+
const plan2 = await classifyStagedRestore(record12, dataset);
|
|
41371
42752
|
if (plan2.problems.length)
|
|
41372
42753
|
throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${plan2.problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir]);
|
|
41373
42754
|
for (const { role, action } of plan2.data) {
|
|
41374
|
-
await act(action,
|
|
42755
|
+
await act(action, record12, ctx);
|
|
41375
42756
|
await stateLayoutStep(ctx, `restore:placed:${role}`);
|
|
41376
42757
|
}
|
|
41377
42758
|
await ctx.fs.syncDirectory(dataset.oldDir);
|
|
41378
42759
|
await stateLayoutStep(ctx, "restore:data-flushed");
|
|
41379
42760
|
for (const { role, action } of plan2.barriers) {
|
|
41380
|
-
await act(action,
|
|
42761
|
+
await act(action, record12, ctx);
|
|
41381
42762
|
await stateLayoutStep(ctx, `restore:placed:${role}`);
|
|
41382
42763
|
}
|
|
41383
42764
|
await ctx.fs.syncDirectory(dataset.oldDir);
|
|
41384
42765
|
await stateLayoutStep(ctx, "restore:barriers-flushed");
|
|
41385
42766
|
const restored = {
|
|
41386
|
-
...
|
|
42767
|
+
...record12,
|
|
41387
42768
|
phase: "restored",
|
|
41388
42769
|
restore: { ...restore, cleanup: "pending" }
|
|
41389
42770
|
};
|
|
@@ -41395,15 +42776,15 @@ async function finishStagedRestore(record10, dataset, ctx) {
|
|
|
41395
42776
|
forgetRelocationObservations();
|
|
41396
42777
|
return finishRestoreRetirement(restored, dataset, ctx);
|
|
41397
42778
|
}
|
|
41398
|
-
async function newRestoreProblems(
|
|
42779
|
+
async function newRestoreProblems(record12, dataset, options) {
|
|
41399
42780
|
const problems = [];
|
|
41400
|
-
if (
|
|
42781
|
+
if (record12.cleanup === "pending")
|
|
41401
42782
|
problems.push("the move has not finished removing the old copies; start OpenCode with anthropic-auth once and close it again");
|
|
41402
|
-
if (
|
|
41403
|
-
for (const pair of
|
|
42783
|
+
if (record12.cleanup === "conflict")
|
|
42784
|
+
for (const pair of record12.conflict ?? [])
|
|
41404
42785
|
problems.push(`two copies of the account state exist (${pair.old} and ${pair.new}); keep the one you trust and move the other out of both folders`);
|
|
41405
|
-
if (
|
|
41406
|
-
for (const path2 of
|
|
42786
|
+
if (record12.cleanup === "kept") {
|
|
42787
|
+
for (const path2 of record12.kept ?? [])
|
|
41407
42788
|
if (await exists3(path2))
|
|
41408
42789
|
problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
|
|
41409
42790
|
}
|
|
@@ -41413,20 +42794,20 @@ async function newRestoreProblems(record10, dataset, options) {
|
|
|
41413
42794
|
problems.push(`${describeFenceBlocker(blocker)} is still running`);
|
|
41414
42795
|
for (const slot of dataset.slots) {
|
|
41415
42796
|
if (slot.role === "localRuntime" || slot.role === "vaultRuntime") {
|
|
41416
|
-
if (await tombstoneAttempt(slot.from) !==
|
|
42797
|
+
if (await tombstoneAttempt(slot.from) !== record12.attempt)
|
|
41417
42798
|
problems.push(`${slot.from} is no longer the marker the move left there; move it aside`);
|
|
41418
42799
|
continue;
|
|
41419
42800
|
}
|
|
41420
42801
|
if (await exists3(slot.from))
|
|
41421
42802
|
problems.push(`${slot.from} came back after the move; move it aside or delete it`);
|
|
41422
42803
|
}
|
|
41423
|
-
const moving = movingJournalPath(dataset.oldPaths.journal,
|
|
42804
|
+
const moving = movingJournalPath(dataset.oldPaths.journal, record12.attempt);
|
|
41424
42805
|
if (await exists3(moving))
|
|
41425
42806
|
problems.push(`${moving} is still there; move it aside or delete it`);
|
|
41426
42807
|
return problems;
|
|
41427
42808
|
}
|
|
41428
|
-
async function startRestore(
|
|
41429
|
-
const problems = await newRestoreProblems(
|
|
42809
|
+
async function startRestore(record12, dataset, ctx, options) {
|
|
42810
|
+
const problems = await newRestoreProblems(record12, dataset, options);
|
|
41430
42811
|
if (problems.length)
|
|
41431
42812
|
throw refused2(`anthropic-auth can't restore its state to ${dataset.oldDir} yet: ${problems.join("; ")}. Then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.oldDir, dataset.sub]);
|
|
41432
42813
|
const attempt = randomUUID23();
|
|
@@ -41450,7 +42831,7 @@ async function startRestore(record10, dataset, ctx, options) {
|
|
|
41450
42831
|
}
|
|
41451
42832
|
const listed = (role) => files.some((file) => file.role === role);
|
|
41452
42833
|
const restoring = {
|
|
41453
|
-
...
|
|
42834
|
+
...record12,
|
|
41454
42835
|
phase: "restoring",
|
|
41455
42836
|
restore: {
|
|
41456
42837
|
attempt,
|
|
@@ -41468,7 +42849,7 @@ async function startRestore(record10, dataset, ctx, options) {
|
|
|
41468
42849
|
const current = await readStateLayoutRecord(dataset.sub).catch(() => {
|
|
41469
42850
|
return;
|
|
41470
42851
|
});
|
|
41471
|
-
return current?.phase === "committed" && current.attempt ===
|
|
42852
|
+
return current?.phase === "committed" && current.attempt === record12.attempt ? undefined : "layout.json is no longer the committed move";
|
|
41472
42853
|
}
|
|
41473
42854
|
}, ctx.fs);
|
|
41474
42855
|
await stateLayoutStep(ctx, "restore:restoring-written");
|
|
@@ -41493,11 +42874,11 @@ async function startRestore(record10, dataset, ctx, options) {
|
|
|
41493
42874
|
await stateLayoutStep(ctx, "restore:staged-written");
|
|
41494
42875
|
return finishStagedRestore(staged, dataset, ctx);
|
|
41495
42876
|
}
|
|
41496
|
-
function requireRecordMatches(
|
|
42877
|
+
function requireRecordMatches(record12, dataset) {
|
|
41497
42878
|
const path2 = layoutRecordPath(dataset.sub);
|
|
41498
|
-
if (
|
|
41499
|
-
throw new StateLayoutRefusalError("other-dataset", `${path2} belongs to another config folder (${
|
|
41500
|
-
const problem = recordFilesProblem(
|
|
42879
|
+
if (record12.identity !== dataset.identity || record12.oldDir !== dataset.oldDir || record12.sub !== dataset.sub || record12.storageIds.local !== dataset.storageIds.local || record12.storageIds.vault !== dataset.storageIds.vault)
|
|
42880
|
+
throw new StateLayoutRefusalError("other-dataset", `${path2} belongs to another config folder (${record12.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [path2, record12.oldDir, dataset.oldDir]);
|
|
42881
|
+
const problem = recordFilesProblem(record12, dataset);
|
|
41501
42882
|
if (problem)
|
|
41502
42883
|
throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't use ${path2}: ${problem}.`, [path2]);
|
|
41503
42884
|
}
|
|
@@ -41509,12 +42890,12 @@ async function readRecord(sub) {
|
|
|
41509
42890
|
throw new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't read ${path2}, which records where its state is, so it won't restore anything. Restore the file from a backup or ask for help; do not delete the state folder.`, [path2], error);
|
|
41510
42891
|
}
|
|
41511
42892
|
}
|
|
41512
|
-
function finished(
|
|
41513
|
-
if (
|
|
42893
|
+
function finished(record12) {
|
|
42894
|
+
if (record12 === undefined)
|
|
41514
42895
|
return "anthropic-auth has not moved this state out of the config folder";
|
|
41515
|
-
if (
|
|
42896
|
+
if (record12.phase === "rolled-back")
|
|
41516
42897
|
return "the move of this state was undone before it finished";
|
|
41517
|
-
if (
|
|
42898
|
+
if (record12.phase === "restored" && record12.restore?.cleanup === "done")
|
|
41518
42899
|
return "this state was already restored to the config folder";
|
|
41519
42900
|
return;
|
|
41520
42901
|
}
|
|
@@ -41579,32 +42960,32 @@ async function restoreLegacyLayout(options = {}) {
|
|
|
41579
42960
|
}
|
|
41580
42961
|
await stateLayoutStep(ctx, "restore:locks-held");
|
|
41581
42962
|
for (let round = 0;round < 3; round++) {
|
|
41582
|
-
const
|
|
41583
|
-
const done2 = finished(
|
|
41584
|
-
if (done2 || !
|
|
42963
|
+
const record12 = await readRecord(sub);
|
|
42964
|
+
const done2 = finished(record12);
|
|
42965
|
+
if (done2 || !record12)
|
|
41585
42966
|
return { status: "not-moved", reason: done2 ?? "" };
|
|
41586
|
-
requireRecordMatches(
|
|
42967
|
+
requireRecordMatches(record12, dataset);
|
|
41587
42968
|
let result;
|
|
41588
|
-
switch (
|
|
42969
|
+
switch (record12.phase) {
|
|
41589
42970
|
case "preparing":
|
|
41590
42971
|
throw refused2(`A move of anthropic-auth's state for ${dataset.oldDir} did not finish. Start OpenCode with anthropic-auth once to undo it; there is then nothing to restore.`, [layoutRecordPath(sub)]);
|
|
41591
42972
|
case "restoring":
|
|
41592
|
-
await discardAbandonedRestore(
|
|
42973
|
+
await discardAbandonedRestore(record12, dataset, ctx);
|
|
41593
42974
|
continue;
|
|
41594
42975
|
case "committed":
|
|
41595
|
-
result = await startRestore(
|
|
42976
|
+
result = await startRestore(record12, dataset, ctx, options);
|
|
41596
42977
|
break;
|
|
41597
42978
|
case "restore-staged": {
|
|
41598
42979
|
await syncObservedRestoreRecord(dataset, ctx);
|
|
41599
42980
|
const problems = await holderProblems(join30(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
|
|
41600
42981
|
if (problems.length)
|
|
41601
42982
|
throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${problems.join("; ")}. Close them, then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.sub]);
|
|
41602
|
-
result = await finishStagedRestore(
|
|
42983
|
+
result = await finishStagedRestore(record12, dataset, ctx);
|
|
41603
42984
|
break;
|
|
41604
42985
|
}
|
|
41605
42986
|
default:
|
|
41606
42987
|
await syncObservedRestoreRecord(dataset, ctx);
|
|
41607
|
-
result = await finishRestoreRetirement(
|
|
42988
|
+
result = await finishRestoreRetirement(record12, dataset, ctx);
|
|
41608
42989
|
}
|
|
41609
42990
|
return {
|
|
41610
42991
|
status: "restored",
|
|
@@ -41662,13 +43043,13 @@ function configIdentity(configDir) {
|
|
|
41662
43043
|
refuse5("io-failed", `anthropic-auth can't resolve its config folder ${configDir}: ${errorMessage(error)}`, [configDir], error);
|
|
41663
43044
|
}
|
|
41664
43045
|
}
|
|
41665
|
-
function noMoveRecord(
|
|
41666
|
-
return
|
|
43046
|
+
function noMoveRecord(record12) {
|
|
43047
|
+
return record12 === undefined || record12.phase === "rolled-back" || record12.phase === "restored" && record12.restore?.cleanup === "done";
|
|
41667
43048
|
}
|
|
41668
|
-
function requireRecordMatches2(
|
|
41669
|
-
if (
|
|
41670
|
-
refuse5("other-dataset", `${layoutRecordPath(dataset.sub)} belongs to another config folder (${
|
|
41671
|
-
const problem = recordFilesProblem(
|
|
43049
|
+
function requireRecordMatches2(record12, dataset) {
|
|
43050
|
+
if (record12.identity !== dataset.identity || record12.oldDir !== dataset.oldDir || record12.sub !== dataset.sub || record12.storageIds.local !== dataset.storageIds.local || record12.storageIds.vault !== dataset.storageIds.vault)
|
|
43051
|
+
refuse5("other-dataset", `${layoutRecordPath(dataset.sub)} belongs to another config folder (${record12.oldDir}), not ${dataset.oldDir}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [layoutRecordPath(dataset.sub), record12.oldDir, dataset.oldDir]);
|
|
43052
|
+
const problem = recordFilesProblem(record12, dataset);
|
|
41672
43053
|
if (problem)
|
|
41673
43054
|
markerUnreadable(dataset.sub, new Error(problem));
|
|
41674
43055
|
}
|
|
@@ -41731,10 +43112,10 @@ function chooseLegacy(paths, reasons2, log2, registration) {
|
|
|
41731
43112
|
};
|
|
41732
43113
|
}
|
|
41733
43114
|
async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
|
|
41734
|
-
const
|
|
41735
|
-
if (
|
|
43115
|
+
const record12 = await readRecord2(dataset.sub);
|
|
43116
|
+
if (record12?.phase !== "committed" || !allowPendingCleanup && record12.cleanup === "pending")
|
|
41736
43117
|
return "changed";
|
|
41737
|
-
requireRecordMatches2(
|
|
43118
|
+
requireRecordMatches2(record12, dataset);
|
|
41738
43119
|
const conflict = await checkStateHomeServing(stateHomeServingFiles(dataset.newPaths));
|
|
41739
43120
|
if (conflict) {
|
|
41740
43121
|
logger2.error("state-layout", conflict.message, {
|
|
@@ -41743,11 +43124,11 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
|
|
|
41743
43124
|
});
|
|
41744
43125
|
throw conflict;
|
|
41745
43126
|
}
|
|
41746
|
-
await warnReappearedMetadata(
|
|
43127
|
+
await warnReappearedMetadata(record12);
|
|
41747
43128
|
await registerHeld(join31(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
|
|
41748
43129
|
const layout = { kind: "state-home", dir: dataset.sub };
|
|
41749
43130
|
recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
|
|
41750
|
-
return { kind: "state-home", layout, dataset, record:
|
|
43131
|
+
return { kind: "state-home", layout, dataset, record: record12, moved };
|
|
41751
43132
|
}
|
|
41752
43133
|
async function admitFast(dataset, options, ctx) {
|
|
41753
43134
|
try {
|
|
@@ -41793,12 +43174,12 @@ async function readPointers(dataset) {
|
|
|
41793
43174
|
}
|
|
41794
43175
|
async function legacyHeld(dataset, options, ctx, reasons2, log2 = true) {
|
|
41795
43176
|
const pointed = await readPointers(dataset);
|
|
41796
|
-
const
|
|
41797
|
-
if (
|
|
41798
|
-
requireRecordMatches2(
|
|
41799
|
-
if (pointed && noMoveRecord(
|
|
43177
|
+
const record12 = await readRecord2(dataset.sub);
|
|
43178
|
+
if (record12)
|
|
43179
|
+
requireRecordMatches2(record12, dataset);
|
|
43180
|
+
if (pointed && noMoveRecord(record12))
|
|
41800
43181
|
markerUnreadable(dataset.sub);
|
|
41801
|
-
if (pointed || !noMoveRecord(
|
|
43182
|
+
if (pointed || !noMoveRecord(record12))
|
|
41802
43183
|
return "changed";
|
|
41803
43184
|
const registration = await registerLegacyHeld(dataset.oldDir, dataset.oldPaths, dataset.identity, options, ctx);
|
|
41804
43185
|
return chooseLegacy(dataset.oldPaths, reasons2, log2, registration);
|
|
@@ -41837,10 +43218,10 @@ async function recordedMovingJournal(journal, identity3, options) {
|
|
|
41837
43218
|
env: options.env ?? process.env,
|
|
41838
43219
|
home: options.home ?? homedir8()
|
|
41839
43220
|
});
|
|
41840
|
-
const
|
|
41841
|
-
if (
|
|
43221
|
+
const record12 = await readStateLayoutRecord(await canonicalPath(target2.dir));
|
|
43222
|
+
if (record12?.barriers.journal !== "present")
|
|
41842
43223
|
return;
|
|
41843
|
-
return movingJournalPath(journal,
|
|
43224
|
+
return movingJournalPath(journal, record12.attempt);
|
|
41844
43225
|
} catch {
|
|
41845
43226
|
return;
|
|
41846
43227
|
}
|
|
@@ -41964,20 +43345,20 @@ async function decideOpenCodeStateLayout(options) {
|
|
|
41964
43345
|
refuse5("other-dataset", `${sub} holds anthropic-auth state for ${marker.identity}, not for ${target2.identity}. Check OPENCODE_CONFIG_DIR and any symlink to the config folder.`, [sub, marker.identity, target2.identity]);
|
|
41965
43346
|
const pointed = await readPointers(dataset);
|
|
41966
43347
|
for (let round = 0;round < 3; round++) {
|
|
41967
|
-
const
|
|
41968
|
-
if (
|
|
41969
|
-
requireRecordMatches2(
|
|
41970
|
-
if (pointed && noMoveRecord(
|
|
43348
|
+
const record12 = await readRecord2(sub);
|
|
43349
|
+
if (record12)
|
|
43350
|
+
requireRecordMatches2(record12, dataset);
|
|
43351
|
+
if (pointed && noMoveRecord(record12))
|
|
41971
43352
|
markerUnreadable(sub);
|
|
41972
|
-
if (
|
|
43353
|
+
if (record12?.phase === "restore-staged")
|
|
41973
43354
|
restoreUnfinished(dataset.oldDir);
|
|
41974
|
-
if (
|
|
43355
|
+
if (record12?.phase === "committed" && (record12.cleanup === "done" || record12.cleanup === "kept")) {
|
|
41975
43356
|
const admitted = await admitFast(dataset, options, newContext());
|
|
41976
43357
|
if (admitted !== "changed")
|
|
41977
43358
|
return admitted;
|
|
41978
43359
|
continue;
|
|
41979
43360
|
}
|
|
41980
|
-
if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(
|
|
43361
|
+
if ((overrides.length || neverMove.length || !moveEnabled) && noMoveRecord(record12)) {
|
|
41981
43362
|
const ctx = newContext();
|
|
41982
43363
|
const reasons2 = stayReasons.length ? stayReasons : [RELOCATION_MOVE_DISABLED_REASON];
|
|
41983
43364
|
try {
|
|
@@ -42018,8 +43399,8 @@ async function decideOpenCodeStateLayout(options) {
|
|
|
42018
43399
|
} catch (error) {
|
|
42019
43400
|
if (!(error instanceof LockContentionError))
|
|
42020
43401
|
refuse5("io-failed", `anthropic-auth can't take the layout lock beside ${layoutRecordPath(sub)}: ${errorMessage(error)}`, [layoutRecordPath(sub)], error);
|
|
42021
|
-
const
|
|
42022
|
-
if (
|
|
43402
|
+
const record12 = await readRecord2(sub);
|
|
43403
|
+
if (record12?.phase === "committed" && (record12.cleanup === "done" || record12.cleanup === "kept")) {
|
|
42023
43404
|
const admitted = await admitFast(dataset, options, newContext());
|
|
42024
43405
|
if (admitted !== "changed")
|
|
42025
43406
|
return admitted;
|
|
@@ -42062,36 +43443,36 @@ async function ensureSubfolder(sub, fs3) {
|
|
|
42062
43443
|
}
|
|
42063
43444
|
}
|
|
42064
43445
|
async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
|
|
42065
|
-
const
|
|
42066
|
-
if (
|
|
42067
|
-
requireRecordMatches2(
|
|
42068
|
-
if (
|
|
43446
|
+
const record12 = await readRecord2(dataset.sub);
|
|
43447
|
+
if (record12)
|
|
43448
|
+
requireRecordMatches2(record12, dataset);
|
|
43449
|
+
if (record12?.phase === "restore-staged")
|
|
42069
43450
|
restoreUnfinished(dataset.oldDir);
|
|
42070
|
-
if (
|
|
43451
|
+
if (record12?.phase === "restoring" || record12?.phase === "restored" && record12.restore?.cleanup !== "done") {
|
|
42071
43452
|
if (overrides.length)
|
|
42072
43453
|
refuse5("restore-unfinished", `A restore of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}), or run ${RESTORE_LEGACY_COMMAND} again.`, [layoutRecordPath(dataset.sub)]);
|
|
42073
43454
|
await acquireHolderLocks(dataset, ctx);
|
|
42074
|
-
if (
|
|
42075
|
-
await discardAbandonedRestore(
|
|
43455
|
+
if (record12.phase === "restoring")
|
|
43456
|
+
await discardAbandonedRestore(record12, dataset, ctx);
|
|
42076
43457
|
else {
|
|
42077
43458
|
await syncObservedRestoreRecord(dataset, ctx);
|
|
42078
|
-
await finishRestoreRetirement(
|
|
43459
|
+
await finishRestoreRetirement(record12, dataset, ctx);
|
|
42079
43460
|
}
|
|
42080
43461
|
return "again";
|
|
42081
43462
|
}
|
|
42082
|
-
if (
|
|
43463
|
+
if (record12?.phase === "committed") {
|
|
42083
43464
|
try {
|
|
42084
43465
|
await syncCommitted(dataset, ctx);
|
|
42085
43466
|
} catch (error) {
|
|
42086
43467
|
refuse5("unsafe", `anthropic-auth could not make the move of its state to ${dataset.sub} durable, so it won't use either copy.`, [layoutRecordPath(dataset.sub)], error);
|
|
42087
43468
|
}
|
|
42088
43469
|
await acquireHolderLocks(dataset, ctx);
|
|
42089
|
-
if ((
|
|
43470
|
+
if ((record12.cleanup === "pending" || record12.cleanup === "conflict") && !overrides.length) {
|
|
42090
43471
|
const mark = ctx.stack.size;
|
|
42091
43472
|
try {
|
|
42092
43473
|
await drainCoalescedWrites(dataset);
|
|
42093
43474
|
await acquireDataLocks(dataset, ctx);
|
|
42094
|
-
await cleanupOldCopies(
|
|
43475
|
+
await cleanupOldCopies(record12, dataset, ctx);
|
|
42095
43476
|
} catch (error) {
|
|
42096
43477
|
if (error instanceof StateLayoutCrash)
|
|
42097
43478
|
throw error;
|
|
@@ -42105,13 +43486,13 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
|
|
|
42105
43486
|
const admitted2 = await admitHeld(dataset, options, ctx, false, true);
|
|
42106
43487
|
return admitted2 === "changed" ? "again" : admitted2;
|
|
42107
43488
|
}
|
|
42108
|
-
if (
|
|
43489
|
+
if (record12?.phase === "preparing") {
|
|
42109
43490
|
if (overrides.length)
|
|
42110
43491
|
refuse5("unsafe", `A move of anthropic-auth's state for ${dataset.oldDir} did not finish; start anthropic-auth without path overrides (${overrides.join(", ")}) to finish it.`, [layoutRecordPath(dataset.sub)]);
|
|
42111
43492
|
await acquireHolderLocks(dataset, ctx);
|
|
42112
43493
|
await drainCoalescedWrites(dataset);
|
|
42113
43494
|
await acquireDataLocks(dataset, ctx);
|
|
42114
|
-
await rollbackPreparing(
|
|
43495
|
+
await rollbackPreparing(record12, dataset, ctx);
|
|
42115
43496
|
return "again";
|
|
42116
43497
|
}
|
|
42117
43498
|
const stay = async (reasons2, log2 = true) => {
|
|
@@ -42396,8 +43777,8 @@ function applyRunnerTurnNotes(body, options) {
|
|
|
42396
43777
|
function applyTurnEndNotes(body, options = {}) {
|
|
42397
43778
|
if (!supportsTurnEndNote(body.model) || !Array.isArray(body.messages))
|
|
42398
43779
|
return 0;
|
|
42399
|
-
const
|
|
42400
|
-
if (!
|
|
43780
|
+
const allowed3 = new Set((options.tools ?? DEFAULT_TOOLS).map((name) => options.mapToolName?.(name) ?? name));
|
|
43781
|
+
if (!allowed3.size)
|
|
42401
43782
|
return 0;
|
|
42402
43783
|
const messages = body.messages;
|
|
42403
43784
|
const rewritten = [];
|
|
@@ -42419,7 +43800,7 @@ function applyTurnEndNotes(body, options = {}) {
|
|
|
42419
43800
|
if (visible.length < TURN_END_NOTE_MIN_VISIBLE_CHARACTERS)
|
|
42420
43801
|
continue;
|
|
42421
43802
|
const calls = assistant.content.filter((block) => isRecord20(block) && block.type === "tool_use");
|
|
42422
|
-
if (!calls.length || !calls.every((call2) =>
|
|
43803
|
+
if (!calls.length || !calls.every((call2) => allowed3.has(call2.name)))
|
|
42423
43804
|
continue;
|
|
42424
43805
|
const resultIds = new Set(results.content.filter((block) => isRecord20(block) && block.type === "tool_result").map((block) => block.tool_use_id));
|
|
42425
43806
|
if (!calls.every((call2) => typeof call2.id === "string" && resultIds.has(call2.id)))
|
|
@@ -42442,6 +43823,7 @@ export {
|
|
|
42442
43823
|
writerStamp,
|
|
42443
43824
|
writeNativeHostAuth,
|
|
42444
43825
|
writeDumpFile,
|
|
43826
|
+
withSessionCacheReportHandoff,
|
|
42445
43827
|
withNativeLock,
|
|
42446
43828
|
withAbortableFetch,
|
|
42447
43829
|
waitForNativeUsageDrain,
|
|
@@ -42521,6 +43903,9 @@ export {
|
|
|
42521
43903
|
requireAnthropicOAuthOrigin,
|
|
42522
43904
|
requestSignal,
|
|
42523
43905
|
requestGzipPadding,
|
|
43906
|
+
requestCacheLifetimeMs,
|
|
43907
|
+
reportSessionCacheWarmStopped,
|
|
43908
|
+
reportSessionCacheTouch,
|
|
42524
43909
|
reportRouting,
|
|
42525
43910
|
renameWithWindowsSharingRetry,
|
|
42526
43911
|
remapRequestBodyModel,
|
|
@@ -42536,6 +43921,7 @@ export {
|
|
|
42536
43921
|
recordPredatesBoot,
|
|
42537
43922
|
readWindowsOwnerOnly,
|
|
42538
43923
|
readStateLayoutMarker,
|
|
43924
|
+
readSessionCachePolicy,
|
|
42539
43925
|
readRelocationPointer,
|
|
42540
43926
|
readNativeMigrationJournal,
|
|
42541
43927
|
readNativeHostAuthKind,
|
|
@@ -42636,7 +44022,7 @@ export {
|
|
|
42636
44022
|
legacyCacheKeepStoreDirectory,
|
|
42637
44023
|
killswitchRetryAfterSeconds,
|
|
42638
44024
|
killswitchPassesPolicy,
|
|
42639
|
-
isWithinCacheKeepWindow,
|
|
44025
|
+
isWithinCacheKeepWindow2 as isWithinCacheKeepWindow,
|
|
42640
44026
|
isVaultHosted,
|
|
42641
44027
|
isValidBillingPromptId,
|
|
42642
44028
|
isValidApiBaseURL,
|
|
@@ -42863,6 +44249,7 @@ export {
|
|
|
42863
44249
|
askRouting,
|
|
42864
44250
|
applyTurnEndNotes,
|
|
42865
44251
|
applyThinkingBindingControls,
|
|
44252
|
+
applySessionCacheTtl,
|
|
42866
44253
|
applyRunnerTurnNotes,
|
|
42867
44254
|
applyMidConversationOutputConfig,
|
|
42868
44255
|
applyCustomHeaders,
|
|
@@ -42977,10 +44364,11 @@ export {
|
|
|
42977
44364
|
ClaudeUnsupportedAccessError,
|
|
42978
44365
|
ClaudeOAuthRefreshError,
|
|
42979
44366
|
ClaudeCodeFirstUserTextTracker,
|
|
44367
|
+
CacheKeepWarmRefusal,
|
|
42980
44368
|
CacheKeepStore,
|
|
42981
44369
|
CacheKeepSessionRegistry,
|
|
42982
44370
|
CacheKeepPrewarmError,
|
|
42983
|
-
CacheKeepManager,
|
|
44371
|
+
CacheKeepManager2 as CacheKeepManager,
|
|
42984
44372
|
CUSTODY_TOMBSTONE_PREFIX,
|
|
42985
44373
|
CUSTODY_HANDLE_PATTERN,
|
|
42986
44374
|
CODE_CALLBACK_URL,
|