UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

316 lines (315 loc) • 12 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import { i as getPluginRegistryForContext } from "./gateway-request-scope-BvvDhs5D.mjs"; import { d as getActivePluginRegistryWorkspaceDirFromStateCore, l as normalizeProviderModelIdWithRuntime, o as normalizeModelRef } from "./model-ref-shared-DqE2RqZv.mjs"; import { n as getPluginRegistryState } from "./runtime-state-DVrhXeqI.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { r as resolveAgentConfig, s as resolveAgentModelConfigForRuntime } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as resolvePluginControlPlaneFingerprint } from "./plugin-control-plane-context-BmY6xICT.mjs"; import { i as getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot-H0TP3PFt.mjs"; import { o as resolveAgentModelFallbackValues, s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs"; import { t as hasUtilityModelSeparationMigrationMarker } from "./utility-model-separation-migration-BwGu2RZI.mjs"; import { i as DEFAULT_PROVIDER, n as DEFAULT_MODEL } from "./defaults-BWyoTPqn.mjs"; import { t as getPluginRuntimeGenerationRegistry } from "./generation-state-CbpjEoxA.mjs"; import { O as allowsPluginModelNormalization, b as readUtilityModelSetting, h as resolveConfiguredModelRef, i as buildModelAliasIndex, k as hasExactConfiguredProviderModel, y as resolveModelRefFromString } from "./model-selection-shared-9Kz63Hhm.mjs"; import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs"; import { u as isFailoverError } from "./error-BCRqSFIY.mjs"; import { n as resolveConfiguredModelFallbacks, r as resolveModelAliasFromPair } from "./model-selection-resolve-CyMfPqoi.mjs"; import { i as resolveContextTokensForModelFromCache } from "./context-resolution-DOFMNmJZ.mjs"; import { n as isLikelyContextOverflowError } from "./context-overflow-C7ex88b9.mjs"; //#region src/agents/embedded-agent-helpers/context-overflow-observation.ts function isCompactionFailureError(e) { if (!e) return false; const t = normalizeLowercaseStringOrEmpty(e); return (t.includes("summarization failed") || t.includes("compaction")) && (isLikelyContextOverflowError(e) || t.includes("context overflow")); } const OBSERVED_OVERFLOW_TOKEN_PATTERNS = [ /input length(?:\s+and\s+max_tokens)?\s+exceed\s+context(?:\s+limit|\s+window)?\s*\(i\.e\s*([\d,]+)\s*\+\s*([\d,]+)\s*>\s*[\d,]+\)/i, /input length\s+and\s+`max_tokens`\s+exceed\s+context\s+limit:\s*([\d,]+)\s*\+\s*([\d,]+)\s*>\s*[\d,]+/i, /prompt is too long:\s*([\d,]+)\s+tokens\s*>\s*[\d,]+\s+maximum/i, /prompt is too long:\s*([\d,]+)\s*,\s*model maximum context length\s*:\s*[\d,]+/i, /requested\s+([\d,]+)\s+tokens/i, /token limit\s*:\s*[\d,]+\s*\(requested\s*:\s*([\d,]+)\)/i, /resulted in\s+([\d,]+)\s+tokens/i ]; function extractObservedOverflowTokenCount(e) { if (!e) return; for (const t of OBSERVED_OVERFLOW_TOKEN_PATTERNS) { const n = e.match(t)?.slice(1).map((e) => { const t = e.replaceAll(",", ""); return t ? Number(t) : NaN; }); if (n?.every((e, t) => Number.isFinite(e) && (t === 0 ? e > 0 : e >= 0))) return Math.floor(n.reduce((e, t) => e + t, 0)); } } //#endregion //#region src/agents/model-fallback-candidates.ts /** Resolves ordered model and image fallback candidate chains. */ const MAX_FALLBACK_CANDIDATE_CACHE_ENTRIES = 256; const fallbackCandidateCache = /* @__PURE__ */ new Map(); const fallbackContextIds = /* @__PURE__ */ new WeakMap(); let nextFallbackContextId = 0; const log = createSubsystemLogger("model-selection"); /** Prefer known headroom without dropping operator-selected models with incomplete metadata. */ function preferContextFitFallbackCandidates(e) { if (!isFailoverError(e.error) || e.error.reason !== "context_overflow" || e.error.requestSizeCeiling) return e.candidates; const t = e.candidates[e.failedIndex]; if (!t) return e.candidates; const contextTokens = (t) => resolveContextTokensForModelFromCache({ cfg: e.cfg, ...t, allowUnscopedModelLookup: false }); const n = contextTokens(t); const r = extractObservedOverflowTokenCount(e.error.rawError ?? e.error.message) ?? (n === void 0 ? void 0 : n + 1); if (r === void 0) return e.candidates; const i = e.candidates.slice(e.failedIndex + 1).map((e) => ({ candidate: e, fits: (contextTokens(e) ?? 0) >= r })).toSorted((e, t) => Number(t.fits) - Number(e.fits)).map(({ candidate: e }) => e); return [...e.candidates.slice(0, e.failedIndex + 1), ...i]; } function createModelCandidateCollector() { const e = /* @__PURE__ */ new Set(); const t = []; const addCandidate = (n, r, i) => { if (!n.provider || !n.model) return; const a = JSON.stringify([n.provider, n.model]); if (e.has(a)) return; e.add(a); t.push({ ...n, routeOrigin: r, routeResolution: i }); }; return { candidates: t, addCandidate }; } function resolveImageFallbackCandidates(e) { const t = resolveAgentModelPrimaryValue(e.cfg?.agents?.defaults?.imageModel); let n = DEFAULT_PROVIDER; if (t?.trim()) { const r = buildModelAliasIndex({ cfg: e.cfg ?? {}, defaultProvider: DEFAULT_PROVIDER, manifestPlugins: e.manifestPlugins }); n = resolveModelRefFromString({ cfg: e.cfg, raw: t, defaultProvider: "openai", aliasIndex: r, manifestPlugins: e.manifestPlugins })?.ref.provider || "openai"; } const r = buildModelAliasIndex({ cfg: e.cfg ?? {}, defaultProvider: n, manifestPlugins: e.manifestPlugins }); const { candidates: i, addCandidate: a } = createModelCandidateCollector(); const addRaw = (t, i) => { const o = resolveModelRefFromString({ cfg: e.cfg, raw: t, defaultProvider: n, aliasIndex: r, manifestPlugins: e.manifestPlugins }); if (!o) { log.warn(`Unresolved image model "${sanitizeForLog(t)}"; skipped ${i} candidate.`); return; } a(o.ref, i, "resolved"); }; if (e.modelOverride?.trim()) addRaw(e.modelOverride, "requested"); else if (t?.trim()) addRaw(t, "configured-primary"); const o = resolveAgentModelFallbackValues(e.cfg?.agents?.defaults?.imageModel); for (const e of o) addRaw(e, "configured-fallback"); return i; } function resolveModelCandidateChain(e) { const { cacheKey: t, manifestPlugins: n } = resolveFallbackCandidateContext(e); const r = t ? fallbackCandidateCache.get(t) : void 0; if (r) return r; const i = resolveFallbackCandidatesUncached({ ...e, manifestPlugins: n }); if (t) { fallbackCandidateCache.set(t, i); pruneMapToMaxSize(fallbackCandidateCache, MAX_FALLBACK_CANDIDATE_CACHE_ENTRIES); } return i; } function getFallbackContextId(e) { const t = fallbackContextIds.get(e); if (t !== void 0) return t; const n = nextFallbackContextId++; fallbackContextIds.set(e, n); return n; } function resolveFallbackCandidateContext(e) { if (e.manifestPlugins !== void 0) return { cacheKey: null, manifestPlugins: e.manifestPlugins }; const t = getActivePluginRegistryWorkspaceDirFromStateCore(); const n = process.env; const r = getCurrentPluginMetadataSnapshot({ env: n, workspaceDir: t, allowWorkspaceScopedSnapshot: true }); const i = getCurrentPluginMetadataSnapshot({ config: e.cfg, env: n, workspaceDir: t, allowWorkspaceScopedSnapshot: true, requireDefaultDiscoveryContext: e.cfg === void 0 }); const a = getPluginRegistryState(); if (a?.registrationContext) return { cacheKey: null, manifestPlugins: i }; const o = getPluginRuntimeGenerationRegistry() ?? getPluginRegistryForContext(); const s = e.cfg && e.agentId ? resolveAgentConfig(e.cfg, e.agentId) : void 0; return { cacheKey: JSON.stringify({ agentId: e.agentId, agentModel: resolveAgentModelConfigForRuntime(s), agentModels: s?.models, provider: e.provider, model: e.model, requestedRouteResolution: e.requestedRouteResolution, allowPluginNormalization: e.allowPluginNormalization, fallbacksOverride: e.fallbacksOverride, agentsDefaultsModel: e.cfg?.agents?.defaults?.model, agentsDefaultsModels: e.cfg?.agents?.defaults?.models, utilityModel: e.cfg ? readUtilityModelSetting(e.cfg, e.agentId) : void 0, utilityModelSeparation: hasUtilityModelSeparationMigrationMarker(e.cfg), modelProviders: resolveFallbackCandidateModelProviderCacheParts(e.cfg), pluginControlPlane: resolvePluginControlPlaneFingerprint({ config: e.cfg, env: n, workspaceDir: t }), pluginMetadataFingerprint: r?.configFingerprint ?? null, pluginMetadataIdentity: r ? getFallbackContextId(r) : null, normalizationMetadataIdentity: i ? getFallbackContextId(i) : null, pluginRegistryIdentity: o ? getFallbackContextId(o) : null, pluginRegistryKey: a?.key ?? null, pluginRegistryVersion: a?.activeVersion ?? null, pluginWorkspaceDir: t ?? null }), manifestPlugins: i }; } function resolveFallbackCandidateModelProviderCacheParts(e) { const t = e?.models?.providers; if (!t) return; return Object.entries(t).map(([e, t]) => ({ providerId: e, api: t.api, models: t.models?.map((e) => e.id) ?? [] })); } function resolveFallbackCandidatesUncached(e) { const t = e.cfg ? resolveConfiguredModelRef({ cfg: e.cfg, agentId: e.agentId, defaultProvider: DEFAULT_PROVIDER, defaultModel: DEFAULT_MODEL, allowPluginNormalization: false, manifestPlugins: e.manifestPlugins }) : null; const n = t?.provider ?? "openai"; const r = t?.model ?? "gpt-6-astra"; const i = normalizeOptionalString(e.provider) || n; const a = normalizeOptionalString(e.model) || r; const o = e.allowPluginNormalization !== false && e.cfg?.plugins?.enabled !== false; const s = e.requestedRouteResolution ?? "raw"; const c = s === "resolved" ? { provider: normalizeProviderId(i), model: a } : normalizeModelRef(i, a, { allowPluginNormalization: e.allowPluginNormalization !== false && allowsPluginModelNormalization({ cfg: e.cfg, provider: i, model: a }), manifestPlugins: e.manifestPlugins }); const l = buildModelAliasIndex({ cfg: e.cfg ?? {}, agentId: e.agentId, defaultProvider: n, allowPluginNormalization: o, manifestPlugins: e.manifestPlugins }); const { candidates: u, addCandidate: d } = createModelCandidateCollector(); let f = c; const p = hasExactConfiguredProviderModel({ cfg: e.cfg, provider: c.provider, model: c.model }) || l.byKey.has(modelKey(c.provider, c.model)); if (s === "raw" && !p) f = resolveModelAliasFromPair({ cfg: e.cfg, agentId: e.agentId, provider: i, model: a, defaultProvider: n, aliasIndex: l, allowPluginNormalization: e.allowPluginNormalization !== false && allowsPluginModelNormalization({ cfg: e.cfg, provider: i, model: a }), manifestPlugins: e.manifestPlugins }) ?? c; d(f, "requested", e.manifestPlugins !== void 0 ? "resolved" : s); const m = e.fallbacksOverride !== void 0 ? e.fallbacksOverride : e.cfg ? resolveConfiguredModelFallbacks({ cfg: e.cfg, agentId: e.agentId }) : []; for (const t of m) { const r = resolveModelRefFromString({ cfg: e.cfg, agentId: e.agentId, raw: t, defaultProvider: n, aliasIndex: l, allowPluginNormalization: o, manifestPlugins: e.manifestPlugins }); if (!r) continue; d(r.ref, "configured-fallback", "resolved"); } if (e.fallbacksOverride === void 0 && t?.provider && t.model) { let n = t.model; if (o && allowsPluginModelNormalization({ cfg: e.cfg, ...t })) n = normalizeProviderModelIdWithRuntime({ provider: t.provider, context: { provider: t.provider, modelId: n } }) ?? n; d({ ...t, model: n }, "configured-primary", "resolved"); } return u; } //#endregion export { isCompactionFailureError as a, extractObservedOverflowTokenCount as i, resolveImageFallbackCandidates as n, resolveModelCandidateChain as r, preferContextFitFallbackCandidates as t };