File size: 24,777 Bytes
3d50167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// ===== KIMI INDEXEDDB DATABASE SYSTEM =====
class KimiDatabase {
    constructor() {
        this.dbName = "KimiDB";
        this.db = new Dexie(this.dbName);
        this.db.version(3).stores({
            conversations: "++id,timestamp,favorability,character",
            preferences: "key",
            settings: "category",
            personality: "[character+trait],character",
            llmModels: "id",
            memories: "++id,[character+category],character,timestamp,isActive"
        });
    }

    async init() {
        await this.db.open();
        await this.initializeDefaultsIfNeeded();
        return this.db;
    }

    async initializeDefaultsIfNeeded() {
        // Use unified trait defaults from emotion system - CRITICAL FIX
        const getUnifiedDefaults = () => {
            if (window.KimiEmotionSystem) {
                const emotionSystem = new window.KimiEmotionSystem(this);
                return emotionSystem.TRAIT_DEFAULTS;
            }
            // Fallback to match KimiEmotionSystem exactly
            return {
                affection: 65,
                playfulness: 55,
                intelligence: 70,
                empathy: 75,
                humor: 60,
                romance: 50
            };
        };

        const defaults = getUnifiedDefaults();

        const defaultPreferences = [
            { key: "selectedLanguage", value: "en" },
            { key: "selectedVoice", value: "Microsoft Eloise Online" },
            { key: "voiceRate", value: 1.1 },
            { key: "voicePitch", value: 1.1 },
            { key: "voiceVolume", value: 0.8 },
            { key: "selectedCharacter", value: "kimi" },
            { key: "colorTheme", value: "purple" },
            { key: "interfaceOpacity", value: 0.8 },
            { key: "animationsEnabled", value: true },
            { key: "showTranscript", value: true },
            { key: "llmProvider", value: "openrouter" },
            { key: "llmBaseUrl", value: "https://openrouter.ai/api/v1/chat/completions" },
            { key: "llmModelId", value: "mistralai/mistral-small-3.2-24b-instruct" },
            { key: "llmApiKey", value: "" },
            { key: "apiKey_openai", value: "" },
            { key: "apiKey_groq", value: "" },
            { key: "apiKey_together", value: "" },
            { key: "apiKey_deepseek", value: "" },
            { key: "apiKey_custom", value: "" }
        ];
        const defaultSettings = [
            {
                category: "llm",
                settings: {
                    temperature: 0.9,
                    maxTokens: 100,
                    top_p: 0.9,
                    frequency_penalty: 0.3,
                    presence_penalty: 0.3
                }
            }
        ];

        const getCharacterDefaults = () => {
            if (!window.KIMI_CHARACTERS) return {};

            const characterDefaults = {};
            Object.keys(window.KIMI_CHARACTERS).forEach(characterKey => {
                const character = window.KIMI_CHARACTERS[characterKey];
                if (character && character.traits) {
                    characterDefaults[characterKey] = character.traits;
                }
            });
            return characterDefaults;
        };

        const personalityDefaults = getCharacterDefaults();

        const defaultLLMModels = [
            {
                id: "mistralai/mistral-small-3.2-24b-instruct",
                name: "Mistral Small 3.2",
                provider: "openrouter",
                apiKey: "",
                config: { temperature: 0.9, maxTokens: 100 },
                added: new Date().toISOString(),
                lastUsed: null
            }
        ];

        const prefCount = await this.db.preferences.count();
        if (prefCount === 0) {
            for (const pref of defaultPreferences) {
                await this.db.preferences.put({ ...pref, updated: new Date().toISOString() });
            }
            const characters = Object.keys(window.KIMI_CHARACTERS || { kimi: {} });
            for (const character of characters) {
                const prompt = window.KIMI_CHARACTERS[character]?.defaultPrompt || "";
                await this.db.preferences.put({
                    key: `systemPrompt_${character}`,
                    value: prompt,
                    updated: new Date().toISOString()
                });
            }
        }

        const setCount = await this.db.settings.count();
        if (setCount === 0) {
            for (const setting of defaultSettings) {
                await this.db.settings.put({ ...setting, updated: new Date().toISOString() });
            }
        }

        const persCount = await this.db.personality.count();
        if (persCount === 0) {
            const characters = Object.keys(window.KIMI_CHARACTERS || { kimi: {} });
            for (const character of characters) {
                // Use real character-specific traits, not generic defaults
                const characterTraits = personalityDefaults[character] || {};
                const traitsToInitialize = [
                    { trait: "affection", value: characterTraits.affection || defaults.affection },
                    { trait: "playfulness", value: characterTraits.playfulness || defaults.playfulness },
                    { trait: "intelligence", value: characterTraits.intelligence || defaults.intelligence },
                    { trait: "empathy", value: characterTraits.empathy || defaults.empathy },
                    { trait: "humor", value: characterTraits.humor || defaults.humor },
                    { trait: "romance", value: characterTraits.romance || defaults.romance }
                ];

                for (const trait of traitsToInitialize) {
                    await this.db.personality.put({ ...trait, character, updated: new Date().toISOString() });
                }
            }
        }

        const llmCount = await this.db.llmModels.count();
        if (llmCount === 0) {
            for (const model of defaultLLMModels) {
                await this.db.llmModels.put(model);
            }
        }

        // Fix: never recreate default conversations
        const convCount = await this.db.conversations.count();
        if (convCount === 0) {
            // Ne rien faire : aucune conversation par défaut
        }
    }

