feat: Vollständige Admin-Einstellungen für Token-Budget, Dynamik, KI-Provider & Charakter-Editor
This commit is contained in:
1 parent
357692542d
commit
9db92201a9
8 files changed
+954
-86
No files matched your search
+533
-31
@@ -47,8 +47,9 @@ const I18N = {
|
||||
likes_lbl:'Likes', posts_lbl:'Beiträge', people_lbl:'Charaktere',
|
||||
new_post:'+ Neuer Post', compose_ph:'Was läuft bei dir?',
|
||||
delete:'Löschen', confirm_del:'Diesen Post wirklich löschen?',
|
||||
admin_title:'Admin Panel', admin_timeout:'⏱️ Token-Schutz & Timeout',
|
||||
admin_chars:'👥 Char-Ban & Charaktere', admin_posts:'🗑️ Posts verwalten',
|
||||
admin_title:'Admin Panel', admin_timeout:'⏱️ Token & Budget',
|
||||
admin_dynamics:'🎭 Dynamik', admin_ai:'🤖 KI & Provider',
|
||||
admin_chars:'👥 Charaktere', admin_posts:'🗑️ Posts',
|
||||
status_active:'Aktiv (KI generiert)', status_paused:'Pausiert (Token-Schutz)',
|
||||
timeout_desc:'Automatischer Token-Schutz: Wenn für die gewählte Zeitspanne keine Interaktion von dir erfolgt (kein Posten, Kommentieren, Liken oder Chatten), pausieren alle Hintergrund-Aktionen der KI vollständig, damit keine Tokens verschwendet werden.',
|
||||
timeout_label:'Inaktivitäts-Timeout (Stunden):',
|
||||
@@ -56,14 +57,48 @@ const I18N = {
|
||||
wake_up:'⚡ Jetzt aktivieren (Aufwecken)',
|
||||
last_interaction:'Letzte Interaktion:',
|
||||
time_elapsed:'Inaktiv seit:',
|
||||
ban_char:'⛔ Bannen / Entfernen',
|
||||
unban_char:'✅ Reaktivieren / Entbannen',
|
||||
ban_char:'⛔ Bannen',
|
||||
unban_char:'✅ Entbannen',
|
||||
confirm_ban:'Diesen Charakter wirklich entfernen/bannen? Er wird keine neuen Beiträge, Kommentare oder DMs mehr erstellen. Alle bisherigen Nachrichten bleiben erhalten.',
|
||||
confirm_unban:'Diesen Charakter wieder reaktivieren?',
|
||||
status_banned:'Gesperrt', status_char_active:'Aktiv',
|
||||
char_banned_note:'Dieser Charakter ist gesperrt/entfernt – keine neuen Nachrichten.',
|
||||
all_posts:'Alle Posts', ai_posts:'Nur KI', user_posts:'Nur Eigene',
|
||||
search_ph:'Suchen…', post_deleted:'Post wurde gelöscht.',
|
||||
settings_saved:'Einstellungen erfolgreich gespeichert ✓',
|
||||
char_saved:'Charakter erfolgreich aktualisiert ✓',
|
||||
edit_char:'✏️ Bearbeiten', edit_char_title:'Charakter bearbeiten',
|
||||
save:'Speichern', cancel:'Abbrechen',
|
||||
sec_token_cost:'Token- & Kostenkontrolle',
|
||||
sec_images:'KI-Bilder (Kostenfresser-Kontrolle)',
|
||||
sec_feed:'Feed-Frequenz & Auto-Posts',
|
||||
sec_budget:'Tageslimit / Budget-Cap',
|
||||
sec_reactions:'Reaktionen auf deine Beiträge',
|
||||
sec_dms:'Proaktive Direktnachrichten (DMs)',
|
||||
sec_bot_bot:'Dynamik zwischen KI-Charakteren',
|
||||
sec_provider:'KI-Provider & Modell-Auswahl',
|
||||
sec_world:'Globale Welteinstellungen',
|
||||
bot_images_toggle:'KI-Bilder für Bot-Posts erlauben',
|
||||
bot_image_chance:'Bild-Wahrscheinlichkeit bei Bot-Posts',
|
||||
feed_interval:'Posting-Intervall im Hintergrund',
|
||||
posts_per_tick:'Posts pro Durchlauf',
|
||||
daily_budget_lbl:'Max. KI-Aktionen pro Tag (0 = unbegrenzt)',
|
||||
daily_budget_status:'Tagesverbrauch heute:',
|
||||
actions_used:'Aktionen verbraucht',
|
||||
budget_reached:'Tageslimit erreicht – pausiert bis morgen',
|
||||
react_min_lbl:'Minimale Reaktionen', react_max_lbl:'Maximale Reaktionen',
|
||||
like_chance_lbl:'Like-Wahrscheinlichkeit auf deine Posts',
|
||||
dm_post_chance_lbl:'DM-Chance nach neuem Post von dir',
|
||||
dm_comment_chance_lbl:'DM-Chance nach Kommentar von dir',
|
||||
dm_tick_chance_lbl:'DM-Chance bei Hintergrund-Tick',
|
||||
bot_comments_lbl:'Kommentare unter Fremdposts (Min - Max)',
|
||||
provider_lbl:'Aktiver KI-Provider',
|
||||
model_lbl:'Modell-Name',
|
||||
temp_lbl:'Kreativität / Temperatur',
|
||||
api_key_lbl:'API-Key (Optional überschreiben)',
|
||||
base_url_lbl:'Base URL (Optional für LiteLLM / Ollama)',
|
||||
world_lang_lbl:'Weltsprache der Bots',
|
||||
auto_daily_char_lbl:'Täglich automatisch neuen Charakter spawnen',
|
||||
},
|
||||
en: {
|
||||
tab_feed:'Feed', tab_chars:'Characters', tab_chats:'Chats', tab_me:'You', tab_admin:'Admin Panel',
|
||||
@@ -90,8 +125,9 @@ const I18N = {
|
||||
likes_lbl:'Likes', posts_lbl:'Posts', people_lbl:'Characters',
|
||||
new_post:'+ New post', compose_ph:'What is going on with you?',
|
||||
delete:'Delete', confirm_del:'Really delete this post?',
|
||||
admin_title:'Admin Panel', admin_timeout:'⏱️ Token Saver & Timeout',
|
||||
admin_chars:'👥 Char Ban & Characters', admin_posts:'🗑️ Manage Posts',
|
||||
admin_title:'Admin Panel', admin_timeout:'⏱️ Token & Budget',
|
||||
admin_dynamics:'🎭 Dynamics', admin_ai:'🤖 AI & Provider',
|
||||
admin_chars:'👥 Characters', admin_posts:'🗑️ Posts',
|
||||
status_active:'Active (AI Generating)', status_paused:'Paused (Token Saver)',
|
||||
timeout_desc:'Automatic token protection: When no user interaction occurs for the configured period (no posting, commenting, liking, or chatting), all background AI actions pause completely to prevent token waste.',
|
||||
timeout_label:'Inactivity timeout (hours):',
|
||||
@@ -99,14 +135,48 @@ const I18N = {
|
||||
wake_up:'⚡ Activate Now (Wake Up)',
|
||||
last_interaction:'Last interaction:',
|
||||
time_elapsed:'Inactive for:',
|
||||
ban_char:'⛔ Ban / Remove',
|
||||
unban_char:'✅ Reactivate / Unban',
|
||||
ban_char:'⛔ Ban',
|
||||
unban_char:'✅ Unban',
|
||||
confirm_ban:'Really remove/ban this character? They will no longer create new posts, comments, or DMs. All past messages will remain intact.',
|
||||
confirm_unban:'Reactivate this character?',
|
||||
status_banned:'Banned', status_char_active:'Active',
|
||||
char_banned_note:'This character is banned/removed – no new messages.',
|
||||
all_posts:'All Posts', ai_posts:'AI Only', user_posts:'Yours Only',
|
||||
search_ph:'Search…', post_deleted:'Post deleted.',
|
||||
settings_saved:'Settings successfully saved ✓',
|
||||
char_saved:'Character successfully updated ✓',
|
||||
edit_char:'✏️ Edit', edit_char_title:'Edit Character',
|
||||
save:'Save', cancel:'Cancel',
|
||||
sec_token_cost:'Token & Cost Control',
|
||||
sec_images:'AI Images (Credit Saver)',
|
||||
sec_feed:'Feed Frequency & Auto Posts',
|
||||
sec_budget:'Daily Budget / Action Cap',
|
||||
sec_reactions:'Reactions to Your Posts',
|
||||
sec_dms:'Proactive Direct Messages (DMs)',
|
||||
sec_bot_bot:'Dynamics Between AI Characters',
|
||||
sec_provider:'AI Provider & Model Selection',
|
||||
sec_world:'Global World Settings',
|
||||
bot_images_toggle:'Allow AI images for bot posts',
|
||||
bot_image_chance:'Image chance for bot posts',
|
||||
feed_interval:'Background posting interval',
|
||||
posts_per_tick:'Posts per interval',
|
||||
daily_budget_lbl:'Max AI actions per day (0 = unlimited)',
|
||||
daily_budget_status:'Today’s action count:',
|
||||
actions_used:'actions used',
|
||||
budget_reached:'Daily cap reached – paused until tomorrow',
|
||||
react_min_lbl:'Min reactions', react_max_lbl:'Max reactions',
|
||||
like_chance_lbl:'Like probability on your posts',
|
||||
dm_post_chance_lbl:'DM chance after your new post',
|
||||
dm_comment_chance_lbl:'DM chance after your comment',
|
||||
dm_tick_chance_lbl:'DM chance during feed tick',
|
||||
bot_comments_lbl:'Comments under bot posts (Min - Max)',
|
||||
provider_lbl:'Active AI Provider',
|
||||
model_lbl:'Model Name',
|
||||
temp_lbl:'Creativity / Temperature',
|
||||
api_key_lbl:'API Key (Optional override)',
|
||||
base_url_lbl:'Base URL (Optional for LiteLLM / Ollama)',
|
||||
world_lang_lbl:'Bots World Language',
|
||||
auto_daily_char_lbl:'Automatically spawn new daily character',
|
||||
},
|
||||
};
|
||||
const t = (k) => I18N[state.lang][k] ?? k;
|
||||
@@ -607,12 +677,93 @@ function renderThread(main) {
|
||||
}
|
||||
|
||||
/* ---------------- admin panel ---------------- */
|
||||
function openCharEditModal(char, onSave) {
|
||||
const root = $('#modal-root');
|
||||
root.innerHTML = `
|
||||
<div class="modal-overlay" id="modal-bg">
|
||||
<div class="modal-box">
|
||||
<div class="modal-head">
|
||||
<div class="modal-title">${t('edit_char_title')}: ${esc(char.name)}</div>
|
||||
<button class="modal-close" id="m-close">✕</button>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('c_name')}</label>
|
||||
<input type="text" id="m-name" value="${esc(char.name)}" maxlength="100">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>@Handle</label>
|
||||
<input type="text" id="m-handle" value="${esc(char.handle)}" maxlength="50">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('c_bio')}</label>
|
||||
<textarea id="m-bio" rows="2" maxlength="500">${esc(char.bio || '')}</textarea>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('c_hobbies')}</label>
|
||||
<input type="text" id="m-hobbies" value="${esc((char.hobbies || []).join(', '))}">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('c_perso')}</label>
|
||||
<textarea id="m-perso" rows="3" maxlength="1000">${esc(char.personality || '')}</textarea>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('c_lang')}</label>
|
||||
<select id="m-lang">
|
||||
<option value="de" ${char.language === 'de' ? 'selected' : ''}>🇩🇪 Deutsch</option>
|
||||
<option value="en" ${char.language === 'en' ? 'selected' : ''}>🇬🇧 English</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="modal-foot">
|
||||
<button class="btn ghost sm" id="m-cancel">${t('cancel')}</button>
|
||||
<button class="btn sm" id="m-save">${t('save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
$('#m-close')?.addEventListener('click', close);
|
||||
$('#m-cancel')?.addEventListener('click', close);
|
||||
$('#modal-bg')?.addEventListener('click', (e) => {
|
||||
if (e.target.id === 'modal-bg') close();
|
||||
});
|
||||
|
||||
$('#m-save')?.addEventListener('click', async () => {
|
||||
const name = $('#m-name').value.trim();
|
||||
const handle = $('#m-handle').value.trim();
|
||||
if (!name || !handle) return toast('Name & Handle erforderlich', true);
|
||||
|
||||
const hobbies = $('#m-hobbies').value.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
const body = {
|
||||
name,
|
||||
handle,
|
||||
bio: $('#m-bio').value.trim(),
|
||||
hobbies,
|
||||
personality: $('#m-perso').value.trim(),
|
||||
language: $('#m-lang').value,
|
||||
};
|
||||
|
||||
const btn = $('#m-save');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await api(`/api/admin/characters/${char.id}`, { method: 'PUT', body });
|
||||
toast(t('char_saved'));
|
||||
close();
|
||||
if (onSave) onSave();
|
||||
} catch (err) {
|
||||
toast(err.message, true);
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function viewAdmin(main) {
|
||||
main.innerHTML = loadingHTML();
|
||||
const [status, charsData, postsData] = await Promise.all([
|
||||
const [status, charsData, postsData, settingsData] = await Promise.all([
|
||||
api('/api/admin/status'),
|
||||
api('/api/admin/characters'),
|
||||
api('/api/admin/posts'),
|
||||
api('/api/admin/settings'),
|
||||
]);
|
||||
|
||||
state.systemActive = status.active;
|
||||
@@ -620,6 +771,8 @@ async function viewAdmin(main) {
|
||||
|
||||
const chars = charsData.characters || [];
|
||||
const posts = postsData.posts || [];
|
||||
const settings = settingsData.settings || {};
|
||||
const budget = settingsData.budget || status.budget || { limit: 0, count: 0 };
|
||||
const bannedChars = chars.filter((c) => c.isBanned);
|
||||
const activeChars = chars.filter((c) => !c.isBanned);
|
||||
|
||||
@@ -634,19 +787,22 @@ async function viewAdmin(main) {
|
||||
|
||||
const renderAdminTabs = () => `
|
||||
<div class="admin-nav">
|
||||
<button class="admin-tab ${state.adminTab === 'timeout' ? 'active' : ''}" data-tab="timeout">⏱️ ${t('admin_timeout')}</button>
|
||||
<button class="admin-tab ${state.adminTab === 'chars' ? 'active' : ''}" data-tab="chars">👥 ${t('admin_chars')} (${chars.length})</button>
|
||||
<button class="admin-tab ${state.adminTab === 'posts' ? 'active' : ''}" data-tab="posts">🗑️ ${t('admin_posts')} (${posts.length})</button>
|
||||
<button class="admin-tab ${state.adminTab === 'timeout' ? 'active' : ''}" data-tab="timeout">${t('admin_timeout')}</button>
|
||||
<button class="admin-tab ${state.adminTab === 'dynamics' ? 'active' : ''}" data-tab="dynamics">${t('admin_dynamics')}</button>
|
||||
<button class="admin-tab ${state.adminTab === 'ai' ? 'active' : ''}" data-tab="ai">${t('admin_ai')}</button>
|
||||
<button class="admin-tab ${state.adminTab === 'chars' ? 'active' : ''}" data-tab="chars">${t('admin_chars')} (${chars.length})</button>
|
||||
<button class="admin-tab ${state.adminTab === 'posts' ? 'active' : ''}" data-tab="posts">${t('admin_posts')} (${posts.length})</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let tabContent = '';
|
||||
|
||||
// 1. TOKEN & BUDGET
|
||||
if (state.adminTab === 'timeout') {
|
||||
tabContent = `
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-title">
|
||||
<span>${t('admin_timeout')}</span>
|
||||
<span>${t('sec_token_cost')}</span>
|
||||
<span class="status-pill ${status.active ? 'active' : 'paused'}">
|
||||
${status.active ? `🟢 ${t('status_active')}` : `⏸️ ${t('status_paused')}`}
|
||||
</span>
|
||||
@@ -655,7 +811,7 @@ async function viewAdmin(main) {
|
||||
|
||||
<div class="admin-grid">
|
||||
<div class="admin-stat">
|
||||
<span class="val">${status.timeoutHours}h</span>
|
||||
<span class="val">${settings.timeout_hours || status.timeoutHours}h</span>
|
||||
<span class="lbl">${t('timeout_label')}</span>
|
||||
</div>
|
||||
<div class="admin-stat">
|
||||
@@ -668,25 +824,232 @@ async function viewAdmin(main) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row" style="margin-top:14px">
|
||||
<label style="font-weight:600">${t('timeout_label')}</label>
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">⏱️ ${t('timeout_label')}</div>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
|
||||
<input type="number" id="timeout-input" value="${status.timeoutHours}" min="0.1" max="168" step="0.5" style="max-width:140px;background:var(--bg2)">
|
||||
<input type="number" id="s-timeout" value="${settings.timeout_hours || '2'}" min="0.1" max="168" step="0.5" style="max-width:130px">
|
||||
<button class="btn sm" id="save-timeout-btn">${t('save_timeout')}</button>
|
||||
<button class="btn sm ghost" id="wake-btn">${t('wake_up')}</button>
|
||||
</div>
|
||||
<div class="quick-btn-row">
|
||||
<button class="quick-btn" data-hours="0.5">30 Min (0.5h)</button>
|
||||
<button class="quick-btn" data-hours="1">1h</button>
|
||||
<button class="quick-btn" data-hours="2">2h (${t('admin_timeout').includes('Standard') ? 'Standard' : 'Default'})</button>
|
||||
<button class="quick-btn" data-hours="2">2h (Standard)</button>
|
||||
<button class="quick-btn" data-hours="4">4h</button>
|
||||
<button class="quick-btn" data-hours="8">8h</button>
|
||||
<button class="quick-btn" data-hours="24">24h</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">🎨 ${t('sec_images')}</div>
|
||||
<div class="settings-desc">KI-Bilder verbrauchen die meisten Tokens/Credits. Du kannst sie für Bot-Posts deaktivieren oder die Wahrscheinlichkeit anpassen.</div>
|
||||
<label class="switch-label">
|
||||
<span>${t('bot_images_toggle')}</span>
|
||||
<input type="checkbox" id="s-bot-img-toggle" ${settings.bot_images_enabled !== '0' ? 'checked' : ''}>
|
||||
</label>
|
||||
<div class="form-row" style="margin-top:10px">
|
||||
<label>${t('bot_image_chance')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-bot-img-chance" min="0" max="100" value="${settings.bot_image_chance || '35'}">
|
||||
<span class="range-val" id="val-img-chance">${settings.bot_image_chance || '35'}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">🔄 ${t('sec_feed')}</div>
|
||||
<div class="settings-desc">Wie oft und wie viele Posts die Bots von alleine im Hintergrund veröffentlichen, wenn du aktiv bist.</div>
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:8px">
|
||||
<div>
|
||||
<label style="font-size:12px;color:var(--muted)">${t('feed_interval')}</label>
|
||||
<select id="s-feed-interval" style="margin-top:4px">
|
||||
<option value="0" ${settings.feed_tick_interval_min === '0' ? 'selected' : ''}>0 (Deaktiviert / Nur manuell)</option>
|
||||
<option value="10" ${settings.feed_tick_interval_min === '10' ? 'selected' : ''}>10 Min.</option>
|
||||
<option value="15" ${settings.feed_tick_interval_min === '15' ? 'selected' : ''}>15 Min.</option>
|
||||
<option value="20" ${settings.feed_tick_interval_min === '20' ? 'selected' : ''}>20 Min. (Standard)</option>
|
||||
<option value="30" ${settings.feed_tick_interval_min === '30' ? 'selected' : ''}>30 Min.</option>
|
||||
<option value="60" ${settings.feed_tick_interval_min === '60' ? 'selected' : ''}>1 Std.</option>
|
||||
<option value="120" ${settings.feed_tick_interval_min === '120' ? 'selected' : ''}>2 Std.</option>
|
||||
<option value="180" ${settings.feed_tick_interval_min === '180' ? 'selected' : ''}>3 Std.</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label style="font-size:12px;color:var(--muted)">${t('posts_per_tick')}</label>
|
||||
<select id="s-posts-per-tick" style="margin-top:4px">
|
||||
<option value="1" ${settings.feed_tick_posts_count === '1' ? 'selected' : ''}>1 Post</option>
|
||||
<option value="2" ${settings.feed_tick_posts_count === '2' ? 'selected' : ''}>2 Posts</option>
|
||||
<option value="3" ${settings.feed_tick_posts_count === '3' ? 'selected' : ''}>3 Posts</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">🛡️ ${t('sec_budget')}</div>
|
||||
<div class="settings-desc">Maximales Limit für automatische KI-Generierungen pro Tag. Verhindert unkontrollierten Verbrauch.</div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
|
||||
<input type="number" id="s-daily-budget" value="${settings.daily_budget_limit || '0'}" min="0" max="5000" style="max-width:140px">
|
||||
<span class="hint" style="margin-top:0">${t('daily_budget_status')} <b>${budget.count}</b> ${budget.limit > 0 ? `/ ${budget.limit}` : ''} ${t('actions_used')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:16px;text-align:right">
|
||||
<button class="btn" id="save-token-settings-btn">${t('save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else if (state.adminTab === 'chars') {
|
||||
}
|
||||
|
||||
// 2. DYNAMIK
|
||||
else if (state.adminTab === 'dynamics') {
|
||||
tabContent = `
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-title">
|
||||
<span>${t('admin_dynamics')}</span>
|
||||
</div>
|
||||
<p class="hint" style="line-height:1.5;margin-bottom:14px">Passe an, wie aktiv, aufdringlich oder enthusiastisch die KI-Charaktere reagieren.</p>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">💬 ${t('sec_reactions')}</div>
|
||||
<div class="settings-desc">Anzahl der Bots, die auf deinen neuen Beitrag kommentieren, und deren Like-Wahrscheinlichkeit.</div>
|
||||
<div style="display:flex;gap:12px;align-items:center;margin-bottom:10px;flex-wrap:wrap">
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<span style="font-size:12px;color:var(--muted)">Min:</span>
|
||||
<input type="number" id="s-react-min" value="${settings.user_post_reactions_min || '2'}" min="0" max="10" style="width:70px">
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<span style="font-size:12px;color:var(--muted)">Max:</span>
|
||||
<input type="number" id="s-react-max" value="${settings.user_post_reactions_max || '4'}" min="1" max="15" style="width:70px">
|
||||
</div>
|
||||
<div class="quick-btn-row" style="margin:0">
|
||||
<button class="quick-btn" id="preset-calm">Ruhig (1-2)</button>
|
||||
<button class="quick-btn" id="preset-normal">Normal (2-4)</button>
|
||||
<button class="quick-btn" id="preset-hype">Hype (4-7)</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('like_chance_lbl')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-like-chance" min="0" max="100" value="${settings.user_post_like_chance || '70'}">
|
||||
<span class="range-val" id="val-like-chance">${settings.user_post_like_chance || '70'}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">📬 ${t('sec_dms')}</div>
|
||||
<div class="settings-desc">Wahrscheinlichkeit, dass Charaktere proaktiv von selbst in deine DMs sliden.</div>
|
||||
<div class="form-row">
|
||||
<label>${t('dm_post_chance_lbl')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-dm-post" min="0" max="100" value="${settings.proactive_dm_post_chance || '65'}">
|
||||
<span class="range-val" id="val-dm-post">${settings.proactive_dm_post_chance || '65'}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('dm_comment_chance_lbl')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-dm-comment" min="0" max="100" value="${settings.proactive_dm_comment_chance || '35'}">
|
||||
<span class="range-val" id="val-dm-comment">${settings.proactive_dm_comment_chance || '35'}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>${t('dm_tick_chance_lbl')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-dm-tick" min="0" max="100" value="${settings.proactive_dm_tick_chance || '35'}">
|
||||
<span class="range-val" id="val-dm-tick">${settings.proactive_dm_tick_chance || '35'}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="settings-title">👥 ${t('sec_bot_bot')}</div>
|
||||
<div class="settings-desc">Wie viele Kommentare Bots unter Beiträgen anderer Bots hinterlassen (0 = KIs reden nicht untereinander).</div>
|
||||
<div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap">
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<span style="font-size:12px;color:var(--muted)">Min:</span>
|
||||
<input type="number" id="s-bot-min" value="${settings.bot_to_bot_comments_min || '1'}" min="0" max="5" style="width:70px">
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:6px">
|
||||
<span style="font-size:12px;color:var(--muted)">Max:</span>
|
||||
<input type="number" id="s-bot-max" value="${settings.bot_to_bot_comments_max || '2'}" min="0" max="8" style="width:70px">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:16px;text-align:right">
|
||||
<button class="btn" id="save-dynamics-btn">${t('save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 3. KI & PROVIDER
|
||||
else if (state.adminTab === 'ai') {
|
||||
const curProvider = (settings.ai_provider || 'minimax').toLowerCase();
|
||||
tabContent = `
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-title">
|
||||
<span>${t('sec_provider')}</span>
|
||||
<span class="badge ${settings.has_key ? 'active-b' : 'banned'}">
|
||||
${settings.has_key ? 'API-Key aktiv ✓' : 'Demo / Mock'}
|
||||
</span>
|
||||
</div>
|
||||
<p class="hint" style="line-height:1.5;margin-bottom:14px">
|
||||
Passe Provider, Modell und Temperatur im laufenden Betrieb an – ohne Neustart von Docker oder Server.
|
||||
</p>
|
||||
|
||||
<div class="settings-group">
|
||||
<div class="form-row">
|
||||
<label>${t('provider_lbl')}</label>
|
||||
<select id="s-ai-provider">
|
||||
<option value="minimax" ${curProvider === 'minimax' ? 'selected' : ''}>MiniMax (Standard)</option>
|
||||
<option value="openrouter" ${curProvider === 'openrouter' ? 'selected' : ''}>OpenRouter (Llama 3.3, Mistral, etc.)</option>
|
||||
<option value="openai" ${curProvider === 'openai' ? 'selected' : ''}>OpenAI (GPT-4o, GPT-4o-mini)</option>
|
||||
<option value="gemini" ${curProvider === 'gemini' ? 'selected' : ''}>Google Gemini (Gemini 1.5 Flash)</option>
|
||||
<option value="anthropic" ${curProvider === 'anthropic' ? 'selected' : ''}>Anthropic (Claude 3.5 Haiku)</option>
|
||||
<option value="litellm" ${curProvider === 'litellm' ? 'selected' : ''}>LiteLLM / Custom Proxy</option>
|
||||
<option value="ollama" ${curProvider === 'ollama' ? 'selected' : ''}>Ollama (Lokal)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>${t('model_lbl')}</label>
|
||||
<input type="text" id="s-ai-model" value="${esc(settings.ai_model || '')}" placeholder="z. B. MiniMax-M3, gpt-4o-mini, meta-llama/llama-3.3-70b-instruct">
|
||||
<div class="hint">Modellname, der an die API übergeben wird.</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>${t('temp_lbl')}</label>
|
||||
<div class="range-wrap">
|
||||
<input type="range" id="s-ai-temp" min="0.1" max="1.5" step="0.05" value="${settings.ai_temperature || '0.7'}">
|
||||
<span class="range-val" id="val-ai-temp">${settings.ai_temperature || '0.7'}</span>
|
||||
</div>
|
||||
<div class="hint">Niedriger (0.3–0.5) = sachlicher, konsistenter. Höher (0.7–1.0) = lockerer, kreativer, verspielter.</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>${t('api_key_lbl')}</label>
|
||||
<input type="password" id="s-ai-key" placeholder="${settings.ai_api_key_masked ? `Vorhanden (${settings.ai_api_key_masked})` : 'Freilassen für Standard aus .env'}">
|
||||
<div class="hint">Freilassen, um den API-Key aus Umgebungsvariablen (.env / docker-compose) zu verwenden.</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>${t('base_url_lbl')}</label>
|
||||
<input type="text" id="s-ai-base-url" value="${esc(settings.ai_base_url || '')}" placeholder="z. B. http://host.docker.internal:11434/v1">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="margin-top:16px;text-align:right">
|
||||
<button class="btn" id="save-ai-settings-btn">${t('save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 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 = `
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-title">
|
||||
<span>${t('sec_world')}</span>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;align-items:center;margin-bottom:8px">
|
||||
<div>
|
||||
<label style="font-size:12px;color:var(--muted)">${t('world_lang_lbl')}</label>
|
||||
<select id="s-world-lang" style="margin-top:4px">
|
||||
<option value="mixed" ${settings.world_language === 'mixed' ? 'selected' : ''}>${t('lang_mixed')}</option>
|
||||
<option value="de" ${settings.world_language === 'de' ? 'selected' : ''}>${t('lang_de')}</option>
|
||||
<option value="en" ${settings.world_language === 'en' ? 'selected' : ''}>${t('lang_en')}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="switch-label" style="margin-top:20px">
|
||||
<span>${t('auto_daily_char_lbl')}</span>
|
||||
<input type="checkbox" id="s-daily-autospawn" ${settings.daily_char_autospawn !== '0' ? 'checked' : ''}>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div style="text-align:right">
|
||||
<button class="btn sm" id="save-world-settings-btn">${t('save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-title">
|
||||
<span>${t('admin_chars')}</span>
|
||||
<span style="font-size:13px;color:var(--muted)">${activeChars.length} ${t('status_char_active')} · ${bannedChars.length} ${t('status_banned')}</span>
|
||||
</div>
|
||||
<p class="hint" style="line-height:1.5;margin-bottom:12px">
|
||||
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.
|
||||
</p>
|
||||
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-bottom:12px;flex-wrap:wrap">
|
||||
@@ -719,22 +1109,28 @@ async function viewAdmin(main) {
|
||||
${filteredChars.length ? filteredChars.map((c) => `
|
||||
<div class="admin-char-item ${c.isBanned ? 'is-banned' : ''}">
|
||||
${avatar(c.name, c.avatarKey)}
|
||||
<div class="who" style="flex:1;min-width:120px">
|
||||
<div class="who" style="flex:1;min-width:130px">
|
||||
<span class="name">${esc(c.name)} ${c.isCustom ? '✨' : ''}</span>
|
||||
<span class="handle">@${esc(c.handle)} · ${c.language === 'en' ? 'EN' : 'DE'} · ${c.postCount} Posts · ${c.messageCount} DMs</span>
|
||||
</div>
|
||||
<span class="badge ${c.isBanned ? 'banned' : 'active-b'}">
|
||||
${c.isBanned ? `⛔ ${t('status_banned')}` : `🟢 ${t('status_char_active')}`}
|
||||
</span>
|
||||
<button class="btn sm ${c.isBanned ? 'success' : 'danger'} ban-toggle-btn" data-id="${c.id}" data-banned="${c.isBanned ? '1' : '0'}">
|
||||
${c.isBanned ? t('unban_char') : t('ban_char')}
|
||||
</button>
|
||||
<div style="display:flex;gap:6px;align-items:center">
|
||||
<button class="btn sm ghost edit-char-btn" data-id="${c.id}">${t('edit_char')}</button>
|
||||
<button class="btn sm ${c.isBanned ? 'success' : 'danger'} ban-toggle-btn" data-id="${c.id}" data-banned="${c.isBanned ? '1' : '0'}">
|
||||
${c.isBanned ? t('unban_char') : t('ban_char')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('') : `<div class="empty">Keine Charaktere gefunden.</div>`}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} 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;
|
||||
|
||||
@@ -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)}
|
||||
@@ -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);
|
||||
|
||||
@@ -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; }
|
||||
|
||||
+54
-20
@@ -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() };
|
||||
|
||||
+68
-6
@@ -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);
|
||||
|
||||
+3
-2
@@ -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(', ');
|
||||
|
||||
+50
-12
@@ -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();
|
||||
Reference in new issue
Block a user