UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

703 lines (702 loc) • 26.3 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { i as asOptionalObjectRecord, l as isRecord, o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { i as MODEL_CATALOG_THINKING_LEVELS, l as resolveOpenAIThinkingApi } from "./model-catalog-types-DFHCZ2Xr.mjs"; import { t as DEFAULT_MISSING_TOOL_RESULT_TEXT } from "./types-iq-cNLsd.mjs"; import { d as resolveClaudeHaiku55ModelIdentity, g as resolveClaudeOpus5ModelIdentity, p as resolveClaudeMythos5ModelIdentity, u as resolveClaudeFable5ModelIdentity, v as resolveClaudeSonnet5ModelIdentity } from "./anthropic-D3Mx6AZz.mjs"; import "./src-DFw9QOgs.mjs"; import { r as resolveEnvNodeProxyUrlForTarget, t as createFixedNodeProxyAgentPair } from "./node-proxy-agent-CKkgcWcJ.mjs"; import { r as resolveFailedAssistantReplay$1, t as FAILED_ASSISTANT_REPLAY_TEXT$1 } from "./replay-turn-classification-B8UrZf_L.mjs"; import "./stream-DEhzhrZ_.mjs"; import { adjustMaxTokensForThinking as adjustMaxTokensForThinking$1, buildBaseOptions, clampReasoning, transformMessages } from "@openclaw/ai/internal/shared"; import { calculateCost, clampThinkingLevel as clampThinkingLevel$1, createToolArgumentPreviewSchedule as createToolArgumentPreviewSchedule$1, getApiProvider, getApiProviders, getEnvApiKey as getEnvApiKey$1, parseStreamingJson as parseStreamingJson$1, sanitizeSurrogates as sanitizeSurrogates$1 } from "@openclaw/ai/internal/runtime"; //#region packages/llm-core/src/utils/event-stream.ts const thinkingAppends = /* @__PURE__ */ new WeakMap(); const eventStreamCompletions = /* @__PURE__ */ new WeakMap(); /** Generic async-iterable event stream with a separately awaited final result. */ var EventStream = class { constructor(e, t) { this.queue = []; this.queueHead = 0; this.waiting = []; this.done = false; this.resultSettled = false; this.isComplete = e; this.extractResult = t; this.finalResultPromise = new Promise((e, t) => { this.resolveFinalResult = e; this.rejectFinalResult = t; }); eventStreamCompletions.set(this, this.finalResultPromise); } push(e) { if (this.done) return; if (this.isComplete(e)) { this.done = true; this.resultSettled = true; this.resolveFinalResult(this.extractResult(e)); } const t = this.waiting.shift(); if (t) t({ value: e, done: false }); else this.queue.push(e); } end(e) { this.done = true; if (e !== void 0) { this.resultSettled = true; this.resolveFinalResult(e); } else if (!this.resultSettled) { this.resultSettled = true; this.finalResultPromise.catch(() => {}); this.rejectFinalResult(/* @__PURE__ */ new Error("event stream ended without a terminal event or final result")); } for (const e of this.waiting) e({ value: void 0, done: true }); this.waiting = []; } async *[Symbol.asyncIterator]() { while (true) if (this.queueHead < this.queue.length) { const e = this.queue[this.queueHead]; this.queue[this.queueHead] = void 0; this.queueHead += 1; if (this.queueHead >= 1024 && this.queueHead * 2 >= this.queue.length) { this.queue = this.queue.slice(this.queueHead); this.queueHead = 0; } yield e; } else if (this.done) return; else { const e = await new Promise((e) => { this.waiting.push(e); }); if (e.done) return; yield e.value; } } result() { return this.finalResultPromise; } }; /** Assistant-message event stream that resolves on done/error terminal events. */ var AssistantMessageEventStream = class extends EventStream { push(e) { if (!this.done && e.type === "text_delta" && !e.partial) { const t = this.queue[this.queue.length - 1]; if (t?.type === "text_delta" && !t.partial && t.contentIndex === e.contentIndex) { this.queue[this.queue.length - 1] = { ...e, delta: t.delta + e.delta }; return; } } if (e.type === "thinking_delta" || e.type === "thinking_end") { const t = e.partial.content[e.contentIndex]; if (t?.type === "thinking") { if (this.done || e.type === "thinking_end") { thinkingAppends.delete(t); this.activeThinkingBlocks?.delete(t); } else if (thinkingAppends.has(t)) (this.activeThinkingBlocks ??= /* @__PURE__ */ new Set()).add(t); } } if (e.type === "done" || e.type === "error") this.clearThinkingAppends(e.type === "done" ? e.message : e.error); super.push(e); } end(e) { this.clearThinkingAppends(e); super.end(e); } clearThinkingAppends(e) { for (const t of e?.content ?? []) if (t.type === "thinking") thinkingAppends.delete(t); for (const e of this.activeThinkingBlocks ?? []) thinkingAppends.delete(e); this.activeThinkingBlocks = void 0; } constructor() { super((e) => e.type === "done" || e.type === "error", (e) => { if (e.type === "done") return e.message; else if (e.type === "error") return e.error; throw new Error("Unexpected event type for final result"); }); } }; /** Creates an assistant-message stream for provider and plugin adapters. */ function createAssistantMessageEventStream() { return new AssistantMessageEventStream(); } //#endregion //#region packages/ai/src/provider-types.ts const PROVIDER_CONTEXT_HANDOFF = Symbol("providerContextHandoff"); /** Resolves provider-only context without widening the canonical call contract. */ async function resolveProviderContext(e, t) { return t?.[PROVIDER_CONTEXT_HANDOFF]?.() ?? e; } //#endregion //#region packages/ai/src/transports/openai-reasoning-compat.ts /** Explicit model reasoning-effort compatibility metadata. */ function readCompatReasoningEffortMap(e) { const t = asOptionalObjectRecord(asOptionalObjectRecord(e)?.reasoningEffortMap); if (!t) return {}; return Object.fromEntries(Object.entries(t).filter((e) => typeof e[1] === "string")); } /** Resolves the reasoning effort remap for an OpenAI-compatible model. */ function resolveOpenAIReasoningEffortMap(e, t = {}) { return { ...t, ...readCompatReasoningEffortMap(e.compat) }; } //#endregion //#region packages/ai/src/providers/openai-reasoning-effort.ts /** * OpenAI-compatible reasoning-effort normalization. Different GPT families * expose different accepted effort enums, so callers map requested values here * before constructing provider payloads. */ const ENABLED_REASONING_EFFORTS = [ "minimal", "low", "medium", "high", "xhigh", "max" ]; const GPT_5_REASONING_EFFORTS = [ "minimal", "low", "medium", "high" ]; const GPT_51_REASONING_EFFORTS = [ "none", "low", "medium", "high" ]; const GPT_52_REASONING_EFFORTS = [ "none", "low", "medium", "high", "xhigh" ]; const GPT_56_REASONING_EFFORTS = [ "none", "low", "medium", "high", "xhigh", "max" ]; const GPT_6_MANDATORY_REASONING_EFFORTS = [ "low", "medium", "high", "xhigh", "max" ]; const GPT_CODEX_REASONING_EFFORTS = [ "low", "medium", "high", "xhigh" ]; const GPT_PRO_REASONING_EFFORTS = [ "medium", "high", "xhigh" ]; const GPT_5_PRO_REASONING_EFFORTS = ["high"]; const GPT_51_CODEX_MAX_REASONING_EFFORTS = [ "none", "medium", "high", "xhigh" ]; const GPT_51_CODEX_MINI_REASONING_EFFORTS = ["medium"]; const GENERIC_REASONING_EFFORTS = [ "low", "medium", "high" ]; const CANONICAL_REASONING_EFFORTS = /* @__PURE__ */ new Set([ "none", ...ENABLED_REASONING_EFFORTS, "off" ]); function normalizeModelId$1(e) { return normalizeLowercaseStringOrEmpty(e ?? "").replace(/^openai\//u, "").replace(/-\d{4}-\d{2}-\d{2}$/u, ""); } /** Return whether a model has a known GPT-6 reasoning and sampling contract. */ function isOpenAIGpt6Model(e) { const t = normalizeModelId$1(typeof e.id === "string" ? e.id : void 0); return t === "gpt-6-astra" || t === "gpt-6-sol" || t === "gpt-6-luna" || t === "gpt-6.1-sol"; } /** Normalize user-facing reasoning effort names to API effort names. */ function normalizeOpenAIReasoningEffort(e) { const t = e.trim(); const n = t.toLowerCase(); return CANONICAL_REASONING_EFFORTS.has(n) ? n : t; } function isDisabledReasoningEffort(e) { return e === "none" || e === "off"; } /** Resolve the reasoning efforts accepted by a specific OpenAI-compatible model. */ function resolveOpenAISupportedReasoningEfforts(e) { return resolveOpenAIModelReasoningEfforts(e) ?? GENERIC_REASONING_EFFORTS; } /** Read a declared or known model contract, leaving unknown compatible models unspecified. */ function resolveOpenAIModelReasoningEfforts(e) { const t = e.compat; if (t && typeof t === "object") { if (t.supportsReasoningEffort === false) return []; const e = t.supportedReasoningEfforts; if (Array.isArray(e)) return normalizeUniqueTrimmedStringList(e); } const n = normalizeModelId$1(typeof e.id === "string" ? e.id : void 0); const r = resolveOpenAIThinkingApi(e.api); const i = r !== "openai-completions"; if (isOpenAIGpt6Model(e) && r !== "azure-openai-responses") { if (n === "gpt-6-astra" || n === "gpt-6.1-sol") return i ? GPT_6_MANDATORY_REASONING_EFFORTS : GPT_CODEX_REASONING_EFFORTS; return i ? GPT_56_REASONING_EFFORTS : GPT_52_REASONING_EFFORTS; } if (/^gpt-5\.6(?:-|$)/u.test(n)) return i ? GPT_56_REASONING_EFFORTS : GPT_52_REASONING_EFFORTS; if (n === "gpt-5.1-codex-mini") return GPT_51_CODEX_MINI_REASONING_EFFORTS; if (n === "gpt-5.1-codex-max") return GPT_51_CODEX_MAX_REASONING_EFFORTS; if (/^gpt-5(?:\.\d+)?-codex(?:-|$)/u.test(n)) return GPT_CODEX_REASONING_EFFORTS; if (n === "gpt-5-pro") return GPT_5_PRO_REASONING_EFFORTS; if (/^gpt-5\.[2-9](?:\.\d+)?-pro(?:-|$)/u.test(n)) return GPT_PRO_REASONING_EFFORTS; if (/^gpt-5\.[2-9](?:\.\d+)?(?:-|$)/u.test(n)) return GPT_52_REASONING_EFFORTS; if (/^gpt-5\.1(?:-|$)/u.test(n)) return GPT_51_REASONING_EFFORTS; if (/^gpt-5(?:-|$)/u.test(n)) return GPT_5_REASONING_EFFORTS; } /** Return whether a model accepts a requested reasoning effort. */ function supportsOpenAIReasoningEffort(e, t) { const n = normalizeOpenAIReasoningEffort(t); const r = resolveOpenAIModelReasoningEfforts(e); if (r !== void 0) return r.includes(n); return GENERIC_REASONING_EFFORTS.some((e) => e === n) || [...Object.values(resolveOpenAIReasoningEffortMap({ compat: e.compat })), ...Object.values(asRecord(e.thinkingLevelMap))].some((e) => typeof e === "string" && e.trim() === n); } /** Read provider mappings without folding provider-native labels. */ function resolveOpenAIReasoningEffortMapping(e, t) { const n = normalizeOpenAIReasoningEffort(e); return t?.[n] ?? (t && CANONICAL_REASONING_EFFORTS.has(n) ? Object.entries(t).find(([e]) => normalizeOpenAIReasoningEffort(e) === n)?.[1] : void 0); } /** Resolve a requested reasoning effort to the closest value supported by the model. */ function resolveOpenAIReasoningEffortForModel(e) { const t = normalizeOpenAIReasoningEffort(e.effort); const n = resolveOpenAIReasoningEffortMapping(t, e.fallbackMap); const r = n === void 0 ? t : n.trim(); const i = resolveOpenAISupportedReasoningEfforts(e.model); if (i.includes(r)) return r; if (t === "off" && i.includes("none")) return "none"; if (isDisabledReasoningEffort(t) || isDisabledReasoningEffort(r)) return; const a = ENABLED_REASONING_EFFORTS.findIndex((e) => e === r); const o = ENABLED_REASONING_EFFORTS.filter((e) => i.includes(e)); return (a < 0 ? void 0 : o.findLast((e) => ENABLED_REASONING_EFFORTS.indexOf(e) <= a) ?? o[0]) ?? i.find((e) => !isDisabledReasoningEffort(normalizeOpenAIReasoningEffort(e))); } //#endregion //#region packages/ai/src/media-payload.ts /** Media metadata alone is not an attachment; provider emitters need inline bytes. */ function hasMediaPayload(e) { return isRecord(e) && typeof e.data === "string" && e.data.trim().length > 0; } /** Image metadata alone is not an attachment; provider emitters need inline bytes. */ function isImageWithMediaPayload(e) { return isRecord(e) && e.type === "image" && hasMediaPayload(e); } //#endregion //#region packages/ai/src/providers/anthropic-model-contract.ts function normalizeModelId(e) { const t = normalizeLowercaseStringOrEmpty(e); return (t.startsWith("anthropic/") ? t.slice(10) : t).replace(/[._\s]+/g, "-"); } function normalizeApi(e) { const t = normalizeLowercaseStringOrEmpty(e); return t === "openclaw-anthropic-messages-transport" ? "anthropic-messages" : t; } function hasConcreteResponseModel(e) { const t = normalizeModelId(e.responseModelId); return t.length > 0 && t !== normalizeModelId(e.modelId); } function resolveReplayModelBoundIdentity(e) { if (normalizeApi(e.api) !== "anthropic-messages") return; const t = hasConcreteResponseModel(e) ? { id: e.responseModelId } : { id: e.modelId, params: e.modelParams }; const n = resolveClaudeFable5ModelIdentity(t); const r = resolveClaudeHaiku55ModelIdentity(t); if (r) return `haiku:${r}`; if (n) return `fable:${n}`; const i = resolveClaudeMythos5ModelIdentity(t); if (i) return `mythos:${i}`; const a = resolveClaudeOpus5ModelIdentity(t); if (a) return `opus:${a}`; const o = resolveClaudeSonnet5ModelIdentity(t); return o ? `sonnet:${o}` : void 0; } const FABLE_51_REPLAY_IDENTITY = /^fable:claude-fable-5-1(?=$|[^a-z0-9])/; const SONNET_55_REPLAY_IDENTITY = /^sonnet:claude-sonnet-5-5(?=$|[^a-z0-9])/; /** * Verified live (2026-09-28): Fable 5.1 reads every earlier Claude generation * except Sonnet 5.5; Sonnet 5.5 reads Sonnet 5 and pre-Claude-5 thinking but * not Opus 5, Fable, or Mythos; no other model reads Sonnet 5.5 thinking. The * API drops what a target cannot read, and every other cross-identity move * stays dropped here until its replay contract is proven separately. */ function readsPriorClaudeThinking(e, t) { if (e === void 0) return false; if (FABLE_51_REPLAY_IDENTITY.test(e)) return t === void 0 || !SONNET_55_REPLAY_IDENTITY.test(t) && !t.startsWith("haiku:"); if (SONNET_55_REPLAY_IDENTITY.test(e)) return t === void 0 || t.startsWith("sonnet:"); return false; } function isClaudeReplaySource(e) { const t = hasConcreteResponseModel(e) ? e.responseModelId : e.modelId; return /(?:^|[-/])claude-/.test(normalizeModelId(t)); } /** The destination is fixed during one synchronous history transform. */ function prepareModelBoundThinkingReplay(e) { const t = normalizeApi(e.api); const n = resolveReplayModelBoundIdentity({ api: e.api, modelId: e.id, modelParams: e.params }); const r = normalizeLowercaseStringOrEmpty(e.provider); const i = normalizeModelId(e.id); return (e) => { const a = normalizeApi(e.api); const o = resolveReplayModelBoundIdentity(e); if (!o && !n) return "default"; if (a === t && readsPriorClaudeThinking(n, o) && isClaudeReplaySource(e)) return "preserve"; if (!o && !hasConcreteResponseModel(e) && n && normalizeLowercaseStringOrEmpty(e.provider) === r && a === t && normalizeModelId(e.modelId) === i) return "preserve"; return a === t && o === n ? "preserve" : "drop"; }; } //#endregion //#region packages/ai/src/transports/openai-responses-contracts.ts const OPENAI_RESPONSES_APIS = /* @__PURE__ */ new Set([ "openai-responses", "azure-openai-responses", "openai-chatgpt-responses", "openclaw-openai-responses-transport", "openclaw-openai-chatgpt-responses-transport", "openclaw-azure-openai-responses-transport" ]); //#endregion //#region packages/ai/src/transcript-transform.ts const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)"; const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)"; function replaceImagesWithPlaceholder(e, t) { const n = []; for (const r of e) { if (r.type !== "image") { n.push(r); continue; } const e = n.at(-1); const i = e?.type === "text" && e.text === t; if (isImageWithMediaPayload(r) && !i) n.push({ type: "text", text: t }); } return Object.isFrozen(e) && n.length === e.length && n.every((t, n) => t === e[n]) ? e : n; } function transformAssistant(e, t, n, r, i) { const a = r({ provider: e.provider, api: e.api, modelId: e.model, responseModelId: e.responseModel }); const o = a === "preserve" || e.provider === t.provider && e.api === t.api && e.model === t.id; const s = (typeof e.content === "string" ? [{ type: "text", text: e.content }] : e.content).flatMap((r) => { if (r.type === "thinking") { if (a === "drop") return []; if (r.redacted) return o ? r : []; if (o && r.thinkingSignature) return r; if (!r.thinking?.trim()) return []; return o ? r : { type: "text", text: r.thinking }; } if (r.type === "text") return o ? r : { type: "text", text: r.text }; const s = r.id.trim(); if (o) return s === r.id ? r : Object.assign({}, r, { id: s }); const { thoughtSignature: c, async: l, ...u } = r; const d = i?.(s, t, e) ?? s; if (d !== s) n.set(s, d); return d === r.id ? u : Object.assign({}, u, { id: d }); }); return Array.isArray(e.content) && Object.isFrozen(e) && Object.isFrozen(e.content) && s.length === e.content.length && s.every((t, n) => t === e.content[n]) ? e : { ...e, content: s }; } function transformMessages$1(e, t, n) { const r = /* @__PURE__ */ new Map(); const i = prepareModelBoundThinkingReplay(t); const a = /* @__PURE__ */ new Map(); const o = /* @__PURE__ */ new Map(); const s = /* @__PURE__ */ new Set(); for (const n of e) if (n.role === "assistant") { const e = n.provider === t.provider && n.api === t.api && n.model === t.id; for (const t of n.content ?? []) if (t.type === "toolCall") { const r = t.id.trim(); if (t.async && !e) a.set(r, n); else a.delete(r); } } else if (n.role === "toolResult") { const e = n.toolCallId.trim(); const t = a.get(e); if (t) { const r = o.get(t) ?? []; r.push(n); o.set(t, r); s.add(n); a.delete(e); } } const c = s.size > 0 ? e.flatMap((e) => s.has(e) ? [] : [e, ...e.role === "assistant" ? o.get(e) ?? [] : []]) : e; const l = t.input.includes("image"); const u = OPENAI_RESPONSES_APIS.has(t.api) ? "aborted" : DEFAULT_MISSING_TOOL_RESULT_TEXT; const d = []; const f = /* @__PURE__ */ new Map(); let p = []; let m = /* @__PURE__ */ new Set(); const flushToolCalls = () => { for (const { call: e, timestamp: t } of p) if (!m.has(e.id)) d.push({ role: "toolResult", toolCallId: e.id, toolName: e.name, content: [{ type: "text", text: u }], details: { openclawSyntheticMissingToolResult: true }, isError: true, timestamp: t }); p = []; m = /* @__PURE__ */ new Set(); }; for (let e of c) { if (e.content == null) e = { ...e, content: [] }; if (e.role === "assistant") { const a = resolveFailedAssistantReplay$1(e, { pairingAware: false }); e = transformAssistant(e, t, r, i, n); flushToolCalls(); if (a === "drop") continue; if (a === "marker") { d.push({ ...e, content: [{ type: "text", text: FAILED_ASSISTANT_REPLAY_TEXT$1 }] }); continue; } p = e.content.flatMap((t) => { if (t.type !== "toolCall") return []; const n = { call: t, timestamp: e.timestamp ?? 0 }; if (t.async) { f.set(t.id, n); return []; } return [n]; }); } else { if (!l && typeof e.content !== "string") { const t = replaceImagesWithPlaceholder(e.content, e.role === "user" ? NON_VISION_USER_IMAGE_PLACEHOLDER : NON_VISION_TOOL_IMAGE_PLACEHOLDER); if (!Object.isFrozen(e) || t !== e.content) e = { ...e, content: t }; } if (e.role === "toolResult") { const t = e.toolCallId.trim(); const n = r.get(t) ?? t; if (n !== e.toolCallId) e = { ...e, toolCallId: n }; m.add(n); f.delete(n); } else flushToolCalls(); } d.push(e); } p.push(...f.values()); flushToolCalls(); return d; } //#endregion //#region packages/ai/src/host.ts const MAX_PENDING_CUSTOM_API_REGISTRATIONS = 32; function queueCustomApiRegistration(e, t, n) { const r = hostState.pendingRegistrations.find((n) => n.registry === e && n.api === t); if (r) { r.streamFn = n; return false; } if (hostState.pendingRegistrations.length >= MAX_PENDING_CUSTOM_API_REGISTRATIONS) throw new Error("Too many custom transport APIs were registered before host configuration"); hostState.pendingRegistrations.push({ registry: e, api: t, streamFn: n }); return false; } const inertAiTransportHost = { runInDetachedAsyncContext: (e) => e(), buildModelFetch: () => void 0, resolveSecretSentinel: (e) => e, redactToolPayloadText: (e) => e, normalizeAnthropicInlineContentBlocks: async (e) => [...e], resolveOpenAIStrictToolSetting: (e, t) => t?.supportsStrictMode ? false : void 0, plugin: { resolveProviderStream: () => void 0, resolveTransportTurnState: () => void 0, wrapSimpleCompletionStream: () => void 0, createAnthropicVertexStream: () => { throw new Error("Anthropic Vertex transport is not configured by the embedding host"); } }, buildCopilotDynamicHeaders: () => ({}), resolveProviderRequestCapabilities: () => ({ endpointClass: "default", knownProviderFamily: "", supportsNativeStreamingUsageCompat: false, supportsOpenAICompletionsStreamingUsageCompat: false, usesExplicitProxyLikeEndpoint: false, allowsAnthropicServiceTier: false }), resolveProviderRequestHeaders: ({ providerHeaders: e, callerHeaders: t, precedence: n }) => ({ ...n === "caller-wins" ? e : t, ...n === "caller-wins" ? t : e }), resolveModelRequestTimeoutMs: () => void 0, requiresManagedTransport: () => false, inheritManagedTransport: (e, t) => t, transformTransportMessages: (e, t, n) => transformMessages$1(e, t, n), registerCustomApi: queueCustomApiRegistration, isLogEnabled: () => true, logDebug: () => {}, logInfo: () => {}, logWarn: () => {} }; function createAiTransportHostScope() { if (typeof process === "undefined") return; const e = process.getBuiltinModule?.("node:async_hooks"); return e ? new e.AsyncLocalStorage() : void 0; } const HOST_STATE_KEY = Symbol.for("openclaw.ai.transportHost"); function resolveAiTransportHostState() { const e = globalThis; const t = e[HOST_STATE_KEY]; if (Object.hasOwn(e, HOST_STATE_KEY) && t !== void 0) return t; const n = { inert: inertAiTransportHost, active: inertAiTransportHost, scope: createAiTransportHostScope(), pendingHost: void 0, pendingOperations: 0, pendingRegistrations: [] }; e[HOST_STATE_KEY] = n; return n; } const hostState = resolveAiTransportHostState(); /** Returns the active transport host (inert defaults unless configured). */ function getAiTransportHost() { return hostState.scope?.getStore() ?? hostState.active; } //#endregion //#region packages/ai/src/transports/host-policy.ts function resolveProviderEndpoint(e) { return { endpointClass: getAiTransportHost().resolveProviderRequestCapabilities({ baseUrl: e.baseUrl, model: e }).endpointClass }; } //#endregion //#region packages/ai/src/transports/openai-completions-host.ts /** * Chat Completions accepts Azure AI Foundry hosts in addition to traditional * Azure OpenAI hosts. Do not replace this with isTraditionalAzureOpenAIHost, * which intentionally excludes the .services.ai.azure.com Foundry suffix. */ function isAzureOpenAICompatibleHost(e) { return e.endsWith(".openai.azure.com") || e.endsWith(".services.ai.azure.com") || e.endsWith(".cognitiveservices.azure.com"); } //#endregion //#region packages/ai/src/transports/openai-completions-compat.ts /** Native OpenAI defaults never apply to a configured proxy endpoint. */ function isNativeOpenAIEndpoint(e) { const t = e.baseUrl?.trim(); if (!t) return e.provider === "openai"; const n = URL.parse(t); return n?.protocol === "https:" && (n.hostname === "api.openai.com" || n.hostname.endsWith(".api.openai.com")); } /** Model-name defaults apply only on a known OpenAI endpoint. */ function isKnownOpenAIEndpoint(e) { if (!e.baseUrl?.trim() || isNativeOpenAIEndpoint(e)) return true; const t = resolveProviderEndpoint(e).endpointClass; if (t === "openai-public" || t === "azure-openai") return true; const n = URL.parse(e.baseUrl); return n !== null && isAzureOpenAICompatibleHost(n.hostname.toLowerCase()); } //#endregion //#region packages/ai/src/providers/openai-request-reasoning.ts function resolveOpenAIRequestReasoning(e, t) { const n = normalizeOpenAIReasoningEffort(t ?? "off"); const r = MODEL_CATALOG_THINKING_LEVELS.find((e) => e === n); const i = r ? e.thinkingLevelMap?.[r] : void 0; const a = i === null ? null : resolveOpenAIReasoningEffortMapping(n, resolveOpenAIReasoningEffortMap(e)) ?? i; const o = a !== void 0 ? a?.trim() : t === void 0 ? void 0 : n; const s = normalizeOpenAIReasoningEffort(o ?? "off"); const c = n === "off" || n === "none"; const l = resolveOpenAIModelReasoningEfforts(c && resolveOpenAIThinkingApi(e.api) !== "openai-chatgpt-responses" && !isKnownOpenAIEndpoint(e) ? { compat: e.compat } : e); const u = !e.reasoning || l?.length === 0 || o === void 0 ? void 0 : l === void 0 ? c && a === void 0 ? void 0 : o : resolveOpenAIReasoningEffortForModel({ model: e, effort: n, fallbackMap: { [n]: o } }); return { effort: u === "none" && resolveOpenAIThinkingApi(e.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(e.id === "gpt-6-sol" || e.id === "gpt-6-luna" ? e : { compat: e.compat, thinkingLevelMap: e.thinkingLevelMap }, "none") ? void 0 : u, thinkingEnabled: o === void 0 ? void 0 : e.reasoning && s !== "off" && s !== "none" }; } //#endregion //#region src/llm/utils/node-http-proxy.ts /** Builds fixed HTTP and HTTPS proxy agents for a target URL, when env proxy config applies. */ function createHttpProxyAgentsForTarget(e) { const t = resolveEnvNodeProxyUrlForTarget(e); if (!t) return; return createFixedNodeProxyAgentPair(t); } //#endregion export { resolveOpenAIReasoningEffortMap as _, clampThinkingLevel$1 as a, createAssistantMessageEventStream as b, getApiProviders as c, sanitizeSurrogates$1 as d, transformMessages as f, resolveOpenAIReasoningEffortMapping as g, resolveOpenAIModelReasoningEfforts as h, clampReasoning as i, getEnvApiKey$1 as l, resolveOpenAIRequestReasoning as m, buildBaseOptions as n, createToolArgumentPreviewSchedule$1 as o, createHttpProxyAgentsForTarget as p, calculateCost as r, getApiProvider as s, adjustMaxTokensForThinking$1 as t, parseStreamingJson$1 as u, resolveProviderContext as v, AssistantMessageEventStream as y };