Commit Graph
19 Commits
Author SHA1 Message Date
MelekiandClaude Opus 5 7305a5a50f OpenAI: Server-Key-Setting, Filter-Fix fuer o-Reihe, ehrlicher Modell-Refresh
Der Modell-Refresh war fuer OpenAI faktisch ein No-Op: der Key wurde nur aus
der api_keys-Tabelle geholt, und ohne Key blieb die alte Liste im Speicher
stehen und wurde direkt wieder in models_cache.json geschrieben - waehrend der
Endpoint pauschal Erfolg meldete.

- ServerSettingsService: neues Setting OpenAiApiKey (OpenAI war der einzige
  Provider ohne Server-Key, analog Gemini/MiniMax/z.ai)
- OpenAiService: ResolveOpenAiKey() (Setting -> api_keys), HasServerOpenAiKey(),
  ResolveProviderConfig zieht den Setting-Key auch im Chat
- OpenAiService: IsOpenAiChatModel() erfasst die o-Reihe inkl. bare IDs
  (o1, o3, kuenftig o5) - StartsWith("o3-") hat die verschluckt
- RefreshModelsFromApis() liefert ProviderRefreshResult[] pro Provider;
  ModelsEndpoint gibt providers[] zurueck, agent-page.js meldet uebersprungene
  Provider als Fehler-Toast statt pauschalem Erfolg
- ChatEndpoint/TelegramService/CronjobService: OpenAI ohne Agent-Key faellt auf
  den Server-Key zurueck statt hart abzubrechen
- ARCHITECTURE.md nachgezogen

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-15 11:55:22 +02:00
MelekiandClaude Opus 4.8 e6770bb5f8 Fix shared-bot Telegram agent resolution and add effort badge
- TelegramService: build the chat context with the session owner instead
  of the bot owner, so a public/shared bot resolves the agent for foreign
  sessions; credentials/CLI permission stay with the bot owner.
- Agent cards: render an effort badge next to the model badge when an
  agent has an explicit reasoning effort set.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 12:56:42 +02:00
MelekiandClaude Opus 4.8 e395927a67 Send cronjob result and notify-agent reaction to Telegram
The cronjob notification ran the notify-agent on the result summary and
sent only its reaction to Telegram. When the agent merely acknowledged the
summary (e.g. "👍"), the actual cronjob result never reached Telegram —
the user got a header plus an emoji and no information.

Send the real result as the guaranteed first Telegram message, then run
the notify-agent best-effort and send its reaction as a separate second
message. The agent run is wrapped in try/catch with a canRunNotifyAgent
guard instead of the old return-aborts, so a missing key / OpenAI without
key / unavailable CLI only skips the reaction — the result is already
delivered. The notify-agent still persists its reaction to the web history
automatically (ChatNonStreaming / ChatNonStreamingViaCli).

TelegramService.SendNotification now uses SendLongMessage so long results
are chunked into 4096-char messages instead of being rejected whole.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 20:45:00 +02:00
MelekiandClaude Opus 4.8 e3f89043c1 Fix cronjob/telegram fallback for keyless server-key providers
Cronjobs and Telegram bots threw a hard error when an agent had no
assigned user API key, even for providers (nvidia/gemini/minimax/
pollinations) whose server-side key ChatEndpoint resolves automatically
via ResolveProviderConfig. The guard blocked every non-empty provider
instead of only "openai", so e.g. the nvidia agent failed on "Jetzt
ausführen" although the normal chat worked.

