Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

30.6 KB
Raw Blame
import { VAULT_SCOPE_OAUTH_CONNECTIONS } from '@src/shared/constants/general';
import express from 'express';
import config from '../../../config';
import {
  CUSTOM_LLM_SETTINGS_KEY,
  DEFAULT_SMYTH_LLM_PROVIDERS_SETTINGS,
  SMYTH_LLM_PROVIDERS_SETTINGS_KEY,
} from '../../../constants';
import { includeTeamDetails } from '../../../middlewares/auth.mw';
import { cacheClient } from '../../../services/cache.service';
import Vault from '../../../services/SmythVault.class';
import {
  deleteTeamSettingsObj,
  getTeamSettingsObj,
  saveTeamSettingsObj,
} from '../../../services/team-data.service';
import { Team } from '../../../types';
import { isSmythStaff } from '../../../utils';
import { isCustomLLMAllowed } from '../../../utils/customLLM';
import { customLLMHelper } from '../../router.helpers/customLLM.helper';
import { userCustomLLMHelper } from '../../router.helpers/userCustomLLM.helper';
import { getVaultKeys, setVaultKey } from '../../router.utils';
const router = express.Router();

const vault = new Vault();
const OAUTH_SETTING_KEY = 'oauth';

// ------------------------------
// Internal helpers (pure, no side-effects)
// ------------------------------

/**
 * Safely parse JSON string to object, returns object as-is if not a string
 * @param data - The data to parse (string or object)
 * @param fallback - Fallback value if parsing fails (default: {})
 * @param context - Context string for error logging
 */
function safeJsonParse(data: any, fallback: any = {}, context: string = ''): any {
  if (typeof data === 'string') {
    try {
      return JSON.parse(data);
    } catch (e) {
      console.error(`[${context}] Failed to parse JSON string:`, e);
      return fallback;
    }
  }
  return data || fallback;
}

/**
 * Flattens legacy auth_settings.oauth_info into auth_settings (new structure),
 * removes disallowed fields, and guarantees the presence of a name key.
 */
function normalizeAuthSettingsObject(authSettings: any): any {
  if (!authSettings || typeof authSettings !== 'object') return authSettings;

  // Remove disallowed fields
  if (authSettings.team) delete authSettings.team;

  // Flatten oauth_info if present (legacy)
  if (authSettings.oauth_info && typeof authSettings.oauth_info === 'object') {
    const legacyInfo = authSettings.oauth_info;
    const keysToFlatten = [
      'oauth_keys_prefix',
      'service',
      'platform',
      'scope',
      'audience',
      'authorizationURL',
      'tokenURL',
      'clientID',
      'clientSecret',
      'requestTokenURL',
      'accessTokenURL',
      'userAuthorizationURL',
      'consumerKey',
      'consumerSecret',
    ];
    for (const k of keysToFlatten) {
      // Always use value from oauth_info if it exists (overwrite existing)
      if (legacyInfo[k] !== undefined) {
        authSettings[k] = legacyInfo[k];
      }
    }
    delete authSettings.oauth_info;
  }

  // Ensure a name key exists to classify as named connection (even if empty)
  if (typeof authSettings.name === 'undefined') authSettings.name = '';

  return authSettings;
}

/**
 * Merges new settings into existing settings with legacy compatibility.
 * - Existing auth_settings (if present) are the base; otherwise old flat entry is used (sans tokens)
 * - Deep-merges oauth_info (legacy), then flattens and sanitizes to new shape
 */
