UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

476 lines (475 loc) • 18.7 kB
import { c as normalizeOptionalLowercaseString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { a as resolveModelExtraParamSources, o as sanitizeExtraParamsRecord, r as resolveAliasedParamValue } from "./model-extra-params-D2Glrj-b.mjs"; import { n as ensureProviderRuntimePluginHandle, r as getModelProviderRuntimePluginHandle } from "./provider-hook-runtime-CNiG8a3j.mjs"; import { t as log } from "./logger-DgCpB-Fs.mjs"; import { i as streamSimple } from "./stream-DEhzhrZ_.mjs"; import { r as isNativeWebSearchAllowedByToolPolicy } from "./codex-native-web-search-core-Crp3R8rN.mjs"; import { t as streamWithPayloadPatch } from "./stream-payload-utils-CdDjgfPC.mjs"; import { c as createOpenAICompletionsStrictMessageKeysWrapper, f as createOpenAIResponsesContextManagementWrapper, l as createOpenAICompletionsToolsCompatWrapper, m as createOpenAIStringContentWrapper, r as createOpenRouterSystemCacheWrapper, t as OPENROUTER_RESPONSE_CACHE_TTL_KEYS, x as createMinimaxThinkingDisabledWrapper } from "./proxy-DznATSAw.mjs"; import { r as createOpenAICompletionsPayloadPolicyWrapper } from "./ai-transport-runtime-host-BMz3-0Om.mjs"; import { f as createGoogleThinkingPayloadWrapper, l as createDeepSeekV4OpenAICompatibleThinkingWrapper, y as createThinkingOnlyFinalTextWrapper } from "./provider-stream-shared-BJrJjQd2.mjs"; import { canonicalizeMaxTokensParam, detectOpenAICompletionsCompat, resolveMaxTokensParam, resolveOpenAICompletionsCompat, resolveOpenAIPromptCacheKeySupport } from "@openclaw/ai/transports"; //#region src/llm/providers/stream-wrappers/moonshot.ts /** Detects SiliconFlow Pro models that require thinking=null instead of thinking="off". */ function shouldApplySiliconFlowThinkingOffCompat(e) { return e.provider === "siliconflow" && e.thinkingLevel === "off" && e.modelId.startsWith("Pro/"); } /** Wraps Moonshot-compatible requests to rewrite SiliconFlow thinking-off payloads. */ function createSiliconFlowThinkingWrapper(e) { const t = e ?? streamSimple; return (e, n, r) => streamWithPayloadPatch(t, e, n, r, (e) => { if (e.thinking === "off") e.thinking = null; }); } //#endregion //#region src/llm/providers/stream-wrappers/anthropic-family-cache-semantics.ts /** Matches Application Inference Profile ARNs across all AWS partitions with Bedrock. */ const BEDROCK_APP_INFERENCE_PROFILE_ARN_RE = /^arn:aws(-cn|-us-gov)?:bedrock:/; function isAnthropicBedrockModel(e, t = false) { const n = normalizeLowercaseStringOrEmpty(e); if (n.includes("anthropic.claude") || n.includes("anthropic/claude")) return true; if (BEDROCK_APP_INFERENCE_PROFILE_ARN_RE.test(n) && n.includes(":application-inference-profile/")) { const e = n.split(":application-inference-profile/")[1] ?? ""; return t || e.includes("claude"); } return false; } function isAnthropicFamilyCacheTtlEligible(e) { const t = normalizeOptionalLowercaseString(e.provider); if (t === "anthropic" || t === "anthropic-vertex") return true; if (t === "amazon-bedrock") return isAnthropicBedrockModel(e.modelId); return e.modelApi === "anthropic-messages"; } function resolveAnthropicCacheRetentionFamily(e) { const t = normalizeOptionalLowercaseString(e.provider); if (t === "anthropic" || t === "anthropic-vertex") return "anthropic-direct"; if (t === "amazon-bedrock" && e.hasExplicitCacheConfig && typeof e.modelId === "string") { if (isAnthropicBedrockModel(e.modelId, true)) return "anthropic-bedrock"; } if (t !== "amazon-bedrock" && e.hasExplicitCacheConfig && e.modelApi === "anthropic-messages") return "custom-anthropic-api"; } //#endregion //#region src/agents/embedded-agent-runner/prompt-cache-retention.ts /** * Resolves provider/model prompt-cache retention behavior. */ function resolveExplicitCachedContent(e) { return (typeof e?.cachedContent === "string" ? e.cachedContent : typeof e?.cached_content === "string" ? e.cached_content : void 0)?.trim() || void 0; } function parseCacheRetention(e) { return e === "none" || e === "short" || e === "long" ? e : void 0; } function isGooglePromptCacheEligible(e) { if (e.modelApi !== "google-generative-ai") return false; const t = normalizeLowercaseStringOrEmpty(e.modelId); return t.startsWith("gemini-2.5") || t.startsWith("gemini-3"); } function resolveCacheRetention(e, t, n, r, i, a) { const o = e?.cacheRetention !== void 0 || e?.cacheControlTtl !== void 0; const s = resolveAnthropicCacheRetentionFamily({ provider: t, modelApi: n, modelId: r, hasExplicitCacheConfig: o }); const c = (n === "openai-responses" || n === "openai-chatgpt-responses" || n === "openai-completions") && resolveOpenAIPromptCacheKeySupport({ provider: t, api: n, baseUrl: a, compat: i }); const l = isGooglePromptCacheEligible({ modelApi: n, modelId: r }); const u = i?.supportsPromptCacheKey === true || i?.cacheControlFormat === "anthropic"; if (!s && !l && !c && !u && !(n === "bedrock-converse-stream")) return; const d = parseCacheRetention(e?.cacheRetention); if (d) return d; const f = e?.cacheControlTtl; if (f === "5m" && (s || l)) return "short"; if (f === "1h" && (s || l)) return "long"; return s === "anthropic-direct" ? "short" : void 0; } //#endregion //#region src/agents/embedded-agent-runner/extra-params.ts function requireBaseStreamFn(e) { if (!e) throw new Error("Cannot apply stream policy without a lifecycle-owned base stream."); return e; } const REQUEST_SCOPED_EXTRA_PARAM_KEYS = /* @__PURE__ */ new Set([ "response_format", "responseFormat", "stop" ]); const GPT_PARALLEL_TOOL_CALLS_APIS = /* @__PURE__ */ new Set([ "openai-completions", "openai-responses", "openai-chatgpt-responses", "azure-openai-responses" ]); function resolveExtraParams(e) { const { defaultParams: t, modelParams: n, agentModelParams: r, agentParams: i } = resolveModelExtraParamSources({ config: e.cfg, provider: e.provider, modelId: e.modelId, agentId: e.agentId }); const a = [ t, n, r, i ]; const o = Object.assign({}, ...a); canonicalizeExtraParamAlias(o, a, ["serviceTier", "service_tier"]); canonicalizeExtraParamAlias(o, a, ["fastMode", "fast_mode"]); canonicalizeExtraParamAlias(o, a, ["parallel_tool_calls", "parallelToolCalls"]); canonicalizeExtraParamAlias(o, [ n, r, i ], ["text_verbosity", "textVerbosity"]); canonicalizeExtraParamAlias(o, a, ["response_format", "responseFormat"]); canonicalizeMaxTokensParam({ merged: o, sources: a }); canonicalizeExtraParamAlias(o, a, ["cached_content", "cachedContent"], "cachedContent"); if (e.provider === "openrouter") canonicalizeOpenRouterResponseCacheParams(o, a); applyDefaultOpenAIGptRuntimeParams(e, o); return Object.keys(o).length > 0 ? o : void 0; } function resolveSupportedTransport(e) { return e === "sse" || e === "websocket" || e === "websocket-cached" || e === "auto" ? e : void 0; } function resolvePreparedExtraParams(e) { const t = resolveExtraParams(e); const n = stripRequestScopedExtraParams(sanitizeExtraParamsOverride(e.extraParamsOverride)); const r = { ...sanitizeExtraParamsRecord(t), ...n }; canonicalizeExtraParamAlias(r, [t, n], ["serviceTier", "service_tier"]); canonicalizeExtraParamAlias(r, [t, n], ["fastMode", "fast_mode"]); canonicalizeMaxTokensParam({ merged: r, sources: [t, n] }); canonicalizeExtraParamAlias(r, [t, n], ["cached_content", "cachedContent"], "cachedContent"); if (e.provider === "openrouter") canonicalizeOpenRouterResponseCacheParams(r, [t, n]); const { plugin: i } = ensureProviderRuntimePluginHandle({ provider: e.provider, modelId: e.modelId, config: e.transportConfig ?? e.cfg, workspaceDir: e.workspaceDir, runtimeHandle: e.providerRuntimeHandle ?? getModelProviderRuntimePluginHandle(e.model) }); const a = { config: e.transportConfig ?? e.cfg, agentDir: e.agentDir, workspaceDir: e.workspaceDir, provider: e.provider, modelId: e.modelId, model: e.model, thinkingLevel: e.thinkingLevel, auth: e.auth }; const o = i?.prepareExtraParams?.({ ...a, extraParams: r }) ?? r; const s = i?.extraParamsForTransport?.({ ...a, extraParams: o, transport: e.resolvedTransport ?? resolveSupportedTransport(o.transport) })?.patch; const c = s ? { ...o, ...s } : o; canonicalizeMaxTokensParam({ merged: c, sources: [o, s ?? void 0] }); return c; } function sanitizeExtraParamsOverride(e) { return e && Object.keys(e).length > 0 ? sanitizeExtraParamsRecord(Object.fromEntries(Object.entries(e).filter(([, e]) => e !== void 0))) : void 0; } function stripRequestScopedExtraParams(e) { if (!e) return; const t = Object.fromEntries(Object.entries(e).filter(([e]) => !REQUEST_SCOPED_EXTRA_PARAM_KEYS.has(e))); return Object.keys(t).length > 0 ? t : void 0; } function applyDefaultOpenAIGptRuntimeParams(e, t) { if (e.provider !== "openai" || !/^gpt-5(?:[.-]|$)/i.test(e.modelId)) return; for (const [e, n, r] of [[ "parallel_tool_calls", "parallelToolCalls", true ], [ "text_verbosity", "textVerbosity", "low" ]]) if (!Object.hasOwn(t, e) && !Object.hasOwn(t, n)) t[e] = r; } function resolveAgentTransportOverride(e) { const t = e.settingsManager.getGlobalSettings(); if (Object.hasOwn(t, "transport")) return; return resolveSupportedTransport(e.effectiveExtraParams?.transport); } function resolveExplicitSettingsTransport(e) { const t = e.settingsManager.getGlobalSettings(); if (!Object.hasOwn(t, "transport")) return; return resolveSupportedTransport(e.sessionTransport); } function normalizeStopSequences(e) { const t = typeof e === "string" ? [e] : Array.isArray(e) ? e : void 0; if (!t) return; const n = t.filter((e) => typeof e === "string" && e.length > 0); return n.length > 0 ? n : void 0; } function createStreamFnWithExtraParams(e, t, n) { if (!t || Object.keys(t).length === 0) return; if (Object.hasOwn(t, "cacheRetention") && parseCacheRetention(t.cacheRetention) === void 0) log.warn("ignoring invalid cacheRetention param; expected \"none\", \"short\", or \"long\""); const r = {}; if (t.promptCacheTtl === "30m" || t.promptCacheTtl === "12h") r.promptCacheTtl = t.promptCacheTtl; else if (t.promptCacheTtl !== void 0) log.warn("ignoring invalid promptCacheTtl param; expected \"30m\" or \"12h\""); if (typeof t.temperature === "number") r.temperature = t.temperature; if (typeof t.streaming === "boolean") r.streaming = t.streaming; const i = resolveMaxTokensParam(t); if (i !== void 0) r.maxTokens = i; const a = resolveAliasedParamValue([t], ["response_format", "responseFormat"]); if (a && typeof a === "object" && !Array.isArray(a)) r.responseFormat = a; const o = resolveSupportedTransport(t.transport); if (o) r.transport = o; else if (t.transport != null) { const e = typeof t.transport === "string" ? t.transport : typeof t.transport; log.warn(`ignoring invalid transport param: ${e}`); } const s = resolveExplicitCachedContent(t); if (s) r.cachedContent = s; for (const e of [ ["topP", "top_p"], ["frequencyPenalty", "frequency_penalty"], ["presencePenalty", "presence_penalty"] ]) { const n = resolveAliasedParamValue([t], e); if (typeof n === "number") r[e[0]] = n; } if (typeof t.seed === "number") r.seed = t.seed; const c = normalizeStopSequences(t.stop); if (c) r.stop = c; const resolveModelCacheRetention = (e) => resolveCacheRetention(t, n, typeof e?.api === "string" ? e.api : void 0, typeof e?.id === "string" ? e.id : void 0, e?.api === "openai-completions" ? resolveOpenAICompletionsCompat(e) : e?.compat, e?.baseUrl); const l = requireBaseStreamFn(e); return (e, t, n) => { const i = resolveModelCacheRetention(e); if (Object.keys(r).length === 0 && !i) return l(e, t, n); const a = n?.cacheRetention ?? i; const o = n?.promptCacheTtl ?? r.promptCacheTtl; return l(e, t, { ...r, ...n, ...a ? { cacheRetention: a } : {}, ...o ? { promptCacheTtl: o } : {} }); }; } function canonicalizeExtraParamAlias(e, t, n, r = n[0]) { const i = resolveAliasedParamValue(t, n); if (i !== void 0) { e[r] = i; delete e[n[0] === r ? n[1] : n[0]]; } } const OPENROUTER_RESPONSE_CACHE_PARAM_ALIASES = [ ["responseCache", "response_cache"], OPENROUTER_RESPONSE_CACHE_TTL_KEYS, ["responseCacheClear", "response_cache_clear"] ]; function canonicalizeOpenRouterResponseCacheParams(e, t) { for (const n of OPENROUTER_RESPONSE_CACHE_PARAM_ALIASES) { const r = resolveAliasedParamValue(t, n); if (r === void 0) continue; for (const t of n) delete e[t]; e[n[0]] = r; } } function createParallelToolCallsWrapper(e, t) { const n = requireBaseStreamFn(e); return (e, r, i) => { if (!GPT_PARALLEL_TOOL_CALLS_APIS.has(e.api)) return n(e, r, i); return streamWithPayloadPatch(n, e, r, i, (e) => { e.parallel_tool_calls = t; }); }; } const DEEPSEEK_V4_MODEL_IDS = /* @__PURE__ */ new Set([ "deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro" ]); function normalizeCompatibleModelId(e) { const t = e.trim().toLowerCase(); const n = t.indexOf(":"); const r = n === -1 ? t : t.slice(0, n); return r.slice(r.lastIndexOf("/") + 1); } function isOpenAICompletionsModel(e, t) { const n = normalizeCompatibleModelId(e.id); return e.api === "openai-completions" && t.has(n); } function isMicrosoftFoundryProviderId(e) { const t = e.trim().toLowerCase(); return t === "microsoft-foundry" || t.startsWith("microsoft-foundry-"); } /** * Foundry and other non-native routes reject even thinking.type=disabled. * Explicit compat wins, then detected non-native formats; unknown proxy routes * retain the model-ID fallback to DeepSeek's native wire format. */ function deepSeekV4NativeThinkingAllowedByCompat(e) { const t = e.compat; const n = t && typeof t === "object" ? t.thinkingFormat : void 0; if (typeof n === "string") return n === "deepseek"; const r = detectOpenAICompletionsCompat(e).defaults.thinkingFormat; return r !== "openrouter" && r !== "together" && r !== "zai"; } function createDeepSeekV4NonNativeCompatSanitizerWrapper(e) { if (!e) return; return (t, n, r) => { if (!isOpenAICompletionsModel(t, DEEPSEEK_V4_MODEL_IDS) || !isMicrosoftFoundryProviderId(t.provider) && deepSeekV4NativeThinkingAllowedByCompat(t)) return e(t, n, r); return streamWithPayloadPatch(e, t, n, r, (e) => { delete e.thinking; if (Array.isArray(e.messages)) { for (const t of e.messages) if (t && typeof t === "object") delete t.reasoning_content; } }); }; } const MIMO_REASONING_OPENAI_COMPATIBLE_MODEL_IDS = /* @__PURE__ */ new Set([ "mimo-v2-pro", "mimo-v2-omni", "mimo-v2.5", "mimo-v2.5-pro", ...[ "flash", "pro", "pro-ultraspeed" ].map((e) => `mimo-v2.6-${e}`) ]); const MIMO_REASONING_AS_VISIBLE_TEXT_MODEL_IDS = /* @__PURE__ */ new Set(["mimo-v2-pro", "mimo-v2-omni"]); function applyExtraParamsToAgent(e, t, n, r, i, a, o, s, c, l, u, d) { const f = { provider: n, modelId: r }; const p = ensureProviderRuntimePluginHandle({ ...f, config: d?.transportConfig ?? t, workspaceDir: s, runtimeHandle: getModelProviderRuntimePluginHandle(c) }); const m = sanitizeExtraParamsOverride(i); const h = d?.preparedExtraParams ?? resolvePreparedExtraParams({ cfg: t, transportConfig: d?.transportConfig, ...f, extraParamsOverride: i, thinkingLevel: a, agentId: o, agentDir: l, workspaceDir: s, model: c, resolvedTransport: u, providerRuntimeHandle: p, auth: d?.auth }); const g = e.streamFn; const _ = d?.nativeWebSearchPolicyContext ? isNativeWebSearchAllowedByToolPolicy({ config: t, modelProvider: c?.provider, modelId: c?.id, agentId: o, ...d.nativeWebSearchPolicyContext }) : void 0; const { modelParams: v, agentModelParams: y } = resolveModelExtraParamSources({ config: t, provider: n, modelId: r, agentId: o }); const b = p.plugin?.wrapStreamFn?.({ config: d?.transportConfig ?? t, agentDir: l, workspaceDir: s, agentId: o, auth: d?.auth, nativeWebSearchAllowedByToolPolicy: _, ...f, extraParams: h, modelParams: { ...v, ...y }, modelCallUrgency: d?.modelCallUrgency, thinkingLevel: a, model: c, streamFn: g }) ?? void 0; e.streamFn = b ?? g; const x = m && [...REQUEST_SCOPED_EXTRA_PARAM_KEYS].some((e) => Object.hasOwn(m, e)) ? stripRequestScopedExtraParams(h) : h; const S = m ? { ...x, ...m } : x; const C = createStreamFnWithExtraParams(e.streamFn, S, n); if (C) e.streamFn = C; if (shouldApplySiliconFlowThinkingOffCompat({ ...f, thinkingLevel: a })) e.streamFn = createSiliconFlowThinkingWrapper(e.streamFn); const w = b !== void 0 && b !== g && !b.preservesGenericCompatibility; const T = m ? { ...h, ...m } : h; e.streamFn = createOpenRouterSystemCacheWrapper(e.streamFn, T); e.streamFn = createOpenAIStringContentWrapper(e.streamFn); e.streamFn = createOpenAICompletionsStrictMessageKeysWrapper(e.streamFn); e.streamFn = createOpenAICompletionsToolsCompatWrapper(e.streamFn); if (!w) { e.streamFn = createDeepSeekV4OpenAICompatibleThinkingWrapper({ baseStreamFn: e.streamFn, thinkingLevel: a, shouldPatchModel: (e) => isOpenAICompletionsModel(e, DEEPSEEK_V4_MODEL_IDS) && !isMicrosoftFoundryProviderId(e.provider) && deepSeekV4NativeThinkingAllowedByCompat(e) }); e.streamFn = createDeepSeekV4NonNativeCompatSanitizerWrapper(e.streamFn); e.streamFn = createDeepSeekV4OpenAICompatibleThinkingWrapper({ baseStreamFn: e.streamFn, thinkingLevel: a, shouldPatchModel: (e) => isOpenAICompletionsModel(e, MIMO_REASONING_OPENAI_COMPATIBLE_MODEL_IDS) }); e.streamFn = createThinkingOnlyFinalTextWrapper({ baseStreamFn: e.streamFn, shouldPatchModel: (e) => isOpenAICompletionsModel(e, MIMO_REASONING_AS_VISIBLE_TEXT_MODEL_IDS) }); e.streamFn = createGoogleThinkingPayloadWrapper(e.streamFn, a); e.streamFn = createOpenAIResponsesContextManagementWrapper(e.streamFn, h); } e.streamFn = createMinimaxThinkingDisabledWrapper(e.streamFn, a); e.streamFn = createOpenAICompletionsPayloadPolicyWrapper(requireBaseStreamFn(e.streamFn), [h, m]); const E = resolveAliasedParamValue([h, m], ["parallel_tool_calls", "parallelToolCalls"]); if (typeof E === "boolean") e.streamFn = createParallelToolCallsWrapper(e.streamFn, E); else if (E != null) { const e = typeof E === "string" ? E : typeof E; log.warn(`ignoring invalid parallel_tool_calls param: ${e}`); } return { effectiveExtraParams: h, nativeWebSearchAllowedByToolPolicy: _ }; } //#endregion export { resolvePreparedExtraParams as a, resolveExplicitCachedContent as c, resolveExtraParams as i, isAnthropicFamilyCacheTtlEligible as l, resolveAgentTransportOverride as n, isGooglePromptCacheEligible as o, resolveExplicitSettingsTransport as r, resolveCacheRetention as s, applyExtraParamsToAgent as t };