UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

189 lines (188 loc) • 7.54 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs"; import "./config-CMA-J084.mjs"; import { a as resolveModelContextTokenProjectionFromCache, c as replaceContextWindowCaches, l as replaceDiscoveredContextTokenCache, o as getContextWindowCaches, s as providerContextTokenCacheKey, t as resolveAnthropicFixedContextWindow } from "./context-resolution-DOFMNmJZ.mjs"; import { setImmediate } from "node:timers/promises"; //#region src/agents/context-runtime-state.ts const CONTEXT_WINDOW_RUNTIME_STATE_KEY = Symbol.for("openclaw.contextWindowRuntimeState"); const globalState = globalThis; /** Shared mutable state for context-window resolution and model discovery. */ const CONTEXT_WINDOW_RUNTIME_STATE = globalState[CONTEXT_WINDOW_RUNTIME_STATE_KEY] ||= { loadPromise: null, configuredConfig: void 0 }; /** Invalidate prepared context metadata while a replacement load is staged. */ function beginContextWindowCacheRefresh() { CONTEXT_WINDOW_RUNTIME_STATE.loadPromise = null; CONTEXT_WINDOW_RUNTIME_STATE.configuredConfig = void 0; } //#endregion //#region src/agents/context.ts const CONTEXT_PROJECTION_BATCH_SIZE = 512; function cacheMinimum(e, t, n) { const r = e.get(t); if (r === void 0 || n < r) e.set(t, n); } function contextModelKeys(e, t) { const n = [e]; if (t === void 0) return n; n.push(providerContextTokenCacheKey(t, e)); const r = e.indexOf("/"); const i = r > 0 ? normalizeProviderId(e.slice(0, r)) : ""; const a = r > 0 ? e.slice(r + 1).trim() : ""; if (t && i === t && a) n.push(providerContextTokenCacheKey(t, a)); return n; } function applyDiscoveredContextWindow(e, t) { if (!t.id) return; const n = typeof t.contextTokens === "number" ? Math.trunc(t.contextTokens) : typeof t.contextWindow === "number" ? Math.trunc(t.contextWindow) : void 0; const r = resolveDiscoveredAnthropicFixedContextWindow(t) ?? n; if (!r || r <= 0) return; const i = t.provider ? normalizeProviderId(t.provider) : ""; for (const n of contextModelKeys(t.id, i || void 0)) cacheMinimum(e, n, r); } function* configuredModels(e) { for (const [t, n] of Object.entries(e?.providers ?? {})) for (const e of n?.models ?? []) yield { providerId: t, model: e }; } function applyConfiguredContextWindow(e) { const { id: t, contextTokens: n, contextWindow: r } = e.model; const i = n && n > 0 ? { cache: e.cache, value: n } : r && r > 0 ? { cache: e.windowCache, value: r } : void 0; if (!t || !i) return; for (const n of contextModelKeys(t, normalizeProviderId(e.providerId))) i.cache.set(n, i.value); } function resolveDiscoveredAnthropicFixedContextWindow(e) { const t = e.provider ? normalizeProviderId(e.provider) : void 0; if (t) return resolveAnthropicFixedContextWindow(t, e.id); const n = normalizeLowercaseStringOrEmpty(e.id); const r = n.indexOf("/"); if (r < 0) return; const i = normalizeProviderId(n.slice(0, r)); const a = n.slice(r + 1); return i === "claude-cli" ? resolveAnthropicFixedContextWindow(i, a) : void 0; } async function projectModels(e, t, n = 0) { let r = n; for (const n of [t.entries, t.staticEntries ?? []]) for (const t of n) { applyDiscoveredContextWindow(e, t); r += 1; if (r % CONTEXT_PROJECTION_BATCH_SIZE === 0) await setImmediate(); } } const loadPreparedModelCatalogRuntime = () => import("./prepared-model-catalog-guV7T9CV.mjs"); function primeConfiguredContextWindowsFromConfig(e) { const t = getContextWindowCaches(); for (const n of configuredModels(e.models)) applyConfiguredContextWindow({ cache: t.configuredTokenCache, windowCache: t.contextWindowCache, ...n }); CONTEXT_WINDOW_RUNTIME_STATE.configuredConfig = e; return e; } function primeConfiguredContextWindows() { if (CONTEXT_WINDOW_RUNTIME_STATE.configuredConfig) return CONTEXT_WINDOW_RUNTIME_STATE.configuredConfig; const e = getRuntimeConfigSnapshot(); return e ? primeConfiguredContextWindowsFromConfig(e) : void 0; } function ensureContextWindowCacheLoaded() { if (CONTEXT_WINDOW_RUNTIME_STATE.loadPromise) return CONTEXT_WINDOW_RUNTIME_STATE.loadPromise; const e = primeConfiguredContextWindows(); if (!e) return Promise.resolve(); const t = Promise.resolve().then(async () => { let n = /* @__PURE__ */ new Map(); try { const { loadPreparedModelCatalogOwnerSnapshot: t } = await loadPreparedModelCatalogRuntime(); const r = await t({ config: e, readOnly: true }); const i = /* @__PURE__ */ new Map(); await projectModels(i, r.modelCatalog); n = i; } catch {} if (CONTEXT_WINDOW_RUNTIME_STATE.loadPromise === t) replaceDiscoveredContextTokenCache(n); }).catch(() => {}); CONTEXT_WINDOW_RUNTIME_STATE.loadPromise = t; return t; } /** * Reuse the Gateway's published catalog generation. Omitting the Gateway binding * falls through to a read-only owner whose key hashes the full model config. */ async function prewarmContextWindowCacheAfterReady(e) { beginContextWindowCacheRefresh(); if (e.isCancelled?.()) return; let t = false; const n = Promise.resolve().then(async () => { const { getPublishedPreparedModelCatalogOwnerSnapshot: n } = await loadPreparedModelCatalogRuntime(); const r = n({ config: e.config, allowGatewaySubagentBinding: true }); if (!r) throw new Error("published Gateway model catalog owner is unavailable"); const i = { configuredTokenCache: /* @__PURE__ */ new Map(), discoveredTokenCache: /* @__PURE__ */ new Map(), contextWindowCache: /* @__PURE__ */ new Map() }; let a = 0; for (const e of configuredModels(r.config.models)) { applyConfiguredContextWindow({ cache: i.configuredTokenCache, windowCache: i.contextWindowCache, ...e }); a += 1; if (a % CONTEXT_PROJECTION_BATCH_SIZE === 0) await setImmediate(); } await projectModels(i.discoveredTokenCache, r.modelCatalog, a); if (e.isCancelled?.()) return; replaceContextWindowCaches(i); CONTEXT_WINDOW_RUNTIME_STATE.configuredConfig = r.config; t = true; }).catch(() => {}).finally(() => { if (!t) CONTEXT_WINDOW_RUNTIME_STATE.loadPromise = null; }); CONTEXT_WINDOW_RUNTIME_STATE.loadPromise = n; await n; } /** Restore configured context limits without acquiring a model catalog. */ function resetContextWindowCache(e) { beginContextWindowCacheRefresh(); const t = getContextWindowCaches(); t.configuredTokenCache.clear(); t.contextWindowCache.clear(); primeConfiguredContextWindowsFromConfig(e); } /** Replace cached model context metadata for the active runtime configuration. */ async function refreshContextWindowCache(e) { resetContextWindowCache(e); await ensureContextWindowCacheLoaded(); } function prepareContextWindowCache(e) { if (e?.skipRuntimeConfigLoad) return; if (e?.allowAsyncLoad === false) primeConfiguredContextWindows(); else ensureContextWindowCacheLoaded(); } function resolveContextTokensForModel(e) { return resolveModelContextTokenProjection(e).contextTokens; } function resolveModelContextTokenProjection(e) { prepareContextWindowCache({ allowAsyncLoad: e.allowAsyncLoad, skipRuntimeConfigLoad: Boolean(e.cfg) || e.allowCacheLookup === false }); return resolveModelContextTokenProjectionFromCache(e); } //#endregion export { resolveContextTokensForModel as a, resetContextWindowCache as i, prewarmContextWindowCacheAfterReady as n, resolveModelContextTokenProjection as o, refreshContextWindowCache as r, ensureContextWindowCacheLoaded as t };