function mergeAuthSettings(existingEntry: any, incomingNewSettings: any): any {
  // Determine existing settings base
  let existingAuthSettings = {} as any;
  if (existingEntry?.auth_settings) {
    existingAuthSettings = existingEntry.auth_settings;
  } else if (existingEntry && Object.keys(existingEntry).length > 0 && !existingEntry.auth_data) {
    // Old structure: remove likely token fields
    const { primary: _p, secondary: _s, expires_in: _e, ...oldSettings } = existingEntry;
    existingAuthSettings = oldSettings;
  }

  // Merge incoming
  let merged = { ...existingAuthSettings, ...(incomingNewSettings || {}) } as any;

  // Deep-merge oauth_info if present
  if (existingAuthSettings?.oauth_info && incomingNewSettings?.oauth_info) {
    merged.oauth_info = { ...existingAuthSettings.oauth_info, ...incomingNewSettings.oauth_info };
  }

  // Normalize to new shape (flatten & sanitize)
  merged = normalizeAuthSettingsObject(merged);
  return merged;
}

/*
  some endpoints are duplicated in /page/builder.ts, the concept is we require it to handle page specific ACLs
*/

router.get('/keys', includeTeamDetails, async (req, res) => {
  const allKeys = await getVaultKeys(req);

  // when something goes wrong, allKeys is null
  if (!allKeys) {
    return res.status(400).json({ success: false, error: 'Error getting keys!' });
  }

  res.send({ success: true, data: allKeys, teamId: req?._team?.id });
});

router.post('/keys', includeTeamDetails, async (req, res) => {
  const result = await setVaultKey(req);

  if (!result?.success) {
    return res.status(400).json({ success: false, error: result?.error });
  }

  res.send({ success: true, data: result?.data });
});

router.put('/keys/:keyId', includeTeamDetails, async (req, res) => {
  const { keyId } = req.params;

  const result = await setVaultKey(req, keyId);

  if (!result?.success) {
    return res.status(400).json({ success: false, error: result?.error });
  }

  res.send({ success: true, data: result?.data });
});

router.get('/keys/:keyId', includeTeamDetails, async (req, res) => {
  const { keyId } = req.params;

  const team = req?._team?.id;

  const keyObj = await vault.get({ team, keyId }, req);

  // when something goes wrong, allKeys is null
  if (!keyObj) {
    return res.status(400).json({ success: false, error: 'Error getting key with ID.' });
  }

  res.send({ success: true, data: { [keyId]: keyObj } });
});

router.get('/keys/:keyId/exists', includeTeamDetails, async (req, res) => {
  const { keyId } = req.params;

  const team = req?._team?.id;

  const isKeyExists = await vault.exists({ team, keyId }, req);

  res.send({ success: true, data: isKeyExists });
});

router.get('/keys/name/:keyName', includeTeamDetails, async (req, res) => {
  const { keyName } = req.params;

  const team = req?._team?.id;

  const isKeyExists = await vault.get({ team, keyName }, req);

  res.send({ success: true, data: { data: isKeyExists } });
});

router.get('/keys/name/:keyName/exists', includeTeamDetails, async (req, res) => {
  const { keyName } = req.params;
  const { excludeId } = req.query;
  const team = req?._team?.id;

  const isKeyExists = await vault.exists({ team, keyName, excludeId: excludeId as string }, req);

  res.send({ success: true, data: isKeyExists });
});

router.delete('/keys/:keyId', includeTeamDetails, async (req, res) => {
  const { keyId } = req.params;

  const team = req?._team?.id;

  const result = await vault.delete(keyId, team, req);

  if (!result?.success) {
    return res.status(400).json({ success: false, error: result?.error });
  }

  res.send({ success: true, data: { keyId } });
});

/**
 * Sanitizes OAuth connections by replacing sensitive fields with placeholders.
 * Replaces tokens and expiration info with [REDACTED] to prevent exposure.
 */