Mirror ChatEndpoint's three-way handling at all three sites
(ExecuteCronjob, SendCronjobNotification, TelegramService.HandleMessage):
- Anthropic (empty provider): Claude CLI fallback when permitted/available
- "openai": hard error (no server key, no CLI equivalent)
- other providers: pass through with empty token; server key resolved later

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 13:25:05 +02:00
MelekiandClaude Opus 4.7 271902f32d feat(telegram): CLI-Fallback bei fehlendem API-Key (analog Web-UI)
Wenn ein Telegram-Bot eine Nachricht empfängt und für den Agent kein
API-Key zugewiesen ist, fiel der Bot bisher hart aus ("Kein API-Key
für diesen Agent zugewiesen"). Im Web-UI wird in dem Fall bereits auf
Claude-CLI zurückgefallen – das macht der Telegram-Pfad jetzt analog.

- AnthropicService.Cli: Neue Methode ChatNonStreamingViaCli(...) für
  Non-SSE-Caller (Telegram). Macht dasselbe wie StreamChatViaCli aber
  ohne SSE: System-Prompt + Auto-Context, History-Kontext-Block, letzte
  User-Message (inkl. Image/PDF-Refs), Text + tool_use + tool_result in
  DB persistieren, finalen Text zurückgeben + FinalizeChain mit echten
  Token-Counts vom CLI-Result.
- TelegramService: Bei userApiKey == null jetzt CanUseCli, IsAdmin und
  IsCliAvailable prüfen. Bei OpenAI-Providern bleibt der Hard-Fail
  (kein CLI-Äquivalent). Spezifische Fehlermeldungen pro Szenario.
  Zusätzlich Schutz gegen leere Antwort.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 20:44:36 +02:00
MelekiandClaude Opus 4.7 ecddbe5f36 fix(openai): ask_user_choice-Intercept, Interleaved Thinking in History, MiniMax-Debug-Log
OpenAI-kompatible Provider (MiniMax, DeepSeek-R1, QwQ, Kimi K2, etc.) verloren bei
jeder neuen Iteration ihre eigene Chain-of-Thought, weil thinking-Messages aus der
DB-History rausgefiltert wurden. Folge: Modell kündigt Action an, ruft Tool aber
nicht auf → Stream endet mit finish_reason:stop ohne Tool-Call. Zusätzlich fehlte
der ask_user_choice-Intercept (Tool wurde als unbekannt abgelehnt) und es gab keine
Diagnose-Möglichkeit für unerwartete Stop-Verhalten.

- ChatService.BuildHistoryFromDb(includeThinking): neuer Parameter, fügt
  thinking-Messages als {type:"thinking"}-Block in die Assistant-Message ein.
  Text/Tool-Use derselben Iteration werden via AppendToLastMessage angehängt
  → ein Assistant-Block enthält [thinking, text, tool_use…].
- OpenAiService.ConvertMessage + StreamChat + ChatNonStreaming: Thinking als
  <think>...</think>-Prefix dem Assistant-Content voranstellen (Per-Iteration und
  beim DB-History-Aufbau). Konvention von MiniMax-Docs, wird auch von DeepSeek-R1,
  QwQ, Kimi K2 verstanden.
- ChatEndpoint, SessionEndpoint, CronjobService, TelegramService, ToolService:
  includeThinking je nach Provider durchgereicht. Anthropic-Pfad bleibt aus
  (lehnt thinking-Blöcke ohne Signature ab).
- OpenAiService: ask_user_choice-Intercept im Streaming-Pfad (analog
  AnthropicService.Streaming) – Tool nicht ausführen, SSE user_choice rausschicken,
  mit stopReason awaiting_user_choice finalisieren und return.
- OpenAiService: MiniMax-SSE-Debug-Log in data/openai-debug/ (JSONL: Header +
  Roh-data-Zeilen + Summary mit promptTokens/completionTokens/finishReason/
  toolCalls/duration) – nur für provider=="minimax", nicht-blockierend.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-14 10:19:06 +02:00
Meleki 02f5fe2faf Provider-Abstraktion: Agents unterstützen jetzt OpenAI + Anthropic
Backend:
- ChatEndpoint: Globaler OpenAI-Fallback entfernt, Key-Check pro Provider
- TelegramService/CronjobService: Provider-Weiche statt hardcoded Anthropic
- AnthropicService: Preparer/Review/Finalizer sind Provider-aware
- OpenAiService: Neue ChatNonStreaming()-Methode für agentic loop
- ToolService: send_to_session lädt Key des Ziel-Agents
- SubAgentContext: Provider-Feld hinzugefügt
- ChatService: BuildSubAgentContext setzt Provider

Frontend:
- Key-Switch-Modal: 'Kein Key'-Option zum Entfernen der Zuweisung
- ApiKeysEndpoint: keyId='none' löscht Key-Zuweisung
2026-03-14 22:59:33 +01:00
Meleki 1effc6d00f feat: API Key pro Agent statt pro User
- Neue Tabelle agent_api_keys (user_id, agent_id, key_id)
- Migration: bestehende selected_api_key_id auf alle Agents verteilt
- Backend: GetAgentApiKeyRecord(userId, agentId) in Chat, Telegram, Cronjobs
- Endpoints: select/selected mit ?agentId Query-Parameter
- Frontend: currentAgentId aus Session, alle Key-Calls agent-aware
- DeleteApiKey bereinigt agent_api_keys statt users.selected_api_key_id
2026-03-14 21:41:27 +01:00
Meleki 122000487c Refactor: Server-Settings von appsettings.json in DB-Tabelle (server_settings)
- Neuer ServerSettingsService: zentrale Settings in SQLite mit In-Memory-Cache
- Auto-Migration: bestehende appsettings.Production.json wird einmalig in DB übernommen
- Alle Services umgestellt: IConfiguration → ServerSettingsService (dynamisch, kein Neustart)
- Port bleibt als einziges Setting in appsettings.Production.json (erfordert Neustart)
- ServerSettingsEndpoint: liest/schreibt DB statt JSON-Datei, Port als Sonder-Setting
- IConfiguration komplett entfernt aus allen Services (ChatService, ToolService, AnthropicService,
  OpenAiService, KreaService, TelegramService, KeyScannerService, GitHubEventScannerService)
- AuthMiddleware: KreaApiKey dynamisch aus DB
- appsettings.json bereinigt: nur noch Port und Logging
- Dokumentation aktualisiert (ARCHITECTURE.md, ARCHITECTURE_QUICK.md, README.md)
2026-03-14 13:06:44 +01:00
Meleki dde0fede7d User-spezifische API-Key-Auswahl, globales is_active entfernt
Backend:
- is_active komplett entfernt, durch is_public (Admin-Toggle) ersetzt
- Neues selected_api_key_id auf users-Tabelle
- AnthropicService: globaler _token entfernt, apiToken pro Request
- Token-Durchreichung: StreamChat → ProcessStream → RunAgentChat →
  RunPreparer/RunReview/RunFinalizer, ExecuteTool, send_to_session
- ChatEndpoint: User-Key aus DB laden, an StreamChat übergeben
- TelegramService: Key per bot.UserId auflösen
- CronjobService: Key per job.UserId auflösen
- Neue Endpoints: GET /api/api-keys/available, PUT /api/api-keys/select/{keyId},
  GET /api/api-keys/selected, PUT /api/admin/api-keys/{keyId}/public,
  POST /api/admin/api-keys/check-all
- Program.cs: AnthropicService ohne Token-Parameter

Frontend:
- API-Keys-Page: Public-Toggle (Globe/Lock) statt Activate/Deactivate
- Alle prüfen Button für Batch-Key-Check
- Chat: Key-Auswahl für alle User (nicht nur Admin)
- Dummy-Badge wenn kein Key ausgewählt
- Fallback-Badge bei Key ohne Usage-Daten
- Key-Switch-Modal: apiGetAvailableKeys + apiSelectApiKey
2026-03-13 12:27:03 +01:00
Meleki 47d6f44e07 Auto-Reminder alle 30 Messages + History-Limit 120
- SystemPromptBuilder.BuildReminder(): generiert automatisch Reminder-Text
  aus den aktiven Prompt-Blöcken (Identity, Workspace, Memory, etc.)
- Alle ~30 Messages wird ein [System Reminder]-Paar in die History injiziert
  (nur nach assistant-Messages, um user/assistant-Alternierung zu wahren)
- History auf maximal 120 Messages begrenzt (älteste werden entfernt)
- ChatContext um PromptBlocks-Property erweitert
- Alle Aufrufer (ChatEndpoint, TelegramService, CronjobService) übergeben
  promptBlocks an BuildHistoryFromDb
2026-03-09 06:35:35 +01:00
Meleki 4f847bd33d Telegram: Auto-Link bei /start und normalen Nachrichten
Wenn eine Telegram-Nachricht von einem nicht verknüpften Chat eingeht:
- Sucht nach Sessions mit diesem Bot, die noch keine Chat-ID haben
- Genau 1 unverknüpfte Session → automatisch zuweisen + Bestätigung
- 0 oder mehrere → Chat-ID anzeigen, manuell im Web-UI zuweisen

Neue DB-Methode: FindUnlinkedSessionsForBot(botId)
2026-03-08 23:00:13 +01:00
Meleki ec73ccd71e Telegram Bots als eigenständige Entität mit eigener Page
- Neue Tabelle 'telegram_bots' (bot_id, name, bot_token, webhook_secret, is_public)
- Automatische Migration bestehender Session-Telegram-Configs in telegram_bots
- Sessions verweisen via telegram_bot_id auf Bot (mehrere Sessions pro Bot möglich)
- Webhook-URL: /api/telegram/webhook/{botId} statt {sessionId}
- Eigene Telegram-Bot-Page (wie Agent/Cronjob/Session) statt Modal
- Bot-Page: Name, Token, Secret, Webhook-Verwaltung (registrieren/status/entfernen), Löschen
- Dashboard: Telegram Bots Section mit Cards (Name, maskierter Token, Session-Count)
- Session-Page: Bot-Picker (wie Agent-Picker) statt Token-Input, Chat-ID readonly + Unlink-Button
- Public-Flag: Bot kann von anderen Usern in ihren Sessions ausgewählt werden
- Vereinfacht: 1 Session = max. 1 Telegram Chat, allowed_chat_ids entfällt
- /start zeigt Chat-ID an, /unlink entfernt (Unlink nur über Web-UI)
- Nachrichten-Routing: Bot + Chat-ID → Session Lookup
2026-03-08 19:27:05 +01:00
Meleki 011b26c37f feat(telegram): Zugriffskontrolle mit Chat-ID-Whitelist
- TelegramService: IsChatIdAllowed() prüft Owner + Whitelist
- /start von unbekannter ChatId: Zugriff verweigert + ChatId angezeigt
- Owner wird bei Zugriffsanfrage benachrichtigt (Username + ChatId)
- Alle Commands/Messages prüfen Whitelist vor Verarbeitung
- Neues Feld telegram_allowed_chat_ids in sessions-Tabelle
- Frontend: Input für erlaubte Chat-IDs in Session-Telegram-Settings
- API: allowedChatIds in Save/Get durchgereicht
2026-03-06 13:04:02 +01:00
Meleki b645625b56 Cronjobs + AnthropicService Singleton Refactoring
Cronjobs:
- CronjobService (BackgroundService) prüft jede Minute auf fällige Jobs
- Cron-Expression in Server-Lokalzeit via Cronos (CronFormat.Standard)
- Cronjob-Ausführung: Prompt → Session → Agent-Antwort in Chat-History
- Optionale Benachrichtigungs-Session (notify_session_id): Zusammenfassung
  wird in separate Session geschrieben (z.B. mit Telegram)
- Telegram-Benachrichtigung mit Cronjob-Name + Ursprungs-Session
- REST API: CRUD + toggle + manuelles Ausführen (/run)
- Frontend: Dashboard-Cards, Cronjob-Formular mit Cron-Vorschau,
  Session-Dropdown, Notify-Session-Dropdown, Status-Box

Refactoring:
- AnthropicService als Singleton in DI registriert
- ChatEndpoint + TelegramService nutzen injizierte Instanz
- Redundante Dependencies (Token, ToolService, MemoryService) entfernt

Neue Dateien:
- Models/CronjobRecord.cs
- Services/CronjobService.cs
- Endpoints/CronjobEndpoint.cs
- wwwroot/js/pages/cronjob-page.js
- PLAN-Cronjob.md
2026-03-03 22:44:46 +01:00
Meleki 0120bb8f73 Telegram: Bot=Session statt User-Level, Chat-Code-Refactoring
- Telegram-Config (Bot-Token, Webhook-Secret, ChatId) von User-Settings
  in sessions-Tabelle verschoben → jede Session hat ihren eigenen Bot
- Link-Code-System komplett entfernt (TelegramLinkRecord gelöscht)
- /start verknüpft automatisch, kein /link mehr nötig
- Alle Endpoints session-basiert: /api/sessions/{id}/telegram/*
- Webhook-URL pro Session: /api/telegram/webhook/{sessionId}

Refactoring: Doppelten Chat-Code eliminiert
- Neuer ChatService: PrepareContext, BuildHistoryFromDb, ResolveModelId
- Neues ChatContext-Model als gemeinsame Datenstruktur
- AnthropicService.ChatNonStreaming() für Telegram (statt eigenem Loop)
- TelegramService um ~180 Zeilen reduziert, kein eigener Claude-Loop mehr
- ChatEndpoint nutzt ChatService.PrepareContext() statt eigener Setup-Logik
- Model-Mapping nur noch an einer Stelle (3x → 1x)

Frontend
- Telegram-Section von Settings-Page in Session-Bearbeitungsseite verschoben
- Webhook-Secret readonly, wird einmalig generiert und persistent gespeichert
- Status wird automatisch geladen, Register/Delete je nach Webhook-Status
- Toast-Notification-System (showToast) in ui.js
- Link-Code-Modal und Telegram-Menüpunkt im Dashboard entfernt
- Telegram-Badge auf Session-Cards (konfiguriert/verbunden)

Bugfix: Bearer statt x-api-key für OAuth-Tokens im TelegramService
2026-03-03 21:46:59 +01:00
Meleki 4fa0111c33 feat: Erweiterte Model-Auswahl für Agents
- Model-Optionen: sonnet-4-5, sonnet-4-6, opus-4-5, opus-4-6, haiku-4-5
- ChatEndpoint + TelegramService: Model-Mapping für alle Varianten
- Agent-Formular: Dropdown mit allen Model-Versionen
- ui.js: prettyModelName() vereinfacht für neue Model-Werte
2026-03-03 09:22:47 +01:00
Meleki 4ac042e512 Telegram: Webhook-Verwaltung in Einstellungen-Seite
- Backend: DELETE /api/telegram/webhook Endpoint + TelegramService.DeleteWebhook()
- api.js: apiTelegramWebhookInfo(), apiTelegramRegisterWebhook(), apiTelegramDeleteWebhook()
- Settings-Page: Neue 'Telegram Bot' Section (nur für Admins, nur wenn konfiguriert)
  - Status abrufen: Webhook-URL, ausstehende Updates, letzter Fehler, Aktiv-Badge
  - Webhook registrieren: prompt() für Base-URL, POST an Telegram API
  - Webhook entfernen: Bestätigungsdialog + DELETE
- CSS: .telegram-status-box, .tg-status-row, .tg-label, .tg-value, .tg-badge
2026-03-03 09:06:22 +01:00
Meleki 0dd7c38751 feat: Telegram Bot Integration
- TelegramService: Non-Streaming Claude Chat mit Tool-Loop,
  Commands (/start, /link, /session, /new, /clear, /status, /unlink),
  Nachrichten-Splitting bei >4096 Zeichen, Typing-Indicator,
  History-Aufbau aus DB, Token-Usage-Tracking
- TelegramEndpoint: Webhook (POST, no-auth), Link-Code-Generierung
  (POST, auth), Webhook-Registrierung + Info (Admin)
- DatabaseService: telegram_links Tabelle mit Link-Code-Flow
  (6-stelliger Code, 5 Min Ablauf), GetUserSessions
- AuthMiddleware: /api/telegram/webhook von Auth ausgenommen
- Session-Verknüpfung via Link-Code (Web-UI generiert Code,
  Telegram /link CODE löst ein)
- TelegramLinkRecord Model
2026-03-03 06:30:05 +01:00