`;
- } else if (state.adminTab === 'chars') {
+ }
+
+ // 2. DYNAMIK
+ else if (state.adminTab === 'dynamics') {
+ tabContent = `
+
+ `;
+ }
+
+ // 3. KI & PROVIDER
+ else if (state.adminTab === 'ai') {
+ const curProvider = (settings.ai_provider || 'minimax').toLowerCase();
+ tabContent = `
+
+ `;
+ }
+
+ // 4. CHARAKTERE & WELT
+ else if (state.adminTab === 'chars') {
let filteredChars = chars;
if (state.adminFilter === 'active') filteredChars = activeChars;
else if (state.adminFilter === 'banned') filteredChars = bannedChars;
@@ -697,13 +1060,40 @@ async function viewAdmin(main) {
}
tabContent = `
+
${t('admin_chars')}
${activeChars.length} ${t('status_char_active')} · ${bannedChars.length} ${t('status_banned')}
- Gesperrte Charaktere erstellen keine neuen Feed-Posts, Kommentare, Likes oder DMs mehr. Alle bisherigen Nachrichten und Beiträge bleiben im Feed vollständig erhalten.
+ Gesperrte Charaktere erstellen keine neuen Feed-Posts, Kommentare, Likes oder DMs mehr. Alle bisherigen Nachrichten und Beiträge bleiben im Feed vollständig erhalten. Mit ✏️ kannst du jeden Charakter nachträglich editieren.
@@ -719,22 +1109,28 @@ async function viewAdmin(main) {
${filteredChars.length ? filteredChars.map((c) => `
${avatar(c.name, c.avatarKey)}
-
+
${esc(c.name)} ${c.isCustom ? '✨' : ''}
@${esc(c.handle)} · ${c.language === 'en' ? 'EN' : 'DE'} · ${c.postCount} Posts · ${c.messageCount} DMs
${c.isBanned ? `⛔ ${t('status_banned')}` : `🟢 ${t('status_char_active')}`}
-
- ${c.isBanned ? t('unban_char') : t('ban_char')}
-
+
+ ${t('edit_char')}
+
+ ${c.isBanned ? t('unban_char') : t('ban_char')}
+
+
`).join('') : `
Keine Charaktere gefunden.
`}
`;
- } else if (state.adminTab === 'posts') {
+ }
+
+ // 5. POSTS
+ else if (state.adminTab === 'posts') {
let filteredPosts = posts;
if (state.adminFilter === 'ai') filteredPosts = posts.filter((p) => p.authorType !== 'user');
else if (state.adminFilter === 'user') filteredPosts = posts.filter((p) => p.authorType === 'user');
@@ -804,19 +1200,35 @@ async function viewAdmin(main) {
viewAdmin(main);
}));
- // Timeout tab events
+ // Setup range slider listeners
+ const bindSlider = (sliderId, valId, suffix = '%') => {
+ const slider = $(`#${sliderId}`, main);
+ const val = $(`#${valId}`, main);
+ if (slider && val) {
+ slider.addEventListener('input', () => { val.textContent = `${slider.value}${suffix}`; });
+ }
+ };
+
+ bindSlider('s-bot-img-chance', 'val-img-chance');
+ bindSlider('s-like-chance', 'val-like-chance');
+ bindSlider('s-dm-post', 'val-dm-post');
+ bindSlider('s-dm-comment', 'val-dm-comment');
+ bindSlider('s-dm-tick', 'val-dm-tick');
+ bindSlider('s-ai-temp', 'val-ai-temp', '');
+
+ // 1. Timeout & Budget Event Handlers
if (state.adminTab === 'timeout') {
$$('.quick-btn', main).forEach((b) => b.addEventListener('click', () => {
- const inp = $('#timeout-input');
+ const inp = $('#s-timeout');
if (inp) inp.value = b.dataset.hours;
}));
$('#save-timeout-btn')?.addEventListener('click', async () => {
- const hours = parseFloat($('#timeout-input').value);
+ const hours = parseFloat($('#s-timeout').value);
if (isNaN(hours) || hours <= 0) return toast(t('error'), true);
try {
await api('/api/admin/timeout', { method: 'POST', body: { hours } });
- toast(t('sub_ok'));
+ toast(t('settings_saved'));
viewAdmin(main);
} catch (err) { toast(err.message, true); }
});
@@ -828,10 +1240,92 @@ async function viewAdmin(main) {
viewAdmin(main);
} catch (err) { toast(err.message, true); }
});
+
+ $('#save-token-settings-btn')?.addEventListener('click', async () => {
+ const body = {
+ timeout_hours: $('#s-timeout').value,
+ bot_images_enabled: $('#s-bot-img-toggle').checked ? '1' : '0',
+ bot_image_chance: $('#s-bot-img-chance').value,
+ feed_tick_interval_min: $('#s-feed-interval').value,
+ feed_tick_posts_count: $('#s-posts-per-tick').value,
+ daily_budget_limit: $('#s-daily-budget').value,
+ };
+ try {
+ await api('/api/admin/settings', { method: 'POST', body });
+ toast(t('settings_saved'));
+ viewAdmin(main);
+ } catch (err) { toast(err.message, true); }
+ });
}
- // Chars tab events
+ // 2. Dynamics Event Handlers
+ if (state.adminTab === 'dynamics') {
+ $('#preset-calm')?.addEventListener('click', () => {
+ $('#s-react-min').value = '1';
+ $('#s-react-max').value = '2';
+ });
+ $('#preset-normal')?.addEventListener('click', () => {
+ $('#s-react-min').value = '2';
+ $('#s-react-max').value = '4';
+ });
+ $('#preset-hype')?.addEventListener('click', () => {
+ $('#s-react-min').value = '4';
+ $('#s-react-max').value = '7';
+ });
+
+ $('#save-dynamics-btn')?.addEventListener('click', async () => {
+ const body = {
+ user_post_reactions_min: $('#s-react-min').value,
+ user_post_reactions_max: $('#s-react-max').value,
+ user_post_like_chance: $('#s-like-chance').value,
+ proactive_dm_post_chance: $('#s-dm-post').value,
+ proactive_dm_comment_chance: $('#s-dm-comment').value,
+ proactive_dm_tick_chance: $('#s-dm-tick').value,
+ bot_to_bot_comments_min: $('#s-bot-min').value,
+ bot_to_bot_comments_max: $('#s-bot-max').value,
+ };
+ try {
+ await api('/api/admin/settings', { method: 'POST', body });
+ toast(t('settings_saved'));
+ viewAdmin(main);
+ } catch (err) { toast(err.message, true); }
+ });
+ }
+
+ // 3. AI & Provider Event Handlers
+ if (state.adminTab === 'ai') {
+ $('#save-ai-settings-btn')?.addEventListener('click', async () => {
+ const keyVal = $('#s-ai-key').value.trim();
+ const body = {
+ ai_provider: $('#s-ai-provider').value,
+ ai_model: $('#s-ai-model').value.trim(),
+ ai_temperature: $('#s-ai-temp').value,
+ ai_base_url: $('#s-ai-base-url').value.trim(),
+ };
+ if (keyVal) body.ai_api_key = keyVal;
+
+ try {
+ await api('/api/admin/settings', { method: 'POST', body });
+ toast(t('settings_saved'));
+ viewAdmin(main);
+ } catch (err) { toast(err.message, true); }
+ });
+ }
+
+ // 4. Chars & World Event Handlers
if (state.adminTab === 'chars') {
+ $('#save-world-settings-btn')?.addEventListener('click', async () => {
+ const body = {
+ world_language: $('#s-world-lang').value,
+ daily_char_autospawn: $('#s-daily-autospawn').checked ? '1' : '0',
+ };
+ try {
+ await api('/api/admin/settings', { method: 'POST', body });
+ toast(t('settings_saved'));
+ viewAdmin(main);
+ } catch (err) { toast(err.message, true); }
+ });
+
$$('.chip[data-af]', main).forEach((c) => c.addEventListener('click', () => {
state.adminFilter = c.dataset.af;
viewAdmin(main);
@@ -856,9 +1350,17 @@ async function viewAdmin(main) {
viewAdmin(main);
} catch (err) { toast(err.message, true); b.disabled = false; }
}));
+
+ $$('.edit-char-btn', main).forEach((b) => b.addEventListener('click', () => {
+ const id = b.dataset.id;
+ const char = chars.find((c) => c.id === id);
+ if (char) {
+ openCharEditModal(char, () => viewAdmin(main));
+ }
+ }));
}
- // Posts tab events
+ // 5. Posts Event Handlers
if (state.adminTab === 'posts') {
$$('.chip[data-pf]', main).forEach((c) => c.addEventListener('click', () => {
state.adminFilter = c.dataset.pf;
diff --git a/public/styles.css b/public/styles.css
index 1a42793..06fe7e9 100644
--- a/public/styles.css
+++ b/public/styles.css
@@ -219,3 +219,24 @@ input[type=text]:focus,textarea:focus,select:focus{border-color:var(--acc)}
.status-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 12px;border-radius:999px;font-size:13px;font-weight:700}
.status-pill.active{background:rgba(40,167,69,.2);border:1px solid #28a745;color:#39d98a}
.status-pill.paused{background:rgba(224,169,18,.2);border:1px solid #e0a912;color:#ffd35c}
+
+/* Form controls & settings */
+.settings-group{margin-bottom:18px;border-bottom:1px solid var(--line);padding-bottom:14px}
+.settings-group:last-child{border-bottom:0;margin-bottom:0;padding-bottom:0}
+.settings-title{font-size:14px;font-weight:700;color:var(--txt);margin-bottom:6px;display:flex;align-items:center;gap:6px}
+.settings-desc{font-size:12px;color:var(--muted);line-height:1.45;margin-bottom:10px}
+.range-wrap{display:flex;align-items:center;gap:12px}
+.range-wrap input[type=range]{flex:1;accent-color:var(--acc);cursor:pointer}
+.range-val{font-size:13px;font-weight:700;color:var(--txt);min-width:44px;text-align:right}
+
+.switch-label{display:flex;align-items:center;justify-content:space-between;cursor:pointer;gap:10px;margin-bottom:8px}
+.switch-label input[type=checkbox]{width:18px;height:18px;accent-color:var(--acc);cursor:pointer}
+
+/* Modal */
+.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.75);backdrop-filter:blur(6px);z-index:999;display:flex;align-items:center;justify-content:center;padding:16px}
+.modal-box{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);max-width:520px;width:100%;max-height:90vh;overflow-y:auto;padding:20px;box-shadow:0 20px 40px rgba(0,0,0,.6)}
+.modal-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
+.modal-title{font-size:18px;font-weight:800}
+.modal-close{font-size:20px;color:var(--muted);cursor:pointer;padding:4px}
+.modal-close:hover{color:var(--txt)}
+.modal-foot{display:flex;justify-content:flex-end;gap:8px;margin-top:16px;padding-top:12px;border-top:1px solid var(--line)}
diff --git a/src/ai.js b/src/ai.js
index 7f0674a..81ca4a2 100644
--- a/src/ai.js
+++ b/src/ai.js
@@ -1,13 +1,60 @@
// Multi-provider AI engine for Solus.
// Supports: MiniMax (default), OpenAI, OpenRouter, Gemini, Anthropic, LiteLLM, Mistral, Ollama & Mock fallback.
-import { uid } from './db.js';
+import { uid, getAllSettings } from './db.js';
import { saveImageBuffer } from './images.js';
function getEnv(env) {
return env && Object.keys(env).length ? env : process.env;
}
+let lastResolvedConfig = null;
+
+export async function getEffectiveAIConfig(envArg) {
+ const env = getEnv(envArg);
+ let dbSettings = {};
+ try {
+ dbSettings = await getAllSettings();
+ } catch {}
+
+ const provider = (dbSettings.ai_provider || env.AI_PROVIDER || (env.MINIMAX_API_KEY ? 'minimax' : 'mock')).toLowerCase();
+
+ let apiKey = dbSettings.ai_api_key;
+ if (!apiKey) {
+ if (provider === 'minimax') apiKey = env.MINIMAX_API_KEY || env.AI_API_KEY;
+ else if (provider === 'openai') apiKey = env.OPENAI_API_KEY || env.AI_API_KEY;
+ else if (provider === 'openrouter') apiKey = env.OPENROUTER_API_KEY || env.AI_API_KEY;
+ else if (provider === 'gemini') apiKey = env.GEMINI_API_KEY || env.AI_API_KEY;
+ else if (provider === 'anthropic') apiKey = env.ANTHROPIC_API_KEY || env.AI_API_KEY;
+ else apiKey = env.AI_API_KEY || env.MISTRAL_API_KEY;
+ }
+
+ let model = dbSettings.ai_model;
+ if (!model) {
+ if (provider === 'minimax') model = env.MINIMAX_MODEL || env.AI_MODEL || 'MiniMax-M3';
+ else if (provider === 'openai') model = env.OPENAI_MODEL || env.AI_MODEL || 'gpt-4o-mini';
+ else if (provider === 'openrouter') model = env.OPENROUTER_MODEL || env.AI_MODEL || 'meta-llama/llama-3.3-70b-instruct';
+ else if (provider === 'gemini') model = env.GEMINI_MODEL || env.AI_MODEL || 'gemini-1.5-flash';
+ else if (provider === 'anthropic') model = env.ANTHROPIC_MODEL || env.AI_MODEL || 'claude-3-5-haiku-latest';
+ else model = env.AI_MODEL || 'default';
+ }
+
+ const baseUrl = dbSettings.ai_base_url || env.AI_BASE_URL || '';
+ const temperature = parseFloat(dbSettings.ai_temperature) > 0 ? parseFloat(dbSettings.ai_temperature) : 0.7;
+
+ lastResolvedConfig = {
+ provider,
+ apiKey: apiKey || '',
+ model,
+ baseUrl,
+ temperature,
+ hasKey: Boolean(apiKey),
+ };
+
+ return lastResolvedConfig;
+}
+
export function getActiveProvider(envArg) {
+ if (lastResolvedConfig?.provider) return lastResolvedConfig.provider;
const env = getEnv(envArg);
if (env.AI_PROVIDER) return env.AI_PROVIDER.toLowerCase();
if (env.MINIMAX_API_KEY) return 'minimax';
@@ -20,6 +67,7 @@ export function getActiveProvider(envArg) {
}
export function hasKey(envArg) {
+ if (lastResolvedConfig?.hasKey) return true;
const env = getEnv(envArg);
return Boolean(
env.MINIMAX_API_KEY ||
@@ -40,41 +88,64 @@ export function stripThinking(text) {
// ---------------- Text Chat Completions ----------------
export async function chatText(envArg, messages, opts = {}) {
- const env = getEnv(envArg);
- if (!hasKey(env)) return mockText(messages, opts);
+ const config = await getEffectiveAIConfig(envArg);
+ if (!config.hasKey) return mockText(messages, opts);
- const provider = getActiveProvider(env);
+ const provider = config.provider;
+ const env = {
+ ...getEnv(envArg),
+ AI_PROVIDER: config.provider,
+ AI_API_KEY: config.apiKey,
+ AI_MODEL: config.model,
+ AI_BASE_URL: config.baseUrl,
+ MINIMAX_API_KEY: config.apiKey,
+ MINIMAX_MODEL: config.model,
+ OPENAI_API_KEY: config.apiKey,
+ OPENAI_MODEL: config.model,
+ OPENROUTER_API_KEY: config.apiKey,
+ OPENROUTER_MODEL: config.model,
+ GEMINI_API_KEY: config.apiKey,
+ GEMINI_MODEL: config.model,
+ ANTHROPIC_API_KEY: config.apiKey,
+ ANTHROPIC_MODEL: config.model,
+ };
+
+ const effectiveOpts = {
+ ...opts,
+ temperature: opts.temperature ?? config.temperature,
+ model: opts.model || config.model,
+ };
try {
let result;
switch (provider) {
case 'minimax':
- result = await callMiniMaxChat(env, messages, opts);
+ result = await callMiniMaxChat(env, messages, effectiveOpts);
break;
case 'openai':
- result = await callOpenAIChat(env, messages, opts);
+ result = await callOpenAIChat(env, messages, effectiveOpts);
break;
case 'openrouter':
- result = await callOpenRouterChat(env, messages, opts);
+ result = await callOpenRouterChat(env, messages, effectiveOpts);
break;
case 'gemini':
- result = await callGeminiChat(env, messages, opts);
+ result = await callGeminiChat(env, messages, effectiveOpts);
break;
case 'anthropic':
- result = await callAnthropicChat(env, messages, opts);
+ result = await callAnthropicChat(env, messages, effectiveOpts);
break;
case 'litellm':
case 'mistral':
case 'ollama':
case 'openai_compat':
default:
- result = await callOpenAICompatChat(env, messages, opts);
+ result = await callOpenAICompatChat(env, messages, effectiveOpts);
break;
}
return stripThinking(result);
} catch (err) {
console.error(`AI call to ${provider} failed, falling back to mock text:`, err.message);
- return mockText(messages, opts);
+ return mockText(messages, effectiveOpts);
}
}
@@ -212,13 +283,21 @@ async function sendOpenAICompat(baseUrl, apiKey, model, messages, opts, extraHea
// ---------------- Image Generation ----------------
export async function genImage(envArg, prompt, aspectRatio = '1:1') {
- const env = getEnv(envArg);
- if (!hasKey(env)) return mockImage(prompt);
+ const config = await getEffectiveAIConfig(envArg);
+ if (!config.hasKey) return mockImage(prompt);
- const provider = getActiveProvider(env);
+ const env = {
+ ...getEnv(envArg),
+ AI_PROVIDER: config.provider,
+ AI_API_KEY: config.apiKey,
+ MINIMAX_API_KEY: config.apiKey,
+ OPENAI_API_KEY: config.apiKey,
+ };
+
+ const provider = config.provider;
try {
- if (provider === 'minimax') {
+ if (provider === 'minimax' || env.MINIMAX_API_KEY) {
return await genMiniMaxImage(env, prompt, aspectRatio);
} else if (provider === 'openai' && (env.OPENAI_API_KEY || env.AI_API_KEY)) {
return await genOpenAIImage(env, prompt);
diff --git a/src/db.js b/src/db.js
index 1270e05..c72cf64 100644
--- a/src/db.js
+++ b/src/db.js
@@ -185,6 +185,137 @@ export async function banCharacter(id, banned = true) {
return { id, isBanned: isBanned === 1, bannedAt };
}
+export const DEFAULT_SETTINGS = {
+ // Token & Budget
+ timeout_hours: '2',
+ bot_images_enabled: '1',
+ bot_image_chance: '35',
+ feed_tick_interval_min: '20',
+ feed_tick_posts_count: '1',
+ daily_budget_limit: '0',
+ // Dynamics
+ user_post_reactions_min: '2',
+ user_post_reactions_max: '4',
+ user_post_like_chance: '70',
+ proactive_dm_post_chance: '65',
+ proactive_dm_comment_chance: '35',
+ proactive_dm_tick_chance: '35',
+ bot_to_bot_comments_min: '1',
+ bot_to_bot_comments_max: '2',
+ // AI Provider & Model
+ ai_provider: process.env.AI_PROVIDER || (process.env.MINIMAX_API_KEY ? 'minimax' : 'minimax'),
+ ai_model: process.env.AI_MODEL || process.env.MINIMAX_MODEL || 'MiniMax-M3',
+ ai_api_key: '',
+ ai_base_url: process.env.AI_BASE_URL || '',
+ ai_temperature: '0.7',
+ // World
+ world_language: 'mixed',
+ daily_char_autospawn: '1',
+};
+
+export async function getAllSettings() {
+ const res = await pool.query('SELECT key, value FROM app_state;');
+ const map = {};
+ for (const row of res.rows) {
+ map[row.key] = row.value;
+ }
+ const result = { ...DEFAULT_SETTINGS };
+ for (const key of Object.keys(DEFAULT_SETTINGS)) {
+ if (map[key] !== undefined && map[key] !== null && map[key] !== '') {
+ result[key] = map[key];
+ }
+ }
+ return result;
+}
+
+export async function saveSettings(updates) {
+ for (const [key, val] of Object.entries(updates)) {
+ if (val !== undefined && val !== null) {
+ await setState(key, String(val));
+ }
+ }
+ return await getAllSettings();
+}
+
+export async function checkAndIncrementBudget() {
+ const limit = parseInt(await getState('daily_budget_limit', '0'), 10);
+ if (!limit || limit <= 0) return true; // unlimited
+
+ const today = new Date().toISOString().slice(0, 10);
+ const storedDate = await getState('daily_budget_date', '');
+ let count = parseInt(await getState('daily_budget_count', '0'), 10);
+
+ if (storedDate !== today) {
+ count = 0;
+ await setState('daily_budget_date', today);
+ }
+
+ if (count >= limit) {
+ console.log(`🛑 [Budget-Cap] Tageslimit von ${limit} KI-Aktionen für heute (${today}) erreicht.`);
+ return false;
+ }
+
+ await setState('daily_budget_count', String(count + 1));
+ return true;
+}
+
+export async function getBudgetStatus() {
+ const limit = parseInt(await getState('daily_budget_limit', '0'), 10);
+ const today = new Date().toISOString().slice(0, 10);
+ const storedDate = await getState('daily_budget_date', '');
+ let count = parseInt(await getState('daily_budget_count', '0'), 10);
+ if (storedDate !== today) count = 0;
+ return {
+ limit,
+ count,
+ date: today,
+ exhausted: limit > 0 && count >= limit,
+ };
+}
+
+export async function updateCharacter(id, fields) {
+ const { name, handle, bio, hobbies, personality, language } = fields;
+ const updates = [];
+ const values = [];
+ let idx = 1;
+
+ if (name !== undefined) {
+ updates.push(`name = $${idx++}`);
+ values.push(String(name).trim().slice(0, 100));
+ }
+ if (handle !== undefined) {
+ updates.push(`handle = $${idx++}`);
+ values.push(String(handle).trim().toLowerCase().replace(/[^a-z0-9._-]/g, '').slice(0, 50));
+ }
+ if (bio !== undefined) {
+ updates.push(`bio = $${idx++}`);
+ values.push(String(bio).trim().slice(0, 500));
+ }
+ if (hobbies !== undefined) {
+ updates.push(`hobbies = $${idx++}`);
+ values.push(JSON.stringify(Array.isArray(hobbies) ? hobbies : []));
+ }
+ if (personality !== undefined) {
+ updates.push(`personality = $${idx++}`);
+ values.push(String(personality).trim().slice(0, 1000));
+ }
+ if (language !== undefined) {
+ updates.push(`language = $${idx++}`);
+ values.push(language === 'en' ? 'en' : 'de');
+ }
+
+ if (!updates.length) return null;
+ values.push(id);
+ const q = `UPDATE characters SET ${updates.join(', ')} WHERE id = $${idx} RETURNING *;`;
+ const res = await pool.query(q, values);
+ if (!res.rows.length) return null;
+ const r = res.rows[0];
+ return {
+ ...r,
+ hobbies: Array.isArray(r.hobbies) ? r.hobbies : safeJson(r.hobbies, []),
+ };
+}
+
export function safeJson(s, fallback) {
if (typeof s === 'object' && s !== null) return s;
try { return JSON.parse(s); } catch { return fallback; }
diff --git a/src/engagement.js b/src/engagement.js
index f52e916..8077653 100644
--- a/src/engagement.js
+++ b/src/engagement.js
@@ -1,5 +1,5 @@
// Background AI engagement: comments between characters and towards the user, plus proactive DMs (PostgreSQL).
-import { pool, uid } from './db.js';
+import { pool, uid, getAllSettings } from './db.js';
import { chatText, genImage, hasKey } from './ai.js';
import { personaSystemPrompt } from './personas.js';
@@ -10,13 +10,22 @@ function pick(arr, n) {
return out;
}
-// Characters react to a user's new post: pick 2-4, each likes + comments, and potentially sends a proactive DM.
+// Characters react to a user's new post: pick configurable number, each likes + comments, and potentially sends a proactive DM.
export async function reactToUserPost(post, chars) {
- const participants = pick(chars, hasKey() ? 2 + Math.floor(Math.random() * 3) : 2);
+ const settings = await getAllSettings().catch(() => ({}));
+ const minReact = Math.max(0, parseInt(settings.user_post_reactions_min, 10) || 2);
+ const maxReact = Math.max(minReact, parseInt(settings.user_post_reactions_max, 10) || 4);
+ const targetCount = minReact + Math.floor(Math.random() * (maxReact - minReact + 1));
+
+ const participants = pick(chars, hasKey() ? targetCount : Math.min(targetCount, 2));
+ const likeChance = (parseInt(settings.user_post_like_chance, 10) ?? 70) / 100;
+ const dmChance = (parseInt(settings.proactive_dm_post_chance, 10) ?? 65) / 100;
+ const worldLang = settings.world_language || 'mixed';
+
for (const c of participants) {
try {
const text = await chatText(null, [
- { role: 'system', content: personaSystemPrompt(c) },
+ { role: 'system', content: personaSystemPrompt(c, '', worldLang) },
{ role: 'user', content: `Der Nutzer hat gerade gepostet:\n"${post.text}"${post.image_key ? '\n(mit Bild)' : ''}\n\nSchreib EINEN kurzen Kommentar unter diesen Post – in deinem Stil, wie ein echter User kommentieren würde. Keine Anrede, nur der Kommentar.` },
], { maxTokens: 120 });
@@ -25,7 +34,7 @@ export async function reactToUserPost(post, chars) {
[uid(), post.id, 'char', c.id, text, Date.now()]
);
- if (Math.random() < 0.7) {
+ if (Math.random() < likeChance) {
await pool.query(
'INSERT INTO likes (post_id, liker_type, liker_id, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING;',
[post.id, 'char', c.id, Date.now()]
@@ -36,8 +45,8 @@ export async function reactToUserPost(post, chars) {
}
}
- // Proactive DM: ~65% chance that one of the characters slides into the user's DMs about the post!
- if (participants.length > 0 && Math.random() < 0.65) {
+ // Proactive DM after post
+ if (participants.length > 0 && Math.random() < dmChance) {
const dmChar = participants[Math.floor(Math.random() * participants.length)];
await sendProactiveDM(dmChar, `Der Nutzer hat gerade gepostet: "${post.text}". Schreib ihm privat eine kurze Direktnachricht (1-2 Sätze) dazu, wie ein Social-Media-Bekannter, der in die DMs slidet.`);
}
@@ -48,11 +57,20 @@ export async function charactersEngageEachOther(post, author, chars) {
if (author.is_banned) return;
const others = chars.filter((c) => c.id !== author.id && !c.is_banned);
if (!others.length) return;
- const participants = pick(others, 1 + Math.floor(Math.random() * 2));
+
+ const settings = await getAllSettings().catch(() => ({}));
+ const minCom = parseInt(settings.bot_to_bot_comments_min, 10) ?? 1;
+ const maxCom = parseInt(settings.bot_to_bot_comments_max, 10) ?? 2;
+ if (maxCom <= 0) return; // Disabled
+
+ const count = Math.max(1, minCom + Math.floor(Math.random() * (maxCom - minCom + 1)));
+ const participants = pick(others, count);
+ const worldLang = settings.world_language || 'mixed';
+
for (const c of participants) {
try {
const text = await chatText(null, [
- { role: 'system', content: personaSystemPrompt(c) },
+ { role: 'system', content: personaSystemPrompt(c, '', worldLang) },
{ role: 'user', content: `${author.name} (@${author.handle}) hat gepostet:\n"${post.text}"\n\nSchreib EINEN Kommentar als Reaktion – kurz, in deinem Stil. Nur der Kommentar.` },
], { maxTokens: 100 });
@@ -68,11 +86,18 @@ export async function charactersEngageEachOther(post, author, chars) {
// Characters comment on a user's comment (reply-chain under a post).
export async function charsReplyToUserComment(comment, post, chars) {
- const participants = pick(chars, 1 + Math.floor(Math.random() * 2));
+ const settings = await getAllSettings().catch(() => ({}));
+ const minCom = parseInt(settings.bot_to_bot_comments_min, 10) ?? 1;
+ const maxCom = parseInt(settings.bot_to_bot_comments_max, 10) ?? 2;
+ const count = Math.max(1, minCom + Math.floor(Math.random() * (maxCom - minCom + 1)));
+ const participants = pick(chars, count);
+ const worldLang = settings.world_language || 'mixed';
+ const dmChance = (parseInt(settings.proactive_dm_comment_chance, 10) ?? 35) / 100;
+
for (const c of participants) {
try {
const text = await chatText(null, [
- { role: 'system', content: personaSystemPrompt(c) },
+ { role: 'system', content: personaSystemPrompt(c, '', worldLang) },
{ role: 'user', content: `Unter einem Post steht:\nPost: "${post.text}"\nKommentar des Nutzers: "${comment.text}"\n\nSchreib EINEN kurzen Reaktionskommentar darauf – in deinem Stil. Nur der Kommentar.` },
], { maxTokens: 100 });
@@ -85,8 +110,8 @@ export async function charsReplyToUserComment(comment, post, chars) {
}
}
- // 35% chance for a proactive DM after a comment
- if (participants.length > 0 && Math.random() < 0.35) {
+ // Proactive DM after comment
+ if (participants.length > 0 && Math.random() < dmChance) {
const dmChar = participants[0];
await sendProactiveDM(dmChar, `Der Nutzer hat unter dem Post "${post.text.slice(0, 80)}" kommentiert: "${comment.text}". Schreib ihm privat per DM (1-2 Sätze) dazu.`);
}
@@ -96,8 +121,10 @@ export async function charsReplyToUserComment(comment, post, chars) {
export async function sendProactiveDM(char, contextInstruction) {
if (!char || char.is_banned) return;
try {
- const isEn = char.language === 'en';
- const sysPrompt = personaSystemPrompt(char, isEn ? 'You are writing a private direct message (DM) to the human user.' : 'Du schreibst dem Nutzer privat per Direktnachricht (DM).');
+ const settings = await getAllSettings().catch(() => ({}));
+ const worldLang = settings.world_language || 'mixed';
+ const isEn = (worldLang === 'en') || (worldLang === 'mixed' && char.language === 'en');
+ const sysPrompt = personaSystemPrompt(char, isEn ? 'You are writing a private direct message (DM) to the human user.' : 'Du schreibst dem Nutzer privat per Direktnachricht (DM).', worldLang);
const prompt = isEn
? `${contextInstruction}\n\nSend the user a casual, friendly direct message (1-2 sentences). No formal greetings like "Dear", just slide directly into their DMs naturally.`
: `${contextInstruction}\n\nSchreib dem Nutzer eine lockere, direkte Privatnachricht (1-2 Sätze). Keine steife Anrede, schreib wie auf Social Media, wenn man jemandem privat schreibt.`;
@@ -118,30 +145,37 @@ export async function sendProactiveDM(char, contextInstruction) {
}
}
-// Generate a post for a character (feed content). ~1/3 chance with image.
+// Generate a post for a character (feed content).
export async function genCharPost(char) {
if (!char || char.is_banned) return null;
- const wantImage = hasKey() && Math.random() < 0.35;
+ const settings = await getAllSettings().catch(() => ({}));
+ const imagesEnabled = settings.bot_images_enabled !== '0';
+ const imgChance = (parseInt(settings.bot_image_chance, 10) ?? 35) / 100;
+ const wantImage = hasKey() && imagesEnabled && Math.random() < imgChance;
+ const worldLang = settings.world_language || 'mixed';
+
let text;
if (wantImage) {
text = await chatText(null, [
- { role: 'system', content: personaSystemPrompt(char, 'Du postest gerade etwas auf deinen Feed.') },
+ { role: 'system', content: personaSystemPrompt(char, 'Du postest gerade etwas auf deinen Feed.', worldLang) },
{ role: 'user', content: 'Schreib EINEN kurzen Social-Media-Post (2-4 Sätze max) zu einem Bild, das du postest. Beschreibe die Stimmung des Bildes in einem Satz am Ende in Anführungszeichen als Bild-Beschreibung, Format: [BILD: dein englischer Bild-Prompt].' },
], { maxTokens: 200, mockAsPost: true });
} else {
text = await chatText(null, [
- { role: 'system', content: personaSystemPrompt(char, 'Du postest gerade etwas auf deinen Feed.') },
+ { role: 'system', content: personaSystemPrompt(char, 'Du postest gerade etwas auf deinen Feed.', worldLang) },
{ role: 'user', content: 'Schreib EINEN kurzen, lebendigen Social-Media-Post (1-3 Sätze) über irgendetwas aus deinem Leben, deinen Hobbys oder deiner Meinung. Wie ein echter Mensch, nicht perfekt, mit Emojis wenn es passt.' },
], { maxTokens: 150, mockAsPost: true });
}
let imageKey = null;
const m = text.match(/\[BILD:\s*(.+?)\]/);
- if (m && hasKey()) {
+ if (m && hasKey() && imagesEnabled) {
try {
imageKey = await genImage(null, m[1], '1:1');
} catch (e) { console.error('post image failed', e); }
text = text.replace(m[0], '').trim();
+ } else if (m) {
+ text = text.replace(m[0], '').trim();
}
const post = { id: uid(), author_type: 'char', author_id: char.id, text, image_key: imageKey, created_at: Date.now() };
diff --git a/src/index.js b/src/index.js
index 825d76e..05dd75b 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,6 +1,6 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
-import { pool, initDb, uid, getChars, safeJson, getState, setState, updateUserActivity, getUserActivityStatus, isUserActive, banCharacter } from './db.js';
+import { pool, initDb, uid, getChars, safeJson, getState, setState, updateUserActivity, getUserActivityStatus, isUserActive, banCharacter, getAllSettings, saveSettings, updateCharacter, getBudgetStatus } from './db.js';
import { SEED_CHARACTERS, personaSystemPrompt, pickDailyChar, seedCharacters } from './personas.js';
import { chatText, genImage, hasKey } from './ai.js';
import { reactToUserPost, charactersEngageEachOther, charsReplyToUserComment, genCharPost, sendProactiveDM } from './engagement.js';
@@ -289,25 +289,35 @@ app.post('/api/feed-tick', async (c) => {
return c.json({ generated: false, reason: 'inactive_timeout' });
}
+ const settings = await getAllSettings().catch(() => ({}));
+ const intervalMin = parseInt(settings.feed_tick_interval_min, 10) ?? 20;
+ if (!body?.manual && intervalMin <= 0) {
+ return c.json({ generated: false, reason: 'disabled' });
+ }
+
const lastTick = Number(await getState('last_feed_tick', '0'));
const now = Date.now();
- if (!body?.manual && now - lastTick < 1000 * 60 * 20) return c.json({ generated: false, reason: 'rate_limited' });
+ if (!body?.manual && now - lastTick < 1000 * 60 * Math.max(1, intervalMin)) {
+ return c.json({ generated: false, reason: 'rate_limited' });
+ }
await setState('last_feed_tick', String(now));
const chars = await getChars();
if (!chars.length) return c.json({ generated: false, reason: 'no_active_chars' });
- const n = 1 + Math.floor(Math.random() * 2);
+ const postsCount = Math.max(1, parseInt(settings.feed_tick_posts_count, 10) || 1);
+ const tickDmChance = (parseInt(settings.proactive_dm_tick_chance, 10) ?? 35) / 100;
+
runBackground((async () => {
- for (let i = 0; i < n; i++) {
+ for (let i = 0; i < postsCount; i++) {
try {
const char = chars[Math.floor(Math.random() * chars.length)];
const post = await genCharPost(char);
if (post) await charactersEngageEachOther(post, char, chars);
} catch (e) { console.error(e); }
}
- // ~35% chance for an active character to slide into user's DMs during a tick
- if (Math.random() < 0.35) {
+ // Configurable chance for an active character to slide into user's DMs during a tick
+ if (Math.random() < tickDmChance) {
const activeChar = chars[Math.floor(Math.random() * chars.length)];
await sendProactiveDM(activeChar, 'Du bist gerade online und siehst, dass der Nutzer auch da ist. Schreib ihm eine kurze lockere Nachricht (1-2 Sätze), wie es ihm geht oder was er treibt.');
}
@@ -462,14 +472,66 @@ app.get('/api/admin/status', async (c) => {
const totalCharsRes = await pool.query('SELECT COUNT(*)::int AS n FROM characters;');
const bannedCharsRes = await pool.query('SELECT COUNT(*)::int AS n FROM characters WHERE is_banned = 1;');
const totalPostsRes = await pool.query('SELECT COUNT(*)::int AS n FROM posts;');
+ const budget = await getBudgetStatus();
return c.json({
...act,
totalChars: totalCharsRes.rows[0]?.n || 0,
bannedChars: bannedCharsRes.rows[0]?.n || 0,
totalPosts: totalPostsRes.rows[0]?.n || 0,
+ budget,
});
});
+app.get('/api/admin/settings', async (c) => {
+ const settings = await getAllSettings();
+ const budget = await getBudgetStatus();
+ const rawKey = settings.ai_api_key || process.env.AI_API_KEY || process.env.MINIMAX_API_KEY || '';
+ const maskedKey = rawKey ? '••••••••' + rawKey.slice(-4) : '';
+ return c.json({
+ settings: {
+ ...settings,
+ ai_api_key_masked: maskedKey,
+ has_key: Boolean(rawKey),
+ },
+ budget,
+ });
+});
+
+app.post('/api/admin/settings', async (c) => {
+ const body = await c.req.json().catch(() => ({}));
+ const toSave = { ...body };
+
+ // Don't overwrite with masked or placeholder key
+ if (toSave.ai_api_key && toSave.ai_api_key.includes('••••')) {
+ delete toSave.ai_api_key;
+ }
+
+ await saveSettings(toSave);
+ await updateUserActivity();
+
+ const settings = await getAllSettings();
+ const budget = await getBudgetStatus();
+ const rawKey = settings.ai_api_key || process.env.AI_API_KEY || process.env.MINIMAX_API_KEY || '';
+ return c.json({
+ ok: true,
+ settings: {
+ ...settings,
+ ai_api_key_masked: rawKey ? '••••••••' + rawKey.slice(-4) : '',
+ has_key: Boolean(rawKey),
+ },
+ budget,
+ });
+});
+
+app.put('/api/admin/characters/:id', async (c) => {
+ const id = c.req.param('id');
+ const body = await c.req.json().catch(() => ({}));
+ const updated = await updateCharacter(id, body);
+ if (!updated) return c.json({ error: 'Charakter nicht gefunden oder keine Änderungen' }, 404);
+ await updateUserActivity();
+ return c.json({ ok: true, character: updated });
+});
+
app.post('/api/admin/timeout', async (c) => {
const { hours } = await c.req.json().catch(() => ({}));
const num = parseFloat(hours);
diff --git a/src/personas.js b/src/personas.js
index 7693d57..c53ca82 100644
--- a/src/personas.js
+++ b/src/personas.js
@@ -184,8 +184,9 @@ export const SEED_POSTS = [
},
];
-export function personaSystemPrompt(char, extra = '') {
- const lang = char.language === 'en'
+export function personaSystemPrompt(char, extra = '', overrideLang = null) {
+ const effectiveLang = (overrideLang && overrideLang !== 'mixed') ? overrideLang : char.language;
+ const lang = effectiveLang === 'en'
? 'You ALWAYS reply in natural English.'
: 'Du antwortest IMMER auf Deutsch.';
const hobbies = (char.hobbies || []).join(', ');
diff --git a/src/server.js b/src/server.js
index c0e9055..f4a98a3 100644
--- a/src/server.js
+++ b/src/server.js
@@ -54,37 +54,75 @@ async function start() {
}
function startBackgroundSimulation() {
- const SIMULATION_INTERVAL_MS = 20 * 60 * 1000;
+ const CHECK_INTERVAL_MS = 30 * 1000; // Check every 30 seconds
setInterval(async () => {
try {
- const { isUserActive, getChars, setState } = await import('./db.js');
+ const { isUserActive, getChars, getState, setState, getAllSettings, checkAndIncrementBudget } = await import('./db.js');
const { genCharPost, charactersEngageEachOther, sendProactiveDM } = await import('./engagement.js');
+ const settings = await getAllSettings().catch(() => ({}));
+ const intervalMin = parseInt(settings.feed_tick_interval_min, 10) ?? 20;
+ if (intervalMin <= 0) return; // Background simulation disabled by setting
+
+ const lastTick = Number(await getState('last_feed_tick', '0'));
+ const now = Date.now();
+ if (now - lastTick < intervalMin * 60 * 1000) return;
+
const active = await isUserActive();
if (!active) {
- console.log('⏳ [Token-Schutz] Keine Nutzer-Interaktion im Timeout-Fenster – Hintergrund-KI pausiert.');
- return;
+ return; // Inactivity timeout active
+ }
+
+ // Check daily budget cap
+ const budgetOk = await checkAndIncrementBudget();
+ if (!budgetOk) return;
+
+ // Handle daily character auto-spawn if enabled
+ if (settings.daily_char_autospawn !== '0') {
+ const today = new Date().toISOString().slice(0, 10);
+ const lastDaily = await getState('last_daily_char');
+ if (lastDaily !== today) {
+ try {
+ const { pickDailyChar } = await import('./personas.js');
+ const { uid, pool } = await import('./db.js');
+ const spec = pickDailyChar();
+ const id = uid();
+ await pool.query(
+ `INSERT INTO characters (id, name, handle, bio, hobbies, personality, language, avatar_key, created_at, is_custom)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 0);`,
+ [id, spec.name, spec.handle, spec.bio, JSON.stringify(spec.hobbies), spec.personality, spec.language, spec.avatar, Date.now()]
+ );
+ await setState('last_daily_char', today);
+ console.log(`✨ [Tagescharakter] ${spec.name} ist automatisch beigetreten`);
+ } catch (e) {
+ console.error('Auto daily char error:', e.message);
+ }
+ }
}
const chars = await getChars();
if (!chars.length) return;
- const char = chars[Math.floor(Math.random() * chars.length)];
- const post = await genCharPost(char);
- if (post) {
- await charactersEngageEachOther(post, char, chars);
- await setState('last_feed_tick', String(Date.now()));
- console.log(`✓ [Hintergrund-Simulation] Neuer Post von @${char.handle}`);
+ const postsCount = Math.max(1, parseInt(settings.feed_tick_posts_count, 10) || 1);
+ for (let i = 0; i < postsCount; i++) {
+ const char = chars[Math.floor(Math.random() * chars.length)];
+ const post = await genCharPost(char);
+ if (post) {
+ await charactersEngageEachOther(post, char, chars);
+ console.log(`✓ [Hintergrund-Simulation] Neuer Post von @${char.handle}`);
+ }
}
+ await setState('last_feed_tick', String(now));
- if (Math.random() < 0.35) {
+ const tickDmChance = (parseInt(settings.proactive_dm_tick_chance, 10) ?? 35) / 100;
+ if (Math.random() < tickDmChance) {
const activeChar = chars[Math.floor(Math.random() * chars.length)];
await sendProactiveDM(activeChar, 'Du bist gerade online und siehst, dass der Nutzer auch da ist. Schreib ihm eine kurze lockere Nachricht (1-2 Sätze), wie es ihm geht oder was er treibt.');
}
} catch (err) {
console.error('Simulation loop error:', err.message);
}
- }, SIMULATION_INTERVAL_MS);
+ }, CHECK_INTERVAL_MS);
}
start();