function sanitizeOAuthConnections(connections: any): any {
  if (!connections || typeof connections !== 'object') return connections;

  const sanitized = {};

  for (const [key, value] of Object.entries(connections)) {
    if (!value || typeof value !== 'object') {
      sanitized[key] = value;
      continue;
    }

    // Deep clone the connection object
    const sanitizedConnection = JSON.parse(JSON.stringify(value));

    // Helper to sanitize sensitive fields
    const sanitizeTokenFields = (obj: any, location: string = '') => {
      if (!obj || typeof obj !== 'object') return;

      // List of sensitive field names to sanitize
      const sensitiveFields = [
        'primary',
        'secondary',
        'expires_in',
        'refresh_token',
        'access_token',
        'accessToken',
        'refreshToken',
        'token',
        'tokenSecret',
        'accessTokenSecret',
      ];

      for (const field of sensitiveFields) {
        if (obj[field] && typeof obj[field] === 'string' && obj[field] !== '[REDACTED]') {
          obj[field] = '[REDACTED]';
        }
      }

      // Also check for any field that looks like a token (JWT pattern or long string)
      // Exclude fields that are meant to be visible like clientID, clientSecret, consumerKey, etc.
      const excludedFields = [
        'clientID',
        'clientSecret',
        'consumerKey',
        'consumerSecret',
        'oauth_keys_prefix',
        'name',
        'platform',
        'service',
        'type',
        'scope',
        'audience',
        'authorizationURL',
        'tokenURL',
        'requestTokenURL',
        'accessTokenURL',
        'userAuthorizationURL',
      ];

      for (const [fieldName, fieldValue] of Object.entries(obj)) {
        if (
          typeof fieldValue === 'string' &&
          fieldValue.length > 40 &&
          !excludedFields.includes(fieldName) &&
          fieldValue !== '[REDACTED]'
        ) {
          // This might be a token - check for JWT pattern or OAuth token pattern
          const looksLikeToken =
            fieldValue.includes('.') || // JWT (has dots)
            fieldValue.match(/^[A-Za-z0-9_-]{40,}$/); // OAuth token pattern
          if (looksLikeToken) {
            obj[fieldName] = '[REDACTED]';
          }
        }
      }
    };

    // Sanitize auth_data (new structure)
    if (sanitizedConnection.auth_data && typeof sanitizedConnection.auth_data === 'object') {
      sanitizeTokenFields(sanitizedConnection.auth_data, 'auth_data');
    }

    // Sanitize auth_settings (might exist in legacy or contain misplaced tokens)
    if (
      sanitizedConnection.auth_settings &&
      typeof sanitizedConnection.auth_settings === 'object'
    ) {
      sanitizeTokenFields(sanitizedConnection.auth_settings, 'auth_settings');
    }

    // Sanitize root level (legacy structure)
    sanitizeTokenFields(sanitizedConnection, 'root');

    sanitized[key] = sanitizedConnection;
  }

  return sanitized;
}

function isVaultKey(key: string): string | null {
  // pattern is {{KEY(keyName)}}
  const pattern = /{{KEY\((.*?)\)}}/;
  const match = key.match(pattern);
  return match ? match[1] : null;
}

async function deleteVaultKeys(entry: any, team: string, req: any) {
  const vaultKeys = [];

  const entriesToCheck = [entry];
  // crawl the entry using BFS so that we can go deep if objects are nested
  while (entriesToCheck.length > 0) {
    const currentEntry = entriesToCheck.shift();
    // check if the current entry is
    // string: then check if it is vault key
    // object: add it to the entriesToCheck
    if (typeof currentEntry === 'string') {
      const keyNameNullable = isVaultKey(currentEntry);
      if (keyNameNullable) {
        vaultKeys.push(keyNameNullable);
      }
    } else if (typeof currentEntry === 'object') {
      entriesToCheck.push(...Object.values(currentEntry));
    }
  }

  console.log('WE SHOULD DELETE', vaultKeys);
  await Promise.all(
    vaultKeys.map(async (key) => {
      const result = await vault.delete(key, team, req);
      console.log('DELETED KEY. Result: ', key, result);
    }),
  );
}

