openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 7.26 kB
JavaScript
import{a as mapLmstudioWireModels,c as LMSTUDIO_DEFAULT_API_KEY_ENV_VAR,l as LMSTUDIO_LOCAL_API_KEY_PLACEHOLDER,n as resolveLmstudioProviderAuthMode,o as resolveLmstudioInferenceBase,r as resolvePersistedLmstudioApiKey,s as resolveLmstudioServerBase,t as hasLmstudioAuthorizationHeader,u as LMSTUDIO_PROVIDER_ID}from"./provider-auth-CKoC-ACN.mjs";import{CUSTOM_LOCAL_AUTH_MARKER,isKnownEnvApiKeyMarker,isNonSecretApiKeyMarker,normalizeApiKeyConfig,normalizeOptionalSecretInput}from"openclaw/plugin-sdk/provider-auth";import{asOptionalRecord,asPositiveSafeInteger,isRecord,normalizeUniqueTrimmedStringList}from"openclaw/plugin-sdk/string-coerce-runtime";import{LiveModelCatalogHttpError,runLiveProviderCatalog}from"openclaw/plugin-sdk/provider-catalog-live-runtime";import{createSubsystemLogger}from"openclaw/plugin-sdk/logging-core";import{resolveTimerTimeoutMs}from"openclaw/plugin-sdk/number-runtime";import{readProviderJsonArrayFieldResponse}from"openclaw/plugin-sdk/provider-http";import"openclaw/plugin-sdk/response-limit-runtime";import{fetchWithSsrFGuard}from"openclaw/plugin-sdk/ssrf-runtime";import{normalizeOptionalTrimmedStringRecord}from"openclaw/plugin-sdk/collection-input-runtime";import"openclaw/plugin-sdk/provider-auth-runtime";import{resolveConfiguredSecretInputString}from"openclaw/plugin-sdk/secret-input-runtime";import"openclaw/plugin-sdk/setup-tools";
//!extensions/lmstudio/src/runtime.ts
var LmstudioConfigResolutionError=class extends Error{};function buildLmstudioAuthHeaders(e){const t={...e.headers};const n=e.apiKey?.trim();if(n&&!(n===`lmstudio-local`)&&!isNonSecretApiKeyMarker(n)){for(const e of Object.keys(t))if(e.toLowerCase()===`authorization`)delete t[e];t.Authorization=`Bearer ${n}`}if(e.json)t[`Content-Type`]=`application/json`;return Object.keys(t).length>0?t:void 0}async function resolveLmstudioConfiguredApiKeyForProvider(e){const t=e.config;const n=(t?.models?.providers?.[e.providerId])?.apiKey;if(n===void 0||n===null||!t)return;const r=e.path??`models.providers[${JSON.stringify(e.providerId)}].apiKey`;const i=e.env??process.env;const a=normalizeOptionalSecretInput(n);const o=await resolveConfiguredSecretInputString({config:t,env:i,value:a??n,path:r,unresolvedReasonStyle:`detailed`});if(o.unresolvedRefReason){if(e.allowUnresolved)return;throw new LmstudioConfigResolutionError(`${r}: ${o.unresolvedRefReason}`)}const s=normalizeOptionalSecretInput(o.value);const c=s?normalizeApiKeyConfig(s).trim():``;if(!c)return;if(a!==void 0&&isKnownEnvApiKeyMarker(c))return normalizeOptionalSecretInput(i[c]);return isNonSecretApiKeyMarker(c)?void 0:c}async function resolveLmstudioConfiguredApiKey(e){return await resolveLmstudioConfiguredApiKeyForProvider({...e,providerId:LMSTUDIO_PROVIDER_ID})}async function resolveLmstudioProviderHeaders(e){const t=asOptionalRecord(e.headers);if(!t)return;if(!e.config)return normalizeOptionalTrimmedStringRecord(t);const n=e.path??`models.providers.lmstudio.headers`;const r={};for(const[i,a]of Object.entries(t)){const t=await resolveConfiguredSecretInputString({config:e.config,env:e.env??process.env,value:a,path:`${n}[${JSON.stringify(i)}]`,unresolvedReasonStyle:`detailed`});if(t.unresolvedRefReason)throw new LmstudioConfigResolutionError(`${n}.${i}: ${t.unresolvedRefReason}`);const o=t.value;if(!o)continue;r[i]=o}return Object.keys(r).length>0?r:void 0}
//!extensions/lmstudio/src/models.fetch.ts
const log=createSubsystemLogger(`extensions/lmstudio/models`);async function fetchLmstudioEndpoint(e){e.signal?.throwIfAborted();const t=resolveTimerTimeoutMs(e.timeoutMs,1);let n;let release;if(e.ssrfPolicy){const r=await fetchWithSsrFGuard({url:e.url,init:e.init,timeoutMs:t,signal:e.signal,fetchImpl:e.fetchImpl,policy:e.ssrfPolicy,auditContext:e.auditContext});n=r.response;release=r.release}else{n=await(e.fetchImpl??fetch)(e.url,{...e.init,signal:e.signal?AbortSignal.any([e.signal,AbortSignal.timeout(t)]):AbortSignal.timeout(t)});release=async()=>void 0}return{response:n,release:async()=>{if(!n.bodyUsed)n.body?.cancel().catch(()=>void 0);await release()}}}async function fetchLmstudioModels(e){const t=resolveLmstudioServerBase(e.baseUrl);const n=e.timeoutMs??5e3;try{const{response:r,release:i}=await fetchLmstudioEndpoint({url:`${t}/api/v1/models`,init:{headers:buildLmstudioAuthHeaders({apiKey:e.apiKey,headers:e.headers})},timeoutMs:n,signal:e.signal,fetchImpl:e.fetchImpl,ssrfPolicy:e.ssrfPolicy,auditContext:`lmstudio-model-discovery`});try{if(!r.ok)return{reachable:true,status:r.status,models:[]};const e=await readProviderJsonArrayFieldResponse(r,`LM Studio model list`,`models`);const t=e.filter(isRecord);if(e.length>0&&t.length===0)throw new Error(`LM Studio model list: malformed JSON response`);return{reachable:true,status:r.status,models:t}}finally{await i()}}catch(e){return{reachable:false,models:[],error:e}}}async function discoverLmstudioModels(e){const t=await fetchLmstudioModels({baseUrl:e.baseUrl,apiKey:e.apiKey,headers:e.headers,fetchImpl:e.fetchImpl});const n=e.quiet;if(!t.reachable||t.status!==void 0&&t.status>=400){const r=t.status===void 0?t.error:new LiveModelCatalogHttpError(`lmstudio`,t.status);if(e.discoveryMode===`strict`)throw r;if(!n)log.debug(`Failed to discover LM Studio models: ${String(r)}`);return[]}e.onListedModels?.(t.models);return mapLmstudioWireModels(t.models,`runtime`)}
//!extensions/lmstudio/src/catalog.ts
async function discoverLmstudioProvider(e,t){if(e.providerIds&&!e.providerIds.includes(`lmstudio`))return null;const n=e.config.models?.providers?.[LMSTUDIO_PROVIDER_ID];const{headers:r,auth:i,apiKey:a,...o}=n??{};const{apiKey:s,discoveryApiKey:c,profileId:l}=e.resolveProviderApiKey(LMSTUDIO_PROVIDER_ID);let u;let d;let f;try{u=await resolveLmstudioProviderHeaders({config:e.config,env:e.env,headers:n?.headers});d=hasLmstudioAuthorizationHeader(u);f=await resolveLmstudioConfiguredApiKey({config:e.config,env:e.env,allowUnresolved:d||Boolean(c)})}catch(e){if(e instanceof LmstudioConfigResolutionError)return null;throw e}const p=d?void 0:c??f;const m=s??n?.apiKey;const h=resolveLmstudioInferenceBase(n?.baseUrl);const g=!s&&!n&&!p;const _=!d&&c&&!isNonSecretApiKeyMarker(c)?l:void 0;const run=async()=>{let e;const r=!t&&n?.models?.length?n.models:await discoverLmstudioModels({onListedModels:t=>{e={baseUrl:h,modelIds:normalizeUniqueTrimmedStringList(t.flatMap(e=>[e.key,...e.loaded_instances?.map(e=>e?.id)??[]])),aliases:normalizeUniqueTrimmedStringList(t.flatMap(e=>e.key?.trim()?[e.selected_variant,...normalizeUniqueTrimmedStringList(e.variants)]:[]))}},baseUrl:h,apiKey:p??``,headers:u,quiet:g,...!g&&t?t:{}});const a=e?[{provider:LMSTUDIO_PROVIDER_ID,profileId:_,status:`ready`,modelIdCatalog:e}]:void 0;if(r.length===0&&(t?g:!s&&!n?.apiKey))return t&&a?{providers:{},outcomes:a}:null;const c=resolvePersistedLmstudioApiKey({currentApiKey:m,explicitAuth:i,fallbackApiKey:LMSTUDIO_DEFAULT_API_KEY_ENV_VAR,hasModels:r.length>0,hasAuthorizationHeader:d});const l=resolveLmstudioProviderAuthMode(c);return{...a?{outcomes:a}:{},provider:{...o,baseUrl:h,api:n?.api??`openai-completions`,...u?{headers:u}:{},...c?{apiKey:c}:{},...l?{auth:l}:{},models:r}}};return t?await runLiveProviderCatalog({providerId:LMSTUDIO_PROVIDER_ID,profileId:_,run}):await run()}export{discoverLmstudioProvider};