Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(lmstudio): auto-load embedding models via native REST API
Adam Eivy0600c48c62fa
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex 624badffb6..6afad259c9 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -520,6 +520,13 @@ This release introduces a structured changelog documentation system for creating### Periodic Zombie Agent Cleanup- **Runtime orphan detection**: `cleanupOrphanedAgents()` now runs every health check cycle (15 min) instead of only at daemon startup, catching agents whose process died mid-run without proper state cleanup+### LM Studio API Modernization & Embedding Auto-Load+- **Auto-load embedding models**: When an embedding request encounters "No models loaded", the system now discovers downloaded embedding models via LM Studio's native REST API (`GET /api/v0/models`) and auto-loads one via `POST /api/v1/models/load`+- **Dynamic model discovery**: Embedding model ID is no longer hardcoded — the system detects the actual loaded/available model and uses its correct identifier+- **Native REST API for model management**: `lmStudioManager.js` now uses LM Studio's native `POST /api/v1/models/load` and `POST /api/v1/models/unload` endpoints instead of workarounds (test completions for loading, stub responses for unloading)+- **Rich model metadata**: `getLoadedModels()` and `getAvailableModels()` now return model type, architecture, quantization, state, and context length via the `/api/v0/models` endpoint+- **Model download API**: `downloadModel()` now uses LM Studio's `POST /api/v1/models/download` endpoint instead of returning a stub error+### CoS Learning Task Type Classification- **Fixed "unknown" task type pollution**: `extractTaskType()` was returning "unknown" for all internal/system tasks that didn't have specific metadata markers, causing 741+ misclassified entries that skewed learning insights and triggered false "investigate root cause" recommendations- **Task metadata forwarding**: Agent registration now forwards key task metadata fields (`analysisType`, `reviewType`, `app`, `selfImprovementType`, `missionName`, `missionId`) so the learning system can properly classify agents after completiondiff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 6e25f50f6e..129ba932d7 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -99,25 +99,40 @@ async function getLoadedModels(forceRefresh = false) {return []}- try {- const response = await lmStudioRequest('/v1/models')- loadedModels = (response.data || []).map(model => ({+ // Use native REST API for richer model info (type, state, architecture)+ const nativeModels = await lmStudioRequest('/api/v0/models').catch(() => null)+ if (nativeModels?.data) {+ loadedModels = nativeModels.data+ .filter(model => model.state === 'loaded')+ .map(model => ({+ id: model.id,+ object: model.object || 'model',+ type: model.type,+ arch: model.arch,+ quantization: model.quantization,+ state: model.state,+ maxContextLength: model.max_context_length,+ ownedBy: model.publisher+ }))+ return loadedModels+ }++ // Fallback to OpenAI-compat endpoint+ const response = await lmStudioRequest('/v1/models').catch(() => null)+ if (response?.data) {+ loadedModels = response.data.map(model => ({id: model.id,object: model.object,created: model.created,ownedBy: model.owned_by}))- return loadedModels- } catch (err) {- console.error(`⚠️ Failed to get LM Studio models: ${err.message}`)- return []}+ return loadedModels}/**- * Get available models in LM Studio catalog- * Note: This requires LM Studio's /lmstudio.* endpoints if available- * @returns {Promise<Array>} - Available models+ * Get all downloaded models (loaded and not-loaded)+ * @returns {Promise<Array>} - All downloaded models with state info*/async function getAvailableModels() {const available = await checkLMStudioAvailable()@@ -125,43 +140,55 @@ async function getAvailableModels() {return []}- // LM Studio doesn't have a public catalog API by default- // Return loaded models as available for now+ const response = await lmStudioRequest('/api/v0/models').catch(() => null)+ if (response?.data) {+ availableModels = response.data.map(model => ({+ id: model.id,+ type: model.type,+ arch: model.arch,+ publisher: model.publisher,+ quantization: model.quantization,+ state: model.state,+ maxContextLength: model.max_context_length+ }))+ return availableModels+ }++ // Fallback to loaded models onlyreturn getLoadedModels(true)}/*** Download a model from LM Studio catalog- * Note: Requires LM Studio API support for downloads- ** @param {string} modelId - Model identifier to download* @returns {Promise<Object>} - Download result*/async function downloadModel(modelId) {const available = await checkLMStudioAvailable()if (!available) {- return {- success: false,- error: 'LM Studio not available'- }+ return { success: false, error: 'LM Studio not available' }}- // LM Studio doesn't have a public download API- // This would need to be implemented via LM Studio's developer API- console.log(`📥 Model download requested: ${modelId}`)+ console.log(`📥 Downloading model: ${modelId}`)cosEvents.emit('lmstudio:downloadRequested', { modelId })- return {- success: false,- error: 'Model downloading not yet supported via API',- modelId,- instruction: 'Please download the model manually via LM Studio UI'+ const response = await lmStudioRequest('/api/v1/models/download', {+ method: 'POST',+ body: JSON.stringify({ model: modelId }),+ timeout: 10000+ }).catch(err => ({ _err: err.message }))++ if (response._err) {+ console.error(`⚠️ Failed to start download for ${modelId}: ${response._err}`)+ return { success: false, error: response._err, modelId }}++ return { success: true, modelId, ...response }}/*** Load a model into LM Studio memory- * @param {string} modelId - Model identifier to load+ * @param {string} modelId - Model identifier (publisher/model-name format)* @returns {Promise<Object>} - Load result*/async function loadModel(modelId) {@@ -170,35 +197,29 @@ async function loadModel(modelId) {return { success: false, error: 'LM Studio not available' }}- try {- // Try to make a test completion to trigger model loading- await lmStudioRequest('/v1/chat/completions', {- method: 'POST',- body: JSON.stringify({- model: modelId,- messages: [{ role: 'user', content: 'test' }],- max_tokens: 1- }),- timeout: 60000 // Loading can take a while- })+ // Use the native REST API load endpoint+ const response = await lmStudioRequest('/api/v1/models/load', {+ method: 'POST',+ body: JSON.stringify({ model: modelId }),+ timeout: 60000 // Loading can take a while+ }).catch(err => ({ _err: err.message }))- // Refresh loaded models- await getLoadedModels(true)+ if (response._err) {+ console.error(`⚠️ Failed to load model ${modelId}: ${response._err}`)+ return { success: false, error: response._err, modelId }+ }- console.log(`📦 Model loaded: ${modelId}`)- cosEvents.emit('lmstudio:modelLoaded', { modelId })+ // Refresh loaded models+ await getLoadedModels(true)- return { success: true, modelId }- } catch (err) {- console.error(`⚠️ Failed to load model ${modelId}: ${err.message}`)- return { success: false, error: err.message, modelId }- }+ console.log(`📦 Model loaded: ${modelId}`)+ cosEvents.emit('lmstudio:modelLoaded', { modelId })++ return { success: true, modelId, ...response }}/*** Unload a model from LM Studio memory- * Note: Requires LM Studio API support for unloading- ** @param {string} modelId - Model identifier to unload* @returns {Promise<Object>} - Unload result*/@@ -208,16 +229,24 @@ async function unloadModel(modelId) {return { success: false, error: 'LM Studio not available' }}- // LM Studio doesn't have a public unload API- console.log(`📤 Model unload requested: ${modelId}`)- cosEvents.emit('lmstudio:unloadRequested', { modelId })+ const response = await lmStudioRequest('/api/v1/models/unload', {+ method: 'POST',+ body: JSON.stringify({ model: modelId }),+ timeout: 15000+ }).catch(err => ({ _err: err.message }))- return {- success: false,- error: 'Model unloading not yet supported via API',- modelId,- instruction: 'Please unload the model manually via LM Studio UI'+ if (response._err) {+ console.error(`⚠️ Failed to unload model ${modelId}: ${response._err}`)+ return { success: false, error: response._err, modelId }}++ // Refresh loaded models+ await getLoadedModels(true)++ console.log(`📤 Model unloaded: ${modelId}`)+ cosEvents.emit('lmstudio:modelUnloaded', { modelId })++ return { success: true, modelId }}/**@@ -310,28 +339,40 @@ async function getEmbeddings(text, options = {}) {return { success: false, error: 'LM Studio not available' }}- const model = options.model || 'text-embedding-nomic-embed-text-v2-moe'+ // Auto-discover an embedding model if none specified+ let model = options.model+ if (!model) {+ const models = await getAvailableModels()+ const embeddingModel = models.find(m => m.type === 'embeddings' && m.state === 'loaded')+ || models.find(m => m.type === 'embeddings')+ if (embeddingModel) {+ // Load it if not already loaded+ if (embeddingModel.state !== 'loaded') {+ await loadModel(embeddingModel.id)+ }+ model = embeddingModel.id+ } else {+ return { success: false, error: 'No embedding model available in LM Studio' }+ }+ }- try {- const response = await lmStudioRequest('/v1/embeddings', {- method: 'POST',- body: JSON.stringify({- model,- input: text- }),- timeout: options.timeout || 10000- })+ const response = await lmStudioRequest('/v1/embeddings', {+ method: 'POST',+ body: JSON.stringify({ model, input: text }),+ timeout: options.timeout || 10000+ }).catch(err => ({ _err: err.message }))- const embedding = response.data?.[0]?.embedding || []+ if (response._err) {+ return { success: false, error: response._err, model }+ }- return {- success: true,- embedding,- model,- dimensions: embedding.length- }- } catch (err) {- return { success: false, error: err.message, model }+ const embedding = response.data?.[0]?.embedding || []++ return {+ success: true,+ embedding,+ model,+ dimensions: embedding.length}}diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 5a41893004..b0799b22b2 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -11,6 +11,80 @@ import { getProviderById } from './providers.js';// Cache for embedding config (loaded from CoS config)let embeddingConfig = null;let initialized = false;+let modelEnsured = false;++/**+ * Get the LM Studio base URL from config+ */+function getBaseUrl(config) {+ return config.embeddingEndpoint.replace(/\/v1\/embeddings$/, '');+}++/**+ * Discover and auto-load an embedding model in LM Studio.+ * Uses the REST API to find downloaded embedding models and load one if needed.+ */+async function ensureEmbeddingModelLoaded(config) {+ if (modelEnsured) return;++ const baseUrl = getBaseUrl(config);+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 10000);++ // Query LM Studio's native API for all downloaded models+ const response = await fetch(`${baseUrl}/api/v0/models`, {+ signal: controller.signal+ });+ clearTimeout(timeout);++ if (!response.ok) return;++ const models = await response.json();+ const allModels = models.data || [];+ const embeddingModels = allModels.filter(m => m.type === 'embeddings');++ // Check if an embedding model is already loaded+ const loaded = embeddingModels.find(m => m.state === 'loaded');+ if (loaded) {+ config.embeddingModel = loaded.id;+ modelEnsured = true;+ console.log(`📚 Embedding model already loaded: ${loaded.id}`);+ return;+ }++ // No embedding model loaded — try to load the configured one first, then any available+ const candidates = [+ embeddingModels.find(m => m.id.includes(config.embeddingModel)),+ ...embeddingModels+ ].filter(Boolean);++ if (candidates.length === 0) {+ console.warn(`⚠️ No embedding models found in LM Studio — download one in the Discover tab`);+ return;+ }++ const modelToLoad = candidates[0];+ console.log(`📦 Auto-loading embedding model: ${modelToLoad.id}`);++ const loadController = new AbortController();+ const loadTimeout = setTimeout(() => loadController.abort(), 60000);+ const loadResponse = await fetch(`${baseUrl}/api/v1/models/load`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: modelToLoad.id }),+ signal: loadController.signal+ });+ clearTimeout(loadTimeout);++ if (loadResponse.ok) {+ config.embeddingModel = modelToLoad.id;+ modelEnsured = true;+ console.log(`✅ Embedding model loaded: ${modelToLoad.id}`);+ } else {+ const err = await loadResponse.text();+ console.error(`❌ Failed to auto-load embedding model ${modelToLoad.id}: ${err}`);+ }+}/*** Initialize embedding config from provider settings@@ -47,7 +121,7 @@ export function setEmbeddingConfig(config) {}/**- * Check if LM Studio is available+ * Check if LM Studio is available and ensure embedding model is loaded*/export async function checkAvailability() {await initConfig();@@ -55,28 +129,44 @@ export async function checkAvailability() {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 5000);- try {- const response = await fetch(`${config.embeddingEndpoint.replace('/v1/embeddings', '/v1/models')}`, {- method: 'GET',- signal: controller.signal- });-+ const response = await fetch(`${config.embeddingEndpoint.replace('/v1/embeddings', '/v1/models')}`, {+ method: 'GET',+ signal: controller.signal+ }).catch(err => {clearTimeout(timeout);+ return { ok: false, _err: err.message };+ });- if (!response.ok) {- return { available: false, error: `LM Studio returned ${response.status}`, endpoint: config.embeddingEndpoint };- }+ clearTimeout(timeout);- const data = await response.json();- return {- available: true,- models: data.data?.map(m => m.id) || [],- endpoint: config.embeddingEndpoint- };- } catch (err) {- clearTimeout(timeout);- return { available: false, error: err.message, endpoint: config.embeddingEndpoint };+ if (!response.ok) {+ return { available: false, error: response._err || `LM Studio returned ${response.status}`, endpoint: config.embeddingEndpoint };+ }++ const data = await response.json();+ const models = data.data?.map(m => m.id) || [];++ // If no embedding models are loaded, try to auto-load one+ const hasEmbeddingModel = models.some(id => id.includes('embed'));+ if (!hasEmbeddingModel) {+ await ensureEmbeddingModelLoaded(config).catch(err =>+ console.warn(`⚠️ Could not auto-load embedding model: ${err.message}`)+ );+ } else {+ // Use the loaded embedding model's actual ID+ const embeddingModelId = models.find(id => id.includes('embed'));+ if (embeddingModelId) {+ config.embeddingModel = embeddingModelId;+ modelEnsured = true;+ }}++ return {+ available: true,+ models,+ embeddingModel: config.embeddingModel,+ endpoint: config.embeddingEndpoint+ };}/**@@ -90,6 +180,13 @@ export async function generateEmbedding(text) {return null;}+ // Ensure embedding model is loaded before requesting+ if (!modelEnsured) {+ await ensureEmbeddingModelLoaded(config).catch(err =>+ console.warn(`⚠️ Could not ensure embedding model: ${err.message}`)+ );+ }+// Truncate very long texts to prevent issuesconst maxChars = 8000;const truncatedText = text.length > maxChars ? text.substring(0, maxChars) : text;@@ -124,6 +221,13 @@ export async function generateBatchEmbeddings(texts) {return [];}+ // Ensure embedding model is loaded before requesting+ if (!modelEnsured) {+ await ensureEmbeddingModelLoaded(config).catch(err =>+ console.warn(`⚠️ Could not ensure embedding model: ${err.message}`)+ );+ }+// LM Studio supports batch embeddings via array inputconst maxChars = 8000;const truncatedTexts = texts.map(t => t.length > maxChars ? t.substring(0, maxChars) : t);