async function storeSensitiveKeysInVault(entry: { [key: string]: any }, entryId: string, req: any) {
  let clonedEntry = JSON.parse(JSON.stringify(entry));
  const senstiveFields = ['clientID', 'clientSecret', 'consumerKey', 'consumerSecret'];

  const storeKeyPromises = senstiveFields.map(async (field) => {
    if (!clonedEntry[field]) return;
    const keyName = `${entryId}_${field}`;
    const keyData = {
      team: req?._team?.id,
      owner: req?._user?.email,
      name: keyName,
      key: clonedEntry[field],
      scope: [VAULT_SCOPE_OAUTH_CONNECTIONS],
    };
    const result = await vault.set({
      req,
      data: keyData,
      keyId: keyName,
    });
    console.log('STORED KEY. Result: ', result);
    if (!result?.success) {
      console.error(`Failed to store sensitive key ${field} in vault:`, result?.error);
      throw new Error(`Failed to store sensitive key ${field} in vault: ${result?.error}`);
    }

    clonedEntry[field] = `{{KEY(${keyName})}}`;
    return result;
  });

  try {
    await Promise.all(storeKeyPromises);
  } catch (error) {
    console.error('Failed to store sensitive keys in vault:', error);
    throw new Error('Failed to store sensitive keys in vault');
  }
  return clonedEntry;
}

router.get('/oauth-connections', includeTeamDetails, async (req, res) => {
  try {
    const settings = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);
    if (settings === null) {
      console.error('Failed to get OAuth settings due to an internal error.');
      return res
        .status(500)
        .json({ success: false, error: 'Failed to retrieve OAuth connections.' });
    }

    // Parse any stringified entries before sanitization
    const parsedSettings = Object.entries(settings || {}).reduce((acc, [key, value]) => {
      acc[key] = value;
      if (typeof value === 'string') {
        try {
          acc[key] = JSON.parse(value);
        } catch {}
      }
      return acc;
    }, {});

    // Sanitize the settings before sending to frontend
    const sanitizedSettings = sanitizeOAuthConnections(parsedSettings);
    res.json(sanitizedSettings);
  } catch (error) {
    console.error('Error fetching OAuth connections:', error?.message);
    res.status(500).json({
      success: false,
      error: 'An unexpected error occurred while fetching OAuth connections.',
    });
  }
});

