openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
226 lines (225 loc) • 9.3 kB
JavaScript
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs";
import { p as asPositiveSafeInteger } from "./number-coercion-D6u-4YD8.mjs";
import { o as resolveDefaultModelMaxTokens } from "./defaults-BWyoTPqn.mjs";
import { p as readProviderJsonArrayFieldResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { g as ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "./ssrf-DHBNJw0c.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { i as normalizeModelCompat } from "./provider-model-compat-DgjEUAN7.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import "./provider-model-shared-Dg70R9-2.mjs";
import "./provider-http-LcawLneq.mjs";
import { g as LiveModelCatalogHttpError } from "./provider-catalog-live-runtime-D-M7f_ww.mjs";
import { a as resolveStaticCopilotModelOverride, i as resolveCopilotTransportApi, n as resolveCopilotModelCompat, r as resolveCopilotThinkingLevelMap } from "./model-metadata-Bwed7cJR.mjs";
import { t as buildCopilotRuntimeHeaders } from "./runtime-identity-BCYAo2Tm.mjs";
//#region extensions/github-copilot/models.ts
const PROVIDER_ID = "github-copilot";
const DEFAULT_CONTEXT_WINDOW = 128e3;
function resolveCopilotForwardCompatModel(e) {
const t = e.modelId.trim();
if (!t) return;
const n = normalizeOptionalLowercaseString(t) ?? "";
if (e.modelRegistry.find("github-copilot", n)) return;
const r = resolveStaticCopilotModelOverride(n);
const i = r ? r.reasoning ?? false : /^o[13](\b|$)/.test(n) || /(?:^|[-_.])codex(?:$|[-_.])/.test(n);
const a = r?.compat ?? resolveCopilotModelCompat(t);
return normalizeModelCompat({
id: t,
name: r?.name ?? t,
provider: PROVIDER_ID,
api: r?.api ?? resolveCopilotTransportApi(t),
reasoning: i,
input: r?.input ?? ["text", "image"],
cost: r?.cost ?? {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
...r?.family ? { family: r.family } : {},
contextWindow: r?.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
...r?.contextWindow === void 0 ? { contextWindowSource: "synthetic" } : {},
...r?.contextTokens !== void 0 ? { contextTokens: r.contextTokens } : {},
maxTokens: r?.maxTokens ?? resolveDefaultModelMaxTokens(r?.contextWindow ?? DEFAULT_CONTEXT_WINDOW),
...r?.thinkingLevelMap ? { thinkingLevelMap: r.thinkingLevelMap } : {},
...a ? { compat: a } : {}
});
}
const copilotModelSelectionMetadata = /* @__PURE__ */ new WeakMap();
function isCopilotCatalogModelVisible(e) {
const t = copilotModelSelectionMetadata.get(e);
return Boolean(t?.pickerEnabled && t.policyState !== "disabled" && t.policyState !== "unconfigured");
}
function isCopilotCatalogModelSelectable(e) {
const t = copilotModelSelectionMetadata.get(e);
return Boolean(isCopilotCatalogModelVisible(e) && t?.streaming !== false && t?.toolCalls);
}
const COPILOT_STARTER_CATEGORY_RANK = /* @__PURE__ */ new Map([
["versatile", 0],
["lightweight", 1],
["powerful", 2]
]);
function compareCopilotStarterCandidates(e, t) {
const n = copilotModelSelectionMetadata.get(e);
const r = copilotModelSelectionMetadata.get(t);
const i = Number(n?.preview === true) - Number(r?.preview === true);
if (i !== 0) return i;
const a = (COPILOT_STARTER_CATEGORY_RANK.get(n?.category ?? "") ?? Number.MAX_SAFE_INTEGER) - (COPILOT_STARTER_CATEGORY_RANK.get(r?.category ?? "") ?? Number.MAX_SAFE_INTEGER);
if (a !== 0) return a;
const o = (t.contextWindow ?? Math.max(t.contextTokens ?? 0, DEFAULT_CONTEXT_WINDOW)) - (e.contextWindow ?? Math.max(e.contextTokens ?? 0, DEFAULT_CONTEXT_WINDOW));
if (o !== 0) return o;
const s = t.maxTokens - e.maxTokens;
if (s !== 0) return s;
return e.id.localeCompare(t.id);
}
function selectCopilotStarterModel(e, t) {
const n = e.filter(isCopilotCatalogModelSelectable);
return n.find((e) => e.id === t) ?? n.toSorted(compareCopilotStarterCandidates)[0];
}
const COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS = 1e4;
const COPILOT_ROUTER_ID_PREFIX = "accounts/";
const COPILOT_TRANSPORT_ENDPOINTS = {
"anthropic-messages": "/messages",
"openai-completions": "/chat/completions",
"openai-responses": "/responses"
};
function resolveCopilotApi(e) {
const t = e.vendor?.toLowerCase() === "anthropic" ? "anthropic-messages" : resolveCopilotTransportApi(e.id ?? "");
const n = new Set(Array.isArray(e.supported_endpoints) ? e.supported_endpoints.filter((e) => typeof e === "string").map((e) => e.trim().replace(/^\/v1(?=\/)/, "").replace(/\/+$/, "")) : []);
return [
t,
"openai-responses",
"openai-completions",
"anthropic-messages"
].find((e) => n.has(COPILOT_TRANSPORT_ENDPOINTS[e])) ?? t;
}
const COPILOT_VENDOR_FAMILIES = /* @__PURE__ */ new Map([
["anthropic", "anthropic"],
["azure openai", "openai"],
["google", "google"],
["moonshot ai", "moonshot"],
["openai", "openai"],
["xai", "xai"]
]);
function resolveCopilotModelFamily(e, t) {
const n = normalizeOptionalLowercaseString(e.vendor);
return (n ? COPILOT_VENDOR_FAMILIES.get(n) : void 0) ?? resolveStaticCopilotModelOverride(t)?.family;
}
function mergeCopilotCompat(e, t) {
if (!Array.isArray(t)) return e;
return {
...e,
supportedReasoningEfforts: [...new Set(t.map((e) => normalizeOptionalLowercaseString(e)).filter((e) => Boolean(e)))]
};
}
function mapCopilotApiModelToDefinition(e) {
const t = e.id?.trim();
if (!t) return;
if (e.object && e.object !== "model") return;
if (e.capabilities?.type && e.capabilities.type !== "chat") return;
if (t.startsWith(COPILOT_ROUTER_ID_PREFIX)) return;
const n = e.capabilities?.limits;
const r = e.capabilities?.supports;
const i = Array.isArray(r?.reasoning_effort) ? r.reasoning_effort.length > 0 : false;
const a = r?.vision === true ? ["text", "image"] : ["text"];
const o = asPositiveSafeInteger(n?.max_context_window_tokens);
const s = asPositiveSafeInteger(n?.max_prompt_tokens);
const c = asPositiveSafeInteger(n?.max_output_tokens) ?? resolveDefaultModelMaxTokens(asPositiveSafeInteger(n?.max_context_window_tokens) ?? DEFAULT_CONTEXT_WINDOW);
const l = resolveCopilotApi(e);
const u = mergeCopilotCompat(resolveCopilotModelCompat(t, l), r?.reasoning_effort);
const d = u?.supportedReasoningEfforts;
const f = l === "anthropic-messages" && d?.includes("xhigh") ? { claudeCapabilities: {
adaptiveThinking: true,
xhighEffort: true,
maxEffort: d.includes("max")
} } : void 0;
const p = resolveCopilotThinkingLevelMap(t, u, l, f);
const m = resolveCopilotModelFamily(e, t);
const h = {
id: t,
name: e.name?.trim() || t,
...m ? { family: m } : {},
api: l,
reasoning: i,
input: a,
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
...o !== void 0 ? { contextWindow: o } : {},
...s !== void 0 ? { contextTokens: s } : {},
maxTokens: c,
...p ? { thinkingLevelMap: p } : {},
...u ? { compat: u } : {},
...f ? { params: f } : {}
};
copilotModelSelectionMetadata.set(h, {
category: normalizeOptionalLowercaseString(e.model_picker_category),
pickerEnabled: e.model_picker_enabled === true,
policyState: normalizeOptionalLowercaseString(e.policy?.state),
preview: e.preview === true,
streaming: r?.streaming,
toolCalls: r?.tool_calls === true
});
return h;
}
function asCopilotApiModelEntry(e) {
if (typeof e !== "object" || e === null || Array.isArray(e)) throw new Error("Copilot /models: malformed JSON response");
return e;
}
/**
* Fetch the live Copilot model catalog from `${baseUrl}/models` and project it
* into `ModelDefinitionConfig[]`. Used by the plugin's discovery hook so the
* runtime catalog tracks per-account entitlements + accurate context windows
* without manifest churn.
*
* Filters out non-chat objects (embeddings, routers) and internal router ids.
* Failures propagate so the catalog owner can publish a truthful outcome.
*/
async function fetchCopilotModelCatalog(e) {
const t = e.baseUrl.replace(/\/+$/, "");
if (!t) throw new Error("fetchCopilotModelCatalog: baseUrl required");
if (!e.copilotApiToken.trim()) throw new Error("fetchCopilotModelCatalog: copilotApiToken required");
const n = `${t}/models`;
const r = new AbortController();
const i = setTimeout(() => r.abort(), COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS);
let a;
try {
const i = await fetchWithSsrFGuard({
url: n,
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(t),
signal: r.signal,
init: {
method: "GET",
headers: {
Accept: "application/json",
...buildCopilotRuntimeHeaders({ headers: e.headers }),
Authorization: `Bearer ${e.copilotApiToken}`
}
}
});
a = i.release;
const o = i.response;
if (!o.ok) {
await o.body?.cancel().catch(() => void 0);
throw new LiveModelCatalogHttpError(PROVIDER_ID, o.status);
}
const s = await readProviderJsonArrayFieldResponse(o, "Copilot /models", "data");
const c = /* @__PURE__ */ new Set();
const l = [];
for (const e of s) {
const t = mapCopilotApiModelToDefinition(asCopilotApiModelEntry(e));
if (!t || c.has(t.id)) continue;
c.add(t.id);
l.push(t);
}
return l;
} finally {
clearTimeout(i);
await a?.();
}
}
//#endregion
export { resolveCopilotForwardCompatModel as a, isCopilotCatalogModelVisible as i, PROVIDER_ID as n, selectCopilotStarterModel as o, fetchCopilotModelCatalog as r, COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS as t };