openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
205 lines (204 loc) • 8.3 kB
JavaScript
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { f as normalizeResolvedSecretInputString } from "./types.secrets-BmNLLnHp.mjs";
import { _ as readResponseTextLimited, h as readProviderJsonResponse } from "./provider-http-errors-Dtgw3x-5.mjs";
import { a as redactProviderResponseErrorText } from "./provider-request-header-redaction-Ckk_UIqk.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { F as sanitizeAndNormalizeEmbedding, M as buildRemoteBaseUrlPolicy, N as withRemoteHttpResponse } from "./gateway-startup-plugin-config-DY4atCe0.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import "./secret-input-CpgOwFAi.mjs";
import "./provider-http-LcawLneq.mjs";
import "./memory-core-host-engine-embeddings-CX_qB4Zn.mjs";
import { a as resolveGithubCopilotDomain } from "./domain-CmrCAfb-.mjs";
import { t as buildCopilotRuntimeHeaders } from "./runtime-identity-BCYAo2Tm.mjs";
import { t as COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS } from "./models-BjkArA0g.mjs";
import { t as resolveFirstGithubToken } from "./auth-BSnFFp-T.mjs";
import { t as CopilotRuntimeAuthError } from "./runtime-auth-error-CKTqd5Gw.mjs";
import { n as resolveCopilotRuntimeAuth } from "./runtime-auth-DkAnVQE7.mjs";
//#region extensions/github-copilot/embeddings.ts
const COPILOT_EMBEDDING_PROVIDER_ID = "github-copilot";
const PREFERRED_MODELS = [
"text-embedding-3-small",
"text-embedding-3-large",
"text-embedding-ada-002"
];
const COPILOT_ERROR_BODY_LIMIT_BYTES = 8192;
const COPILOT_EMBEDDINGS_RESPONSE_MAX_BYTES = 67108864;
function isCopilotSetupError(e) {
if (e instanceof CopilotRuntimeAuthError) return true;
if (!(e instanceof Error)) return false;
return e.message.includes("No GitHub token available") || e.message.includes("Copilot user response") || e.message.includes("No embedding models available") || e.message.includes("GitHub Copilot model discovery") || e.message.includes("github-copilot.model-discovery") || e.message.includes("GitHub Copilot embedding model") || e.message.includes("Unexpected response from GitHub Copilot user endpoint");
}
function normalizeCopilotEmbeddingModel(e) {
const t = e.trim();
const n = `${COPILOT_EMBEDDING_PROVIDER_ID}/`;
const r = t.startsWith(n) ? t.slice(n.length) : t;
return r && r === r.trim() && !r.startsWith(n) ? r : t;
}
function pickBestModel(e, t) {
if (t) {
const n = normalizeCopilotEmbeddingModel(t);
if (e.length === 0) throw new Error("No embedding models available from GitHub Copilot");
if (!e.includes(n)) throw new Error(`GitHub Copilot embedding model "${n}" is not available. Available: ${e.join(", ")}`);
return n;
}
const n = PREFERRED_MODELS.find((t) => e.includes(t)) ?? e[0];
if (n) return n;
throw new Error("No embedding models available from GitHub Copilot");
}
function parseGitHubCopilotEmbeddingPayload(e, t) {
const n = asOptionalObjectRecord(e)?.data;
if (!Array.isArray(n)) throw new Error("GitHub Copilot embeddings response missing data[]");
const r = Array.from({ length: t });
for (const e of n) {
const n = asOptionalObjectRecord(e);
if (!n) throw new Error("GitHub Copilot embeddings response contains an invalid entry");
const { index: i, embedding: a } = n;
const o = typeof i === "number" ? i : NaN;
if (!Number.isInteger(o)) throw new Error("GitHub Copilot embeddings response contains an invalid index");
if (o < 0 || o >= t) throw new Error("GitHub Copilot embeddings response contains an out-of-range index");
if (r[o] !== void 0) throw new Error("GitHub Copilot embeddings response contains duplicate indexes");
if (!Array.isArray(a) || !a.every((e) => typeof e === "number")) throw new Error("GitHub Copilot embeddings response contains an invalid embedding");
r[o] = sanitizeAndNormalizeEmbedding(a);
}
for (let e = 0; e < t; e += 1) if (r[e] === void 0) throw new Error("GitHub Copilot embeddings response missing vectors for some inputs");
return r;
}
const githubCopilotMemoryEmbeddingProviderAdapter = {
id: COPILOT_EMBEDDING_PROVIDER_ID,
transport: "remote",
authProviderId: COPILOT_EMBEDDING_PROVIDER_ID,
normalizeModel: ({ model: e }) => normalizeCopilotEmbeddingModel(e),
autoSelectPriority: 15,
allowExplicitWhenConfiguredAuto: true,
shouldContinueAutoSelection: isCopilotSetupError,
create: async (e) => {
const t = normalizeResolvedSecretInputString({
value: e.remote?.apiKey,
path: "memory.search.remote.apiKey"
});
const n = e.remote?.baseUrl?.trim();
const r = n ? (() => {
if (!t) throw new Error("GitHub Copilot memory custom baseUrl requires an explicit memory.search.remote.apiKey");
return {
apiKey: t,
baseUrl: n
};
})() : void 0;
const i = t ? void 0 : await resolveFirstGithubToken({
agentDir: e.agentDir,
config: e.config,
env: process.env
});
const a = t ?? i?.githubToken;
if (!a) throw new Error("No GitHub token available for Copilot embedding provider");
const o = resolveGithubCopilotDomain({
env: process.env,
explicit: i?.githubDomain,
config: e.config
});
const s = r ?? await resolveCopilotRuntimeAuth({
githubToken: a,
env: process.env,
githubDomain: o
});
const c = s.baseUrl;
const l = buildRemoteBaseUrlPolicy(c);
const u = buildCopilotRuntimeHeaders({
config: e.config,
headers: {
"Content-Type": "application/json",
...e.remote?.headers
}
});
const d = s.apiKey;
const discoverEmbeddingModels = async () => {
const e = `${c.replace(/\/$/, "")}/models`;
const t = {
...u,
Authorization: `Bearer ${d}`
};
const { response: n, release: r } = await fetchWithSsrFGuard({
url: e,
init: {
method: "GET",
headers: t
},
policy: l,
timeoutMs: COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS,
auditContext: "memory-remote"
});
try {
if (!n.ok) {
const e = redactProviderResponseErrorText(await readResponseTextLimited(n, COPILOT_ERROR_BODY_LIMIT_BYTES), t);
throw new Error(`GitHub Copilot model discovery HTTP ${n.status}: ${e}`);
}
const e = await readProviderJsonResponse(n, "github-copilot.model-discovery");
return (Array.isArray(e?.data) ? e.data ?? [] : []).flatMap((e) => {
const t = typeof e.id === "string" ? e.id.trim() : "";
if (!t) return [];
return filterStringEntries(e.supported_endpoints).some((e) => e.includes("embeddings")) || /\bembedding/i.test(t) ? [t] : [];
});
} finally {
await r();
}
};
const f = pickBestModel(await discoverEmbeddingModels(), e.model?.trim() || void 0);
const p = fetch;
const m = {
...u,
Authorization: `Bearer ${s.apiKey}`
};
const embedMany = async (e, t) => {
if (e.length === 0) return [];
const n = `${c.replace(/\/$/, "")}/embeddings`;
return await withRemoteHttpResponse({
url: n,
fetchImpl: p,
ssrfPolicy: l,
signal: t,
init: {
method: "POST",
headers: m,
body: JSON.stringify({
model: f,
input: e
})
},
onResponse: async (t) => {
if (!t.ok) {
const e = redactProviderResponseErrorText(await readResponseTextLimited(t, COPILOT_ERROR_BODY_LIMIT_BYTES), m);
throw new Error(`GitHub Copilot embeddings HTTP ${t.status}: ${e}`);
}
return parseGitHubCopilotEmbeddingPayload(await readProviderJsonResponse(t, "github-copilot.embeddings", { maxBytes: COPILOT_EMBEDDINGS_RESPONSE_MAX_BYTES }), e.length);
}
});
};
return {
provider: {
id: COPILOT_EMBEDDING_PROVIDER_ID,
model: f,
embed: async (e, t) => {
const [n] = await embedMany([typeof e === "string" ? e : e.text], t?.signal);
return n ?? [];
},
embedBatch: async (e, t) => {
const n = e.map((e) => typeof e === "string" ? e : e.text);
if (t?.inputType === "query") return await Promise.all(n.map(async (e) => (await embedMany([e], t.signal))[0] ?? []));
return await embedMany(n, t?.signal);
}
},
runtime: {
id: COPILOT_EMBEDDING_PROVIDER_ID,
cacheKeyData: {
provider: COPILOT_EMBEDDING_PROVIDER_ID,
baseUrl: c,
model: f
}
}
};
}
};
//#endregion
export { githubCopilotMemoryEmbeddingProviderAdapter as t };