router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
  const { entryId, data: newSettings } = req.body;

  // Validate entryId format
  if (
    !entryId ||
    typeof entryId !== 'string' ||
    !entryId.startsWith('OAUTH_') ||
    !entryId.endsWith('_TOKENS')
  ) {
    return res.status(400).json({ success: false, error: 'Invalid or missing entryId.' });
  }
  // Validate incoming settings data (basic check)
  if (!newSettings || typeof newSettings !== 'object' || Array.isArray(newSettings)) {
    return res
      .status(400)
      .json({ success: false, error: 'Invalid or missing connection settings data.' });
  }

  try {
    // 1. Fetch all existing OAuth settings for the team
    const existingSettingsMap = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);
    if (existingSettingsMap === null) {
      // Handle case where fetching settings failed (getTeamSettingsObj handles internal errors)
      return res
        .status(500)
        .json({ success: false, error: 'Failed to retrieve existing OAuth settings.' });
    }

    // 2. Get the specific entry being updated, parse if string, or default to an empty object
    let existingEntry = safeJsonParse(
      existingSettingsMap[entryId],
      {},
      `OAuth PUT existingEntry ${entryId}`,
    );
    // 3. Parse incoming newSettings if it's a string (shouldn't happen, but defensive coding)
    const parsedNewSettings = safeJsonParse(
      newSettings,
      newSettings,
      `OAuth PUT newSettings ${entryId}`,
    );
    // 4. Preserve existing auth_data (if it exists) OR migrate from old structure
    let preservedAuthData = existingEntry.auth_data || {}; // Keep existing tokens

    // If auth_data is empty but tokens exist at root level (old structure), migrate them
    if (
      !preservedAuthData.primary &&
      !preservedAuthData.secondary &&
      (existingEntry.primary || existingEntry.secondary)
    ) {
      // console.log('[OAuth Edit] Migrating tokens from old structure to new auth_data');
      preservedAuthData = {
        primary: existingEntry.primary || '',
        secondary: existingEntry.secondary || '',
        expires_in: existingEntry.expires_in || '',
      };
    }

    // await deleteVaultKeys(existingEntry, req?._team?.id, req);
    // 5. Merge and normalize the settings using helper (now both are guaranteed to be objects)
    let preparedNewSettings = mergeAuthSettings(existingEntry, parsedNewSettings);
    preparedNewSettings = await storeSensitiveKeysInVault(preparedNewSettings, entryId, req);

    // 6. Parse preservedAuthData if it's somehow still a string (defensive coding)
    preservedAuthData = safeJsonParse(
      preservedAuthData,
      {},
      `OAuth PUT preservedAuthData ${entryId}`,
    );
    // 7. Check if authentication-critical fields changed - if so, invalidate tokens
    // Handle both new structure (auth_settings.oauth_info) and legacy structure (oauth_info at root)
    const existingOAuthInfo =
      existingEntry.auth_settings?.oauth_info || existingEntry.oauth_info || {};
    const newOAuthInfo =
      preparedNewSettings.oauth_info || preparedNewSettings.auth_settings?.oauth_info || {};
    const authCriticalFields = [
      'clientID',
      'clientSecret',
      'scope',
      'audience',
      'authorizationURL',
      'tokenURL',
      'consumerKey',
      'consumerSecret',
      'requestTokenURL',
      'accessTokenURL',
      'userAuthorizationURL',
      'service',
    ];

    // Enhanced comparison for authentication-critical fields
    const hasAuthCriticalChanges = authCriticalFields.some((field) => {
      // Get values from both possible locations for existing data
      const oldValueFromOAuthInfo = existingOAuthInfo[field];
      const oldValueFromRoot = existingEntry[field]; // Legacy structure stores some fields at root
      const oldValueFromAuthSettings = existingEntry.auth_settings?.[field]; // New structure fields
      const oldValue =
        oldValueFromOAuthInfo !== undefined
          ? oldValueFromOAuthInfo
          : oldValueFromAuthSettings !== undefined
            ? oldValueFromAuthSettings
            : oldValueFromRoot;
      // Get values from both possible locations for new data
      const newValueFromOAuthInfo = newOAuthInfo[field];
      const newValueFromSettings = preparedNewSettings[field]; // New data might be at root of mergedAuthSettings
      const newValue =
        newValueFromOAuthInfo !== undefined ? newValueFromOAuthInfo : newValueFromSettings;
      // Normalize values: treat undefined, null, empty string, and whitespace as equivalent
      const normalizeValue = (val) => {
        if (val === undefined || val === null || val === '') return '';
        const stringVal = String(val).trim();
        return stringVal === '' ? '' : stringVal;
      };

      const normalizedOld = normalizeValue(oldValue);
      const normalizedNew = normalizeValue(newValue);

      const hasChanged = normalizedOld !== normalizedNew;

      return hasChanged;
    });

    // 8. Construct the final data object with the new structure
    // Clear tokens if auth-critical fields changed, otherwise preserve them
    const finalDataToSave = {
      auth_data: hasAuthCriticalChanges ? {} : preservedAuthData,
      auth_settings: preparedNewSettings,
    };

    // 9. Save the updated entry back using saveTeamSettingsObj
    const result = await saveTeamSettingsObj({
      req,
      settingKey: OAUTH_SETTING_KEY,
      entryId: entryId,
      data: finalDataToSave,
    });

    // 10. Handle save result
    if (!result.success) {
      console.error(
        `[PUT /oauth-connections] Failed to save settings for ${entryId}:`,
        result.error,
      );
      return res
        .status(500)
        .json({ success: false, error: result.error || 'Failed to save OAuth connection.' });
    }

    res.json({ success: true, data: finalDataToSave }); // Respond with the data that was saved
  } catch (error) {
    console.error(`[PUT /oauth-connections] Error processing request for ${entryId}:`, error);
    res.status(500).json({
      success: false,
      error: 'An unexpected error occurred while saving the OAuth connection.',
    });
  }
});

