import path from 'path'; import { ModelEntry, ProviderName, detectProvider } from './models'; import { AgentConfig } from './agents'; import { SynthOSConfig } from './init'; let _settings: Partial|undefined; export interface ServiceConfig { apiKey: string; enabled: boolean; } export type ServicesConfig = { [serviceId: string]: ServiceConfig }; // Re-export ModelEntry from models so existing imports from settings still work export type { ModelEntry } from './models'; /** * V1 settings shape (flat, single model). Used as migration source. */ export interface SettingsV1 { serviceApiKey: string; model: string; imageQuality: 'standard' | 'hd'; instructions?: string; logCompletions?: boolean; theme?: string; services?: ServicesConfig; } /** * V2 settings shape with versioned models array. */ export interface CacheSettings { enabled: boolean; } export interface PersonalInfo { name?: string; address?: string; details?: string; } export interface BusinessInfo { name?: string; locations?: string; hours?: string; details?: string; } export interface UserProfile { personal?: PersonalInfo; business?: BusinessInfo; } export interface SettingsV2 { version: 2; theme: string; models: ModelEntry[]; features: string[]; services?: ServicesConfig; connectors?: ServicesConfig; agents?: AgentConfig[]; toolbarPosition?: 'left' | 'right'; cache?: CacheSettings; profile?: UserProfile; } export const DefaultSettings: SettingsV2 = { version: 2, theme: 'nebula-dawn', models: [ { use: 'builder', provider: 'Anthropic', configuration: { apiKey: '', model: '' }, imageQuality: 'standard', instructions: '', logCompletions: false, }, { use: 'chat', provider: 'Anthropic', configuration: { apiKey: '', model: '' }, imageQuality: 'standard', instructions: '', logCompletions: false, }, ], features: [], services: {}, connectors: {}, agents: [], toolbarPosition: 'left', }; /** * Find a model entry by its `use` field. Falls back to default if not found. */ export function getModelEntry(settings: SettingsV2, use: 'builder' | 'chat'): ModelEntry { const entry = settings.models.find(m => m.use === use); if (entry) return entry; return DefaultSettings.models.find(m => m.use === use)!; } /** * Migrate a v1 settings object to v2 by detecting provider from model prefix * and wrapping fields into the new configuration object. */ function migrateV1toV2(raw: Record): SettingsV2 { const v1 = raw as unknown as SettingsV1; const rawModel = v1.model ?? ''; // Migrate retired model names const model = rawModel === 'claude-opus-4-5' ? 'claude-opus-4-6' : rawModel; const detected = detectProvider(model); const provider: ProviderName = detected?.name ?? 'Anthropic'; // Default chat to claude-haiku-4-5 when migrating from an Anthropic model const chatModel = provider === 'Anthropic' ? 'claude-haiku-4-5' : model; return { version: 2, theme: v1.theme ?? 'nebula-dusk', models: [ { use: 'builder', provider, configuration: { apiKey: v1.serviceApiKey ?? '', model, }, imageQuality: v1.imageQuality ?? 'standard', instructions: v1.instructions ?? '', logCompletions: v1.logCompletions ?? false, }, { use: 'chat', provider, configuration: { apiKey: v1.serviceApiKey ?? '', model: chatModel, }, imageQuality: v1.imageQuality ?? 'standard', instructions: v1.instructions ?? '', logCompletions: v1.logCompletions ?? false, }, ], features: [], services: v1.services, }; } export async function hasConfiguredSettings(config: SynthOSConfig): Promise { const settings = await loadSettings(config); const builder = getModelEntry(settings, 'builder'); if (typeof builder.configuration.apiKey !== 'string' || builder.configuration.apiKey.length == 0) { return false; } if (typeof builder.configuration.model !== 'string' || builder.configuration.model.length == 0) { return false; } return true; } export async function loadSettings(config: SynthOSConfig): Promise { const sp = config.storageProvider; if (_settings == undefined) { const filename = path.join(config.pagesFolder, 'settings.json'); if (await sp.checkIfExists(filename)) { try { const raw = JSON.parse(await sp.loadFile(filename)); if (!raw.version) { // V1 file — migrate console.log('Migrating settings.json from v1 to v2...'); const migrated = migrateV1toV2(raw); _settings = migrated; await sp.saveFile(filename, JSON.stringify(migrated, null, 4)); } else { _settings = raw as Partial; } } catch { // Invalid JSON } } } const merged = {...DefaultSettings, ..._settings, models: _settings?.models ?? DefaultSettings.models}; // Auto-migrate: copy services into connectors if connectors is empty const connectors = merged.connectors ?? {}; const services = merged.services ?? {}; if (Object.keys(connectors).length === 0 && Object.keys(services).length > 0) { merged.connectors = { ...services }; } return merged; } export async function saveSettings(config: SynthOSConfig, settings: Partial): Promise { const sp = config.storageProvider; _settings = {..._settings, ...settings}; if (settings.models) { _settings.models = settings.models; } _settings.version = 2; await sp.saveFile(path.join(config.pagesFolder, 'settings.json'), JSON.stringify(_settings, null, 4)); } /** * Render the user profile as markdown for injection into the builder's * context section. Each field is optional; sections with no * filled fields are omitted entirely. Returns an empty string when nothing * would be rendered. */ export function renderUserProfile(profile: UserProfile | undefined): string { if (!profile) return ''; const blocks: string[] = []; const personalFields: Array<{ label: string; value?: string }> = [ { label: 'Name', value: profile.personal?.name }, { label: 'Address', value: profile.personal?.address }, { label: 'Details', value: profile.personal?.details }, ]; const personalBody = renderProfileSection(personalFields); if (personalBody) blocks.push(`## Personal Information\n\n${personalBody}`); const businessFields: Array<{ label: string; value?: string }> = [ { label: 'Name', value: profile.business?.name }, { label: 'Locations', value: profile.business?.locations }, { label: 'Hours', value: profile.business?.hours }, { label: 'Details', value: profile.business?.details }, ]; const businessBody = renderProfileSection(businessFields); if (businessBody) blocks.push(`## Business Information\n\n${businessBody}`); return blocks.join('\n\n'); } function renderProfileSection(fields: Array<{ label: string; value?: string }>): string { const parts: string[] = []; for (const { label, value } of fields) { if (value && value.trim().length > 0) { parts.push(`**${label}:**\n${value.trim()}`); } } return parts.join('\n\n'); }