openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 6.53 kB
JavaScript
import{i as asOptionalObjectRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as filterStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{f as normalizeResolvedSecretInputString}from"./types.secrets-UWdyCdE6.mjs";import{n as extractEmbeddingUsage}from"./usage-cost-CjmYqezS.mjs";import{i as fetchWithSsrFGuard}from"./fetch-guard-B_7-F5Lc.mjs";import{n as redactProviderResponseErrorText}from"./provider-request-header-redaction-ZORqqaty.mjs";import{_ as readResponseTextLimited,h as readProviderJsonResponse}from"./provider-http-errors-CWZQ78Qm.mjs";import{M as sanitizeAndNormalizeEmbedding,O as buildRemoteBaseUrlPolicy,k as withRemoteHttpResponse}from"./gateway-startup-plugin-config-DVImEAD3.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./ssrf-runtime-Dx9DKr_m.mjs";import"./secret-input-FyvkT2mt.mjs";import"./provider-http-D0sVd8r_.mjs";import"./memory-core-host-engine-embeddings-C93s8VS5.mjs";import{a as resolveGithubCopilotDomain}from"./domain-Bn9uiqna.mjs";import{t as buildCopilotRuntimeHeaders}from"./runtime-identity-DPmesWFB.mjs";import{t as COPILOT_MODELS_LIST_DEFAULT_TIMEOUT_MS}from"./models-hnw5ORFF.mjs";import{t as resolveFirstGithubToken}from"./auth-B_iKeJvV.mjs";import{n as resolveCopilotRuntimeAuth}from"./runtime-auth-D8vhShbw.mjs";
//!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 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,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?.signal,init:{method:`POST`,headers:m,body:JSON.stringify({model:f,input:e})},onResponse:async n=>{if(!n.ok){const e=redactProviderResponseErrorText(await readResponseTextLimited(n,COPILOT_ERROR_BODY_LIMIT_BYTES),m);throw new Error(`GitHub Copilot embeddings HTTP ${n.status}: ${e}`)}const r=await readProviderJsonResponse(n,`github-copilot.embeddings`,{maxBytes:COPILOT_EMBEDDINGS_RESPONSE_MAX_BYTES});const i=parseGitHubCopilotEmbeddingPayload(r,e.length);t?.onUsage?.(extractEmbeddingUsage(r));return i}})};return{provider:{id:COPILOT_EMBEDDING_PROVIDER_ID,model:f,embed:async(e,t)=>{const[n]=await embedMany([typeof e===`string`?e:e.text],t);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))[0]??[]));return await embedMany(n,t)}},runtime:{id:COPILOT_EMBEDDING_PROVIDER_ID,cacheKeyData:{provider:COPILOT_EMBEDDING_PROVIDER_ID,baseUrl:c,model:f}}}}};export{githubCopilotMemoryEmbeddingProviderAdapter as t};