router.delete('/oauth-connections/:connectionId', includeTeamDetails, async (req, res) => {
  const { connectionId } = req.params;

  if (
    !connectionId ||
    typeof connectionId !== 'string' ||
    !connectionId.startsWith('OAUTH_') ||
    !connectionId.endsWith('_TOKENS')
  ) {
    return res
      .status(400)
      .json({ success: false, error: 'Invalid or missing connectionId parameter.' });
  }

  try {
    const existingSettingsMap = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);
    if (existingSettingsMap === null) {
      return res
        .status(500)
        .json({ success: false, error: 'Failed to retrieve existing OAuth settings.' });
    }

    let existingEntry = safeJsonParse(
      existingSettingsMap[connectionId],
      {},
      `OAuth DELETE existingEntry ${connectionId}`,
    );

    if (!existingEntry) {
      return res.status(404).json({ success: false, error: 'OAuth connection not found.' });
    }

    await deleteVaultKeys(existingEntry, req?._team?.id, req);

    const result = await deleteTeamSettingsObj(req, OAUTH_SETTING_KEY, connectionId);

    if (!result.success) {
      return res
        .status(500)
        .json({ success: false, error: result.error || 'Failed to delete OAuth connection.' });
    }

    res.status(200).json({ success: true });
  } catch (error) {
    console.error(`Error deleting OAuth connection ${connectionId}:`, error);
    res.status(500).json({
      success: false,
      error: 'An unexpected error occurred while deleting the OAuth connection.',
    });
  }
});

async function getRecommendedModels(req) {
  let recommendedModels = (await getTeamSettingsObj(req, SMYTH_LLM_PROVIDERS_SETTINGS_KEY)) || {};

  const hasBuiltinModels =
    req._team.subscription.plan?.properties?.flags?.hasBuiltinModels ||
    isSmythStaff(req._user) ||
    false;

  // if (hasBuiltinModels) {
  recommendedModels = {
    ...DEFAULT_SMYTH_LLM_PROVIDERS_SETTINGS,
    ...recommendedModels,
  };
  // }

  return recommendedModels;
}

router.get('/recommended-models', includeTeamDetails, async (req, res) => {
  const recommendedModels = await getRecommendedModels(req);
  res.send({ success: true, data: recommendedModels });
});

router.put('/recommended-models/:providerId', includeTeamDetails, async (req, res) => {
  const { providerId } = req.params;
  const { enabled } = req.body;

  const result = await saveTeamSettingsObj({
    req,
    entryId: providerId,
    data: { enabled: Boolean(enabled) },
    settingKey: SMYTH_LLM_PROVIDERS_SETTINGS_KEY,
  });

  if (!result?.success) {
    return res.status(400).json({ success: false, error: result?.error });
  }

  res.send({ success: true, data: result?.data });
});

// TODO: Refactor this file by splitting it into separate modules for better organization.
// Suggested structure:
// - vault/index.ts
// - vault/custom-llm.ts
// - vault/user-custom-llm.ts

// #region Custom LLM Routes
/**
 * Custom LLM Routes
 *
 * Provides endpoints for managing team-specific custom LLM models:
 * - CRUD operations for custom LLM configurations
 * - Access control based on team subscription and user permissions
 * - Cache management for custom model data
 */