    async saveConversation(userText, kimiResponse, favorability, timestamp = new Date(), character = null) {
        if (!character) character = await this.getSelectedCharacter();
        const conversation = {
            user: userText,
            kimi: kimiResponse,
            favorability: favorability,
            timestamp: timestamp.toISOString(),
            date: timestamp.toDateString(),
            character: character
        };
        return this.db.conversations.add(conversation);
    }

    async getRecentConversations(limit = 10, character = null) {
        if (!character) character = await this.getSelectedCharacter();
        // Dexie limitation: orderBy() cannot follow a where() chain.
        // Use compound index path by querying all then sorting, or use a custom index strategy.
        // Here we query filtered by character, then sort in JS and take the last N.
        return this.db.conversations
            .where("character")
            .equals(character)
            .toArray()
            .then(arr => {
                arr.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
                return arr.slice(-limit);
            });
    }

    async getAllConversations(character = null) {
        try {
            if (!character) character = await this.getSelectedCharacter();
            return await this.db.conversations.where("character").equals(character).toArray();
        } catch (error) {
            console.warn("Error getting all conversations:", error);
            return [];
        }
    }

    async setPreference(key, value) {
        if (key === "openrouterApiKey" || key === "llmApiKey" || key.startsWith("apiKey_")) {
            const isValid = window.KIMI_VALIDATORS?.validateApiKey(value) || window.KimiSecurityUtils?.validateApiKey(value);
            if (!isValid && value.length > 0) {
                throw new Error("Invalid API key format");
            }
            // Store keys in plain text (no encryption) per request
            if (window.KimiCacheManager && typeof window.KimiCacheManager.set === "function") {
                window.KimiCacheManager.set(`pref_${key}`, value, 60000);
            }
            return this.db.preferences.put({
                key: key,
                value: value,
                // do not set encrypted flag anymore
                updated: new Date().toISOString()
            });
        }

        // Update cache for regular preferences
        if (window.KimiCacheManager && typeof window.KimiCacheManager.set === "function") {
            window.KimiCacheManager.set(`pref_${key}`, value, 60000);
        }

        return this.db.preferences.put({
            key: key,
            value: value,
            updated: new Date().toISOString()
        });
    }