const customLLMAccessMw = async (req: any, res: any, next: any) => {
  //* should be called after `includeTeamDetails` middleware to get the team details
  const teamDetails: Team = req._team;
  const userEmail: string = req?._user?.email || '';
  const flags: any = teamDetails?.subscription?.plan?.properties?.flags;

  if (
    !(
      teamDetails?.subscription?.properties?.customModelsEnabled ||
      flags?.['hasBuiltinModels'] ||
      flags?.['customModelsEnabled']
    ) &&
    !isSmythStaff(req?._user) &&
    !isCustomLLMAllowed(userEmail)
  ) {
    return res
      .status(403)
      .json({ success: false, error: 'Custom LLM models are not enabled for this team or user' });
  }

  return next();
};

// Create a middleware or helper function
const handleCustomLLMSave = async (req, res) => {
  const accessToken = req?.user?.accessToken;
  const teamId = req?._team?.id;
  const userEmail = req?._user?.email;
  const id = req.params?.id; // This will be undefined for POST requests

  try {
    const saveCustomLLM = await customLLMHelper.saveCustomLLM(req, {
      accessToken,
      teamId,
      userEmail,
      idToken: req?.session?.idToken,
      id,
      ...req.body,
    });

    // delete the custom LLM model cache
    await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
      console.warn('Error deleting custom LLM model cache:', error?.message);
    });

    res.status(200).json({ success: true, data: saveCustomLLM.data });
  } catch (error) {
    console.error('Error saving custom LLM model:', error?.message);
    res.status(500).json({ success: false, error: 'Error saving custom LLM model.' });
  }
};

const customLLMRouteMiddlewares = [includeTeamDetails, customLLMAccessMw];

router.post('/custom-llm/', customLLMRouteMiddlewares, handleCustomLLMSave);
router.put('/custom-llm/:id', customLLMRouteMiddlewares, handleCustomLLMSave);

router.get('/custom-llm', includeTeamDetails, async (req, res) => {
  try {
    const enterpriseModels = await customLLMHelper.getAllEnterpriseModels(req);
    res.status(200).json({ success: true, data: enterpriseModels });
  } catch (error) {
    res.status(500).json({ success: false, error: 'Error getting custom LLM models.' });
  }
});

router.get('/custom-llm/:id', includeTeamDetails, async (req, res) => {
  try {
    const entryId = req.params.id;

    const modelInfo = await customLLMHelper.getCustomLLMByEntryId(req, entryId);

    res.status(200).json({ success: true, data: modelInfo });
  } catch (error) {
    res.status(500).json({ success: false, error: 'Error getting custom LLM models.' });
  }
});

router.get('/custom-llm/with-credentials/:provider/:name', includeTeamDetails, async (req, res) => {
  try {
    const provider = req.params.provider;
    const name = req.params.name;
    const accessToken = req?.user?.accessToken;

    const customLLM = await customLLMHelper.getCustomLLMWithCredentials({
      accessToken,
      idToken: req?.session?.idToken,
      teamId: req?._team?.id,
      provider,
      name,
      req,
    });

    res.status(200).json({ success: true, data: customLLM.data });
  } catch (error) {
    res.status(500).json({ success: false, error: 'Error getting custom LLM models.' });
  }
});

router.delete('/custom-llm/:provider/:id', customLLMRouteMiddlewares, async (req, res) => {
  try {
    const accessToken = req?.user?.accessToken;
    const idToken = req?.session?.idToken;
    const teamId = req?._team?.id;
    const provider = req.params.provider;
    const id = req.params.id;

    // It's not necessary to await for deleting the custom LLM model
    customLLMHelper.deleteCustomLLM({
      req,
      accessToken,
      idToken,
      teamId,
      id,
      provider,
    });

    const deleteModel = await deleteTeamSettingsObj(req, CUSTOM_LLM_SETTINGS_KEY, id);

    // delete the custom LLM model cache
    await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
      console.warn('Error deleting custom LLM model cache:', error?.message);
    });

    res.status(200).json({ success: true, data: deleteModel.data });
  } catch (error) {
    res.status(500).json({ success: false, error: 'Error deleting custom LLM model.' });
  }
});
// #endregion

// #region User Custom LLM Routes
/**
 * User Custom LLM Routes
 *
 * Provides endpoints for managing team-specific user custom LLM models:
 * - CRUD operations for user custom LLM configurations
 * - No access control checks (ACL) required - available for all users
 * - Cache management for user custom model data
 * - Secure credential access via with-credentials endpoint
 *
 * Data structure:
 * {
 *   id: {
 *     name: <the friendly name>,
 *     id: <id of the entry>,
 *     modelId: <the model id entered by the user>,
 *     baseURL: <base url>,
 *     provider: <provider/compatible SDK, e.g., 'OpenAI', 'Ollama'>,
 *     features: <array of features, e.g., ['text', 'tools']>,
 *     fallbackLLM: <llm ID from builtin LLMs>
 *   }
 * }
 */

/**
 * Create or update a user custom LLM model
 */
const handleUserCustomLLMSave = async (req, res) => {
  const teamId = req?._team?.id;
  const userEmail = req?._user?.email;
  const id = req.params?.id; // This will be undefined for POST requests

  try {
    const saveUserCustomLLM = await userCustomLLMHelper.saveUserCustomLLM(req, {
      id,
      teamId,
      userEmail,
      ...req.body,
    });

    // Delete the user custom LLM model cache
    await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
      console.warn('Error deleting user custom LLM model cache:', error?.message);
    });

    res.status(200).json({ success: true, data: saveUserCustomLLM.data });
  } catch (error) {
    console.error('Error saving user custom LLM model:', error?.message);
    res.status(500).json({ success: false, error: 'Error saving user custom LLM model.' });
  }
};

/**
 * Create a new user custom LLM model
 * POST /user-custom-llm/
 */
router.post('/user-custom-llm/', includeTeamDetails, handleUserCustomLLMSave);

/**
 * Update an existing user custom LLM model
 * PUT /user-custom-llm/:id
 */
router.put('/user-custom-llm/:id', includeTeamDetails, handleUserCustomLLMSave);

/**
 * Get all user custom LLM models
 * GET /user-custom-llm
 */
router.get('/user-custom-llm', includeTeamDetails, async (req, res) => {
  try {
    const allUserCustomModels = await userCustomLLMHelper.getAllUserCustomLLMs(req);
    res.status(200).json({ success: true, data: allUserCustomModels });
  } catch (error) {
    console.error('Error getting user custom LLM models:', error?.message);
    res.status(500).json({ success: false, error: 'Error getting user custom LLM models.' });
  }
});

/**
 * Get a specific user custom LLM model by ID
 * GET /user-custom-llm/:id
 */
router.get('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {
  try {
    const entryId = req.params.id;
    const modelInfo = await userCustomLLMHelper.getUserCustomLLMByEntryId(req, entryId);

    if (!modelInfo) {
      return res.status(404).json({ success: false, error: 'User custom LLM model not found.' });
    }

    res.status(200).json({ success: true, data: modelInfo });
  } catch (error) {
    console.error('Error getting user custom LLM model:', error?.message);
    res.status(500).json({ success: false, error: 'Error getting user custom LLM model.' });
  }
});

/**
 * Delete a user custom LLM model
 * DELETE /user-custom-llm/:id
 */
router.delete('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {
  try {
    const teamId = req?._team?.id;
    const id = req.params.id;

    const deleteResult = await userCustomLLMHelper.deleteUserCustomLLM(req, id);

    // Delete the user custom LLM model cache
    await cacheClient.del(config.cache.getCustomModelsCacheKey(teamId)).catch((error) => {
      console.warn('Error deleting user custom LLM model cache:', error?.message);
    });

    res.status(200).json({ success: true, data: deleteResult.data });
  } catch (error) {
    console.error('Error deleting user custom LLM model:', error?.message);
    res.status(500).json({ success: false, error: 'Error deleting user custom LLM model.' });
  }
});

// #endregion

export default router;