    async getPreference(key, defaultValue = null) {
        // Try cache first (use a singleton cache instance)
        const cacheKey = `pref_${key}`;
        const cache = window.kimiCache instanceof KimiCacheManager ? window.kimiCache : null;
        if (cache && typeof cache.get === "function") {
            const cached = cache.get(cacheKey);
            if (cached !== null) {
                return cached;
            }
        }

        try {
            const record = await this.db.preferences.get(key);
            if (!record) {
                const cache = window.kimiCache instanceof KimiCacheManager ? window.kimiCache : null;
                if (cache && typeof cache.set === "function") {
                    cache.set(cacheKey, defaultValue, 60000); // Cache for 1 minute
                }
                return defaultValue;
            }

            // Backward compatibility: decrypt legacy encrypted values
            let value = record.value;
            if (record.encrypted && window.KimiSecurityUtils) {
                try {
                    value = window.KimiSecurityUtils.decryptApiKey(record.value);
                    // One-time migration: store back as plain text without encrypted flag
                    try {
                        await this.db.preferences.put({ key: key, value, updated: new Date().toISOString() });
                    } catch (mErr) {}
                } catch (e) {
                    // If decryption fails, fallback to raw value
                    console.warn("Failed to decrypt legacy API key; returning raw value", e);
                }
            }

            // Cache the result
            const cache = window.kimiCache instanceof KimiCacheManager ? window.kimiCache : null;
            if (cache && typeof cache.set === "function") {
                cache.set(cacheKey, value, 60000); // Cache for 1 minute
            }

            return value;
        } catch (error) {
            console.warn(`Error getting preference ${key}:`, error);
            return defaultValue;
        }
    }

    async getAllPreferences() {
        try {
            const all = await this.db.preferences.toArray();
            const prefs = {};
            all.forEach(item => {
                prefs[item.key] = item.value;
            });
            return prefs;
        } catch (error) {
            console.warn("Error getting all preferences:", error);
            return {};
        }
    }

    async setSetting(category, settings) {
        return this.db.settings.put({
            category: category,
            settings: settings,
            updated: new Date().toISOString()
        });
    }

    async getSetting(category, defaultSettings = {}) {
        const result = await this.db.settings.get(category);
        return result ? result.settings : defaultSettings;
    }

    async setPersonalityTrait(trait, value, character = null) {
        if (!character) character = await this.getSelectedCharacter();

        // Invalidate cache
        if (window.KimiCacheManager && typeof window.KimiCacheManager.delete === "function") {
            window.KimiCacheManager.delete(`trait_${character}_${trait}`);
            window.KimiCacheManager.delete(`all_traits_${character}`);
        }

        return this.db.personality.put({
            trait: trait,
            character: character,
            value: value,
            updated: new Date().toISOString()
        });
    }

    async getPersonalityTrait(trait, defaultValue = null, character = null) {
        if (!character) character = await this.getSelectedCharacter();

        // Use unified defaults from emotion system
        if (defaultValue === null) {
            if (window.KimiEmotionSystem) {
                const emotionSystem = new window.KimiEmotionSystem(this);
                defaultValue = emotionSystem.TRAIT_DEFAULTS[trait] || 50;
            } else {
                // Fallback defaults (must match KimiEmotionSystem.TRAIT_DEFAULTS exactly)
                const fallbackDefaults = {
                    affection: 65, // Fixed - matches KimiEmotionSystem
                    playfulness: 55, // Fixed - matches KimiEmotionSystem
                    intelligence: 70, // Fixed - matches KimiEmotionSystem
                    empathy: 75, // Fixed - matches KimiEmotionSystem
                    humor: 60, // Fixed - matches KimiEmotionSystem
                    romance: 50 // Fixed - matches KimiEmotionSystem
                };
                defaultValue = fallbackDefaults[trait] || 50;
            }
        }

        // Try cache first
        const cacheKey = `trait_${character}_${trait}`;
        if (window.KimiCacheManager && typeof window.KimiCacheManager.get === "function") {
            const cached = window.KimiCacheManager.get(cacheKey);
            if (cached !== null) {
                return cached;
            }
        }

        const found = await this.db.personality.get([character, trait]);
        const value = found ? found.value : defaultValue;

        // Cache the result
        if (window.KimiCacheManager && typeof window.KimiCacheManager.set === "function") {
            window.KimiCacheManager.set(cacheKey, value, 120000); // Cache for 2 minutes
        }
        return value;
    }

    async getAllPersonalityTraits(character = null) {
        if (!character) character = await this.getSelectedCharacter();

        // Try cache first
        const cacheKey = `all_traits_${character}`;
        if (window.KimiCacheManager && typeof window.KimiCacheManager.get === "function") {
            const cached = window.KimiCacheManager.get(cacheKey);
            if (cached !== null) {
                return cached;
            }
        }

        const all = await this.db.personality.where("character").equals(character).toArray();
        const traits = {};
        all.forEach(item => {
            traits[item.trait] = item.value;
        });

        // Cache the result
        if (window.KimiCacheManager && typeof window.KimiCacheManager.set === "function") {
            window.KimiCacheManager.set(cacheKey, traits, 120000); // Cache for 2 minutes
        }
        return traits;
    }

    async savePersonality(personalityObj, character = null) {
        if (!character) character = await this.getSelectedCharacter();
        // Invalidate caches for all affected traits and the aggregate cache for this character
        if (window.KimiCacheManager && typeof window.KimiCacheManager.delete === "function") {
            try {
                Object.keys(personalityObj).forEach(trait => {
                    window.KimiCacheManager.delete(`trait_${character}_${trait}`);
                });
                window.KimiCacheManager.delete(`all_traits_${character}`);
            } catch (e) {}
        }
        const entries = Object.entries(personalityObj).map(([trait, value]) =>
            this.db.personality.put({
                trait: trait,
                character: character,
                value: value,
                updated: new Date().toISOString()
            })
        );
        return Promise.all(entries);
    }

    async getPersonality(character = null) {
        return this.getAllPersonalityTraits(character);
    }

    async saveLLMModel(id, name, provider, apiKey, config) {
        return this.db.llmModels.put({
            id: id,
            name: name,
            provider: provider,
            apiKey: apiKey,
            config: config,
            added: new Date().toISOString(),
            lastUsed: null
        });
    }

    async getLLMModel(id) {
        return this.db.llmModels.get(id);
    }

    async getAllLLMModels() {
        try {
            return await this.db.llmModels.toArray();
        } catch (error) {
            console.warn("Error getting all LLM models:", error);
            return [];
        }
    }

    async deleteLLMModel(id) {
        return this.db.llmModels.delete(id);
    }

    async cleanOldConversations(days = null, character = null) {
        // If days not provided, fallback to full clean (legacy behavior)
        if (days === null) {
            if (character) {
                const all = await this.db.conversations.where("character").equals(character).toArray();
                const ids = all.map(item => item.id);
                return this.db.conversations.bulkDelete(ids);
            } else {
                return this.db.conversations.clear();
            }
        }
        const threshold = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
        if (character) {
            const toDelete = await this.db.conversations
                .where("character")
                .equals(character)
                .and(c => c.timestamp < threshold)
                .toArray();
            const ids = toDelete.map(item => item.id);
            return this.db.conversations.bulkDelete(ids);
        } else {
            const toDelete = await this.db.conversations.where("timestamp").below(threshold).toArray();
            const ids = toDelete.map(item => item.id);
            return this.db.conversations.bulkDelete(ids);
        }
    }

    async getStorageStats() {
        try {
            const conversations = await this.getAllConversations();
            const preferences = await this.getAllPreferences();
            const models = await this.getAllLLMModels();
            return {
                conversations: conversations ? conversations.length : 0,
                preferences: preferences ? Object.keys(preferences).length : 0,
                models: models ? models.length : 0,
                totalSize: JSON.stringify({
                    conversations: conversations || [],
                    preferences: preferences || {},
                    models: models || []
                }).length
            };
        } catch (error) {
            console.error("Error getting storage stats:", error);
            return {
                conversations: 0,
                preferences: 0,
                models: 0,
                totalSize: 0
            };
        }
    }

    async deleteSingleMessage(conversationId, sender) {
        const conv = await this.db.conversations.get(conversationId);
        if (!conv) return;
        if (sender === "user") {
            conv.user = "";
        } else if (sender === "kimi") {
            conv.kimi = "";
        }
        if ((conv.user === undefined || conv.user === "") && (conv.kimi === undefined || conv.kimi === "")) {
            await this.db.conversations.delete(conversationId);
        } else {
            await this.db.conversations.put(conv);
        }
    }

    async setPreferencesBatch(prefsArray) {
        const batch = prefsArray.map(({ key, value }) => ({ key, value, updated: new Date().toISOString() }));
        return this.db.preferences.bulkPut(batch);
    }
    async setPersonalityBatch(traitsObj, character = null) {
        if (!character) character = await this.getSelectedCharacter();
        // Invalidate caches for all affected traits and the aggregate cache for this character
        if (window.KimiCacheManager && typeof window.KimiCacheManager.delete === "function") {
            try {
                Object.keys(traitsObj).forEach(trait => {
                    window.KimiCacheManager.delete(`trait_${character}_${trait}`);
                });
                window.KimiCacheManager.delete(`all_traits_${character}`);
            } catch (e) {}
        }

        const batch = Object.entries(traitsObj).map(([trait, value]) => ({
            trait,
            character,
            value,
            updated: new Date().toISOString()
        }));
        return this.db.personality.bulkPut(batch);
    }
    async setSettingsBatch(settingsArray) {
        const batch = settingsArray.map(({ category, settings }) => ({
            category,
            settings,
            updated: new Date().toISOString()
        }));
        return this.db.settings.bulkPut(batch);
    }
    async getPreferencesBatch(keys) {
        const results = await this.db.preferences.where("key").anyOf(keys).toArray();
        const out = {};
        for (const item of results) {
            let val = item.value;
            if (item.encrypted && window.KimiSecurityUtils) {
                try {
                    val = window.KimiSecurityUtils.decryptApiKey(item.value);
                    // Migrate back as plain
                    try {
                        await this.db.preferences.put({ key: item.key, value: val, updated: new Date().toISOString() });
                    } catch (mErr) {}
                } catch (e) {
                    console.warn("Failed to decrypt legacy pref in batch:", item.key, e);
                }
            }
            out[item.key] = val;
        }
        return out;
    }
    async getPersonalityTraitsBatch(traits, character = null) {
        if (!character) character = await this.getSelectedCharacter();
        const results = await this.db.personality.where("character").equals(character).toArray();
        const out = {};
        traits.forEach(trait => {
            const found = results.find(item => item.trait === trait);
            out[trait] = found ? found.value : 50;
        });
        return out;
    }

    async getSelectedCharacter() {
        try {
            return await this.getPreference("selectedCharacter", "kimi");
        } catch (error) {
            console.warn("Error getting selected character:", error);
            return "kimi";
        }
    }

    async setSelectedCharacter(character) {
        try {
            await this.setPreference("selectedCharacter", character);
        } catch (error) {
            console.error("Error setting selected character:", error);
        }
    }

    async getSystemPromptForCharacter(character = null) {
        if (!character) character = await this.getSelectedCharacter();
        try {
            const prompt = await this.getPreference(`systemPrompt_${character}`, null);
            if (prompt) return prompt;

            if (window.KIMI_CHARACTERS && window.KIMI_CHARACTERS[character] && window.KIMI_CHARACTERS[character].defaultPrompt) {
                return window.KIMI_CHARACTERS[character].defaultPrompt;
            }

            return window.DEFAULT_SYSTEM_PROMPT || "";
        } catch (error) {
            console.warn("Error getting system prompt for character:", error);
            return window.DEFAULT_SYSTEM_PROMPT || "";
        }
    }

    async setSystemPromptForCharacter(character, prompt) {
        if (!character) character = await this.getSelectedCharacter();
        try {
            await this.setPreference(`systemPrompt_${character}`, prompt);
        } catch (error) {
            console.error("Error setting system prompt for character:", error);
        }
    }
}

// Export for usage
window.KimiDatabase = KimiDatabase;