Commit Graph
54 Commits
Author SHA1 Message Date
MelekiandClaude Opus 4.8 aa0b8ee493 Add proposer role prompt to panel members
Panel members run read-only (PlanMode / tool-less) but kept their normal
agent prompt, so they repeatedly attempted write/execute/git actions that
the read-only filter blocks — getting stuck in failing tool loops and
wasting tokens. Append an explicit proposer role clarification to each
member's system prompt so they go straight to analysis + text proposal
and leave the actual writing/committing to the synthesizer agent.

- ChatService: PanelMemberRolePrompt constant (read-only, propose-only)
- PrepareContext: append the role prompt to each panel member's SystemPrompt
- Covers all three provider paths (Anthropic direct, CLI/OpenAI via
  ExtractSystemPromptText)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 14:52:40 +02:00
MelekiandClaude Opus 4.8 b7ff928340 Add Mixture-of-Agents (MoA) mode on top of Fusion
Extend the panel engine with a layer loop: Fusion is one proposer round,
MoA runs N rounds where each round after the first sees the previous
round's responses via <previous_layer_responses> and refines its answer.
Only the final round is persisted; intermediate rounds are live-only.
Rounds are clamped to 1-5.

- SessionRecord + migration: moa_layers column (default 2)
- RunPanel: layer loop with per-member cloned message injection
- CloneForMember / BuildPreviousLayerBlock helpers for member isolation
- SSE: panel_layer_start / panel_layer_done events
- Frontend: layer_index composite keying, round dividers, MoA option
- Docs: ARCHITECTURE + ARCHITECTURE_QUICK updated

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 13:46:28 +02:00
MelekiandClaude Opus 4.8 268f11fa6d Add multi-model panel with Fusion mode
Panel agents answer the user prompt in parallel (read-only, non-streaming);
their responses are merged into the worker's last user message as a
<panel_responses> block, and the session agent synthesizes one final
streamed answer. The RunPanel engine is built layer-ready for future MoA.

- New session fields: multi_model_mode (off/fusion), panel_agent_ids (CSV)
  with idempotent column migration
- New partial Services/AnthropicService.Panel.cs holding the RunPanel engine
- Provider-agnostic members: Anthropic RunNonStreamingToolLoop / OpenAI
  CompleteText / CLI plan-mode; all forced read-only, persisted with Tag=panel
- SSE events: panel_start, panel_member_start, panel_member_done, panel_done
- Frontend: multi-agent picker, live panel bubbles, history rendering
- Graceful degradation: panel errors fall back to worker-only

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 12:55:06 +02:00
MelekiandClaude Fable 5 4e41401f23 Add Claude Fable 5 model option
Adds the new claude-fable-5 model (released 2026-06-09) as a selectable
model alongside the existing Claude models:

- ChatService.ResolveModelId: map "fable" and "fable-5" to claude-fable-5
- index.html: fable-5 option in the model dropdown (after opus-4-8)
- ARCHITECTURE.md: model list + resolution table updated

Default stays opus-4-8. The invite-only sibling Mythos 5 is intentionally
not included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 06:53:42 +02:00
MelekiandClaude Opus 4.8 f2fd493e5f Add live steering injection into running chains
Let the user inject a message into a running chain instead of only being
able to abort it. While a chain streams, typing + Enter sends the text to
a new /api/chat/steer endpoint; it is drained at the next iteration
boundary, wrapped with a hint so the model actively classifies it
("complements the task -> keep working" vs. "changes course -> adjust"),
and stored as a Type="steer" user message so it survives reload.

Shared infrastructure (provider-agnostic):
- SteeringQueue: out-of-band queue keyed by sessionId, mirrored from
  StreamingTracker (Enqueue/Drain/Clear).
- Program.cs registers it as a singleton and passes it to AnthropicService.
- ChatEndpoint: POST /api/chat/steer enqueues only while IsStreaming,
  Clear() in the finally.
- ChatService.BuildHistoryFromDb groups Type="steer" so no two
  consecutive user turns are produced on re-chat.
- Frontend api.js/chat.js/bubbles.js/history.js + chat.css render the
  optimistic steer bubble and the steer_injected SSE event; Enter during
  a stream sends a steer instead of being blocked.

Anthropic API path:
- Drain point B (tool boundary, merged into the tool_result user turn)
  and C (turn end -> inject + continue instead of finalize).

Claude CLI path (kill-and-restart):
- The agentic loop runs inside the claude child, so true mid-turn inject
  is impossible. On a pending steer the child is killed at the next tool
  boundary, progress is rebuilt from the DB as a <work_in_progress>
  transcript, and the CLI is restarted with the steer appended.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-02 06:49:58 +02:00
MelekiandClaude Opus 4.8 a58f279eaa Add effort badge to chain summary
Snapshot the agent's effort onto the chain (like model) so it survives
reload, archive and shared chains, then show it in the chain-end meta line.

- ChainRecord.Effort + chains.effort column (TryAddColumn migration).
- CreateChain INSERT carries the value.
- ChatService snapshots agent.Effort at chain creation, but only for Claude
  models – OpenAI providers store '' so there is no misleading badge.
- Anthropic streaming + CLI done-events include effort for the live path.
- chat.js buildMetaBadges renders "Effort: <level>" after the model badge,
  only when a value is set.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-05-31 22:08:44 +02:00
MelekiandClaude Opus 4.7 3f913f14b5 Add per-agent reasoning effort
Opus 4.5+ and Sonnet 4.6+ support a new "effort" knob that controls how
much budget the model spends on thinking and tool calls. Plumb it through
end to end so each agent can pick its own level.

Storage & shape:
- New TEXT column agents.effort (default '') added via TryAddColumn.
- AgentRecord.Effort + INSERT/UPDATE in DatabaseService.Agents.cs.
- ChatContext.Effort + SubAgentContext.Effort so the value travels with the
  request alongside model and tool settings.

Agent editor:
- Effort dropdown above git-commit behavior in the agent form (low/medium/
  high/xhigh/max plus empty = "use default"). Always visible; on OpenAI
  providers the value is sent but silently ignored.
- agent-page.js load/save and AgentEndpoint create/update wired up.

Anthropic API path:
- StreamChat and RunNonStreamingToolLoop add output_config: { effort } when
  effort is set and not "high" – empty/null/"high" means "omit and let the
  API pick its default".
- Sub-agents (preparer/review/finalizer) get the parameter through
  RunAgentChat so each step uses its own agent's effort.

Anthropic CLI path:
- ClaudeCliService.ChatStreamingAsync takes an effort parameter and exports
  CLAUDE_CODE_EFFORT_LEVEL on the spawned process. Env-var beats the
  --effort flag because it also covers "max" and "ultracode".
- StreamChatViaCli, ChatNonStreamingViaCli, RunSubAgentViaCli, and the
  ChatEndpoint anthropic branches all hand the value through.

ARCHITECTURE.md / ARCHITECTURE_QUICK.md updated with the new field.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 21:33:32 +02:00
MelekiandClaude Opus 4.7 88fb3c9867 Add Opus 4.8 model
New Anthropic flagship released 30 May 2026. Adds the dropdown entry as
the new default for fresh agents, maps "opus-4-8" -> "claude-opus-4-8" in
ResolveModelId, and bumps the "opus" alias from 4.7 to 4.8 so the family
shortcut tracks the latest release.

ARCHITECTURE.md updated to list opus-4-8 in both the field reference and the
model-resolution block.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 21:26:13 +02:00
MelekiandClaude Opus 4.7 112fd70f3b Remove obsolete [1m] model variants
Since March 2026 the 1M-token context window is the default for Opus 4.6/4.7
and Sonnet 4.6 – no separate variant or beta header needed. The "[1m]" suffix
on model IDs is dead code now and would even produce HTTP 400 against the
current API.

Cleanup:
- Drop 3 [1m] options from the agent model dropdown; default selection moves
  from opus-4-7[1m] to opus-4-7.
- Drop 5 [1m] mappings from ResolveModelId and add a defensive Replace as a
  safety net for any agent record still holding an old value.
- One-shot startup migration on agents.model + chains.model strips the suffix
  so existing chains can be re-chatted without errors.
- ARCHITECTURE.md reflects the slimmed list and explains why 1M is now default.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 21:25:35 +02:00
MelekiandClaude Opus 4.6 1fe04025d3 fix(openai): Auto-Context, Tool-Result-Matching, Payload-Preview, leere Bubbles
- Auto-Context (Embedding-Suche) für OpenAI-Provider aktiviert: BuildAutoContextAsync
  auf internal static refactored und in StreamChat + ChatNonStreaming integriert
- Tool-Results mit Role="tool" (OpenAI-Konvention) werden in BuildHistoryFromDb
  jetzt korrekt erkannt (vorher nur Role="user"/Anthropic)
- Payload-Preview zeigt für OpenAI-Provider echtes API-Format (function-Wrapper,
  tool_choice:"auto", max_tokens, stream_options, extra_body)
- Tool-Input (Argumente) wird im SSE tool_end-Event mitgesendet (fehlte im OpenAI-Pfad)
- Leere Bubbles durch Whitespace-only Text nach </think>-Extraktion behoben
  (Trim in DB-Save, BuildHistoryFromDb und Frontend-Guard)
- History-Toggle-Bug: var→const in for-Loop (Block-Scoping für Closures),
  tool_result-Matching per data-tool-call-id statt blindes letztes Element
- Non-Streaming max_tokens für MiniMax auf 32768 + extra_body.reasoning_split

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-14 11:16:40 +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
MelekiandClaude Opus 4.6 e7b663c82f feat: Opus 4.7 + 1M-Context-Varianten und neue Krea-Bildmodelle
- Claude Opus 4.7 als neues Default-Modell, 1M-Context-Varianten für Sonnet/Opus
- 5 neue Krea-Bildmodelle (z-image, qwen-2512, nano-banana-2, seedream-5-lite, seededit)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-25 16:39:41 +02:00
MelekiandClaude Opus 4.6 53cee67bef feat: Remote-Execute für Linux/Bash – OS-basierte Tool-Descriptions und remote.sh Script
Remote-Verbindungen erkennen jetzt das OS des Clients und passen die Tool-Description
dynamisch an (PowerShell für Windows, Bash für Linux). Neues remote.sh Script für
Linux/macOS-Clients mit embedded Python WebSocket-Client.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-16 09:31:56 +02:00
MelekiandClaude Opus 4.6 9391b5a6fa fix: Verwaiste tool_result-Blöcke aus History entfernen (API 400)
Wenn eine ältere ask_user_choice-Chain als Text-only geladen wird,
geht der tool_use verloren, aber das tool_result in der nächsten Chain
bleibt – Anthropic API antwortet mit 400 "unexpected tool_use_id".
Neue FixOrphanedToolResults()-Funktion entfernt diese verwaisten Blöcke.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-24 16:52:31 +01:00
MelekiandClaude Opus 4.6 3e19da4d48 refactor: Backend-Deduplizierung – Parameter-Objekte, Shared Helpers, KeyCheckDispatcher
- ToolDefinitionOptions + ToolExecutionContext ersetzen lange Parameterlisten in ToolService
- AppendToLastMessage-Helper in ChatService eliminiert 5x duplizierte Logik
- OpenAiService: ResolveProviderConfig + BuildApiMessages + ConvertToOpenAiTools statt doppeltem Code
- Tool-Definitionen aus einer Quelle (Anthropic→OpenAI Konvertierung statt hardcodierter Liste)
- KeyCheckDispatcher zentralisiert Key-Check-Dispatch (ApiKeysEndpoint, KeyScanner, GitHubEventScanner)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 08:01:49 +01:00
Meleki e31d6cfb4d MaxHistory Default von 120 auf 220 erhöht 2026-03-15 11:20:33 +01:00
Meleki 49ef6bedc6 feat: Payload-Preview im Chat-Menü + Reminder von hinten gezählt
- Neuer Endpoint GET /api/sessions/{id}/payload-preview
  Gibt den exakten Anthropic-API-Payload als JSON zurück (read-only)
- Chat-Menü: 'Payload anzeigen' öffnet Modal mit formatiertem JSON
- Reminder-Logik umgebaut: halbes Intervall (15) vor Ende,
  dann volle Intervalle (30) rückwärts statt von vorne gezählt
- CSS: Payload-Modal Styling, kleine Variable-Fixes
2026-03-15 10:46:51 +01: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 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 192f41e91e feat: Serper Web Search als Agent-Tool
- ToolService: serper_web_search Tool-Definition + ExecuteSerperWebSearch()
  Google-Suche via Serper.dev API mit Titel, Link, Snippet
  Knowledge Graph + Answer Box + organische Ergebnisse
- AgentRecord: UseSerperSearch Property (Default: false)
- DB-Migration: use_serper_search Spalte
- AnthropicService + ChatService: useSerperSearch Parameter durchreichen
- ChatEndpoint + AgentEndpoint: useSerperSearch in API
- Frontend: Checkbox, Badge (Serper Search), laden/speichern
- Aktivierung: Agent-Checkbox + SerperApiKey in Server-Einstellungen
2026-03-13 09:41:56 +01:00
Meleki 89122e2170 feat: GitHub Code Search als Agent-Tool + Dashboard-Badges
- UseGitHubSearch Property im AgentRecord (Default: false)
- DB-Migration: use_github_search Spalte in agents
- Checkbox im Agent-Formular (Standard: unchecked)
- Tool nur aktiv wenn Agent-Checkbox UND GitHubToken konfiguriert
- includeGitHubSearch Parameter durch StreamChat/AddToolsToPayload
- Dashboard-Badges: 🔮 Auto-Kontext + 🐙 GitHub Search
2026-03-13 08:26:15 +01:00
Meleki bca5e5145a Add github_code_search tool + scanned key type field
- New tool: github_code_search (GitHub Code Search API with text-match fragments)
- Tool available when GitHubToken is configured in server settings
- Registered in AnthropicService + ChatService tool pipelines
- ToolService: SetHttpClientFactory() pattern for lazy DI resolution
- ScannedKeyRecord: type field (anthropic_oauth, anthropic_api, anthropic_unknown, unknown)
- DetectKeyType() based on key prefix
- DB migration: type column with default 'anthropic_oauth'
- Frontend: type label in scanned keys list
2026-03-13 08:12:55 +01:00
Meleki db1a7c7f64 Refactoring + Dokumentation: api.js komprimiert (745→267 Zeilen), SseHelper extrahiert, DatabaseService in Partial Classes aufgeteilt, unbenutztes CSS entfernt, ARCHITECTURE.md/ARCHITECTURE_QUICK.md/README.md aktualisiert (neue Features: Embedding, Remote, API-Keys, 16 Tools) 2026-03-12 13:29:19 +01:00
Meleki 145441fa7b feat: Gemini thought_signature korrekt lesen und zurücksenden
- thought_signature aus delta.tool_calls[n].extra_content.google.thought_signature lesen (korrekter Pfad)
- ThoughtSignature-Feld in MessageRecord + DB-Migration (ALTER TABLE messages ADD COLUMN thought_signature)
- SaveMessage speichert ThoughtSignature pro Tool-Call
- OpenAiService: toolCallAccumulators Tuple um ThoughtSignature erweitert
- Tool-Calls mit thought_signature werden mit extra_content.google.thought_signature zurückgesendet (nicht function.thought_signature)
- ConvertMessage (History-Rebuild) setzt thought_signature ebenfalls korrekt
- ChatService.BuildApiMessages übergibt thought_signature aus DB-Record
- Gemini-Modelle dynamisch laden statt hardcodiert
- Tool-Call-Akkumulator nutzt id als primären Key (Gemini sendet parallele Calls ohne index)
- content=null → content='' für Gemini-Kompatibilität
2026-03-12 06:34:11 +01:00
Meleki 7972ca6a3a feat: OpenAI-kompatibler Provider (Nvidia/g4f.space) mit Tool-Calling und SSE-Streaming
- OpenAiService.cs: Neuer Service für OpenAI-kompatible APIs
  - SSE-Streaming mit text_start/text_delta/text_end Events
  - Tool-Calling: list_files, read_file, write_file, edit_file, delete_file, execute
  - Agentic Loop (max 10 Iterationen)
  - Tool-Use + Tool-Result in DB gespeichert
  - History-Rebuild: Anthropic-Format → OpenAI-Format (tool_use/tool_result korrekt konvertiert)
- ChatContext.cs: Provider-Feld hinzugefügt
- ChatService.cs: OpenAI-Provider-Erkennung in ResolveModelId + PrepareContext
- ChatEndpoint.cs: Provider-Dispatch (nvidia → OpenAiService, sonst → AnthropicService)
- Program.cs: OpenAiService als Singleton registriert
- wwwroot/index.html: nvidia:moonshotai/kimi-k2.5 in Modell-Auswahl
2026-03-11 16:15:09 +01:00
Meleki e374c70c89 fix: send_to_session für alle ExecuteTool-Pfade + generelle FixOrphanedToolUse
- AnthropicService: db/chatService/anthropicService/userId/telegramService auch im
  RunAgentChat (Zeile 899) und ChatNonStreaming (Zeile 1105) ExecuteTool-Aufruf
  durchreichen – Telegram-Flow nutzt ChatNonStreaming, hatte zuvor null-Parameter
- ChatService: FixOrphanedAskUserChoice → FixOrphanedToolUse ersetzt
  Prüft gesamte History auf orphaned tool_use-Blöcke (nicht nur ask_user_choice am Ende)
  Synthetische tool_results werden eingefügt um Anthropic API 400 zu verhindern
- ToolService: Debug-Logging für send_to_session nach /tmp/gott_send_to_session.log
2026-03-11 13:50:12 +01:00
Meleki bdb7f54c74 fix: synthetisches tool_result bei übergangenem ask_user_choice
Wenn der User Text schreibt statt eine Choice zu wählen, endet die
vorherige Chain mit einem offenen ask_user_choice tool_use ohne
passendes tool_result. Anthropic API wirft dann 400.

FixOrphanedAskUserChoice() erkennt diesen Fall in BuildHistoryFromDb
und fügt ein synthetisches tool_result ein.
2026-03-11 11:26:52 +01:00
Meleki 10da2bd964 feat: Remote-Verbindungen – Windows-Workstations per WebSocket steuern
- RemoteConnectionManager: Singleton-Service verwaltet WebSocket-Verbindungen
  mit Command-Execution (Send/Receive mit Timeout + SemaphoreSlim-Locking)
- RemoteEndpoint: WebSocket-Endpoint /api/remote (auth-frei), REST-APIs für
  Connections/Assign/Unassign, PowerShell-Script-Auslieferung mit dynamischer URL
- remote.ps1: PowerShell-Client für Windows – verbindet per WebSocket,
  sendet Hostname/User/OS, empfängt und führt Befehle aus, Heartbeat
- remote_execute Tool: Neues Agent-Tool, nur verfügbar wenn Session eine
  zugeordnete Remote-Verbindung hat, führt PowerShell-Befehle remote aus
- Frontend: Menüpunkt 'Remote-Verbindungen' im Chat-Dropdown, Modal zeigt
  alle aktiven WebSocket-Verbindungen (Hostname, User, OS, Verbindungszeit),
  Verbinden/Trennen-Buttons pro Verbindung und Session
- Auth: /api/remote und /remote.ps1 von Authentifizierung ausgenommen

Architektur: Windows-Client → WebSocket → GOTT-Server → Agent-Tool
Session-gebunden: Eine Verbindung wird einer Session zugeordnet
2026-03-11 07:04:24 +01:00
Meleki 9f4746c2e7 fix: fullChainStartIndex erkennt awaiting_user_choice der vorherigen Chain
Bug: Nach ask_user_choice wurde die vorherige Chain (mit allen tool_use/
tool_result Paaren) nur als Text geladen statt vollständig. Die API bekam
tool_use IDs ohne zugehörige tool_result Blöcke → 400 Error.

Ursache: Die fullChainStartIndex-Logik prüfte nur ob die AKTUELLE Chain
eine tool_result mit Iteration 999 hat. Aber die Choice-Antwort wird in
die VORHERIGE Chain gespeichert (ChatEndpoint Zeile 68-78), nicht in die
aktuelle. Deshalb wurde needsPrevious=false → vorherige Chain nur als Text.

Fix: Dritte Prüfung hinzugefügt - wenn die vorherige Chain mit
stop_reason='awaiting_user_choice' endete, muss sie vollständig geladen
werden (sie enthält den tool_use UND den tool_result für die Choice).
2026-03-10 22:29:40 +01:00
Meleki 8dd962ac49 fix: CleanOrphanedWebSearchBlocks bidirektional – entfernt auch verwaiste web_search_tool_result ohne server_tool_use
Vorher wurden nur orphaned server_tool_use entfernt (die keinen
web_search_tool_result hatten). Jetzt auch umgekehrt: web_search_tool_result
Blöcke ohne zugehörigen server_tool_use werden entfernt.

Mögliche Ursache für API 400 'web_search_tool_result without corresponding
server_tool_use': Parse-Fehler beim Laden des server_tool_use aus der DB
oder Reihenfolgeprobleme führten dazu, dass nur der Result-Block in der
History landete.
2026-03-10 11:49:08 +01:00
Meleki 3153cb6c6b fix: web_search_tool_result als Raw-JSON speichern für History-Rebuild
Problem: API 400 'web_search tool use without corresponding
web_search_tool_result block' – weil web_search_tool_result nur als
Sources-Array gespeichert wurde und in BuildHistoryFromDb kein Handler
dafür existierte. Der server_tool_use-Block war in der History, aber
der zugehörige web_search_tool_result fehlte.

Backend (AnthropicService):
- 3 Speicher-Stellen (StreamChat, RunAgentChat, ChatNonStreaming):
  Raw-JSON statt ExtractWebSearchSources-Array speichern

Backend (ChatService):
- Neuer Handler für web_search_result in BuildHistoryFromDb:
  Raw-JSON als web_search_tool_result in assistant content einfügen
- Rückwärtskompatibilität: Alte Array-Einträge überspringen
- CleanOrphanedWebSearchBlocks(): Post-Processing entfernt
  orphaned server_tool_use mit name web_search (alte DB-Einträge)

Frontend (history.js, shared-page.js):
- _extractWebSearchSources(): Unterstützt altes Array-Format und
  neues Raw-JSON Format (content[].type === web_search_result)
2026-03-10 11:34:43 +01:00
Meleki dd99216913 fix: SSE-Stream-Stabilität und History-Trimming tool_use/tool_result-Schutz
- Kestrel MinResponseDataRate per-Request deaktivieren für SSE-Streams
  (Default 240 bytes/s + 5s Grace → client_disconnected bei langen Tools)
- SSE-Heartbeat alle 15s während Stream (schützt gegen Browser/Netzwerk-Idle)
- History-Trimming: RemoveRange schneidet nicht mehr in tool_use/tool_result-Paare
- Reminder-Insertion: kein Einfügen zwischen tool_use und tool_result
2026-03-09 20:13:22 +01:00
Meleki 1e7b68fb09 Fix: ask_user_choice Dauerschleife bei mehreren aufeinanderfolgenden Choice-Runden
Bug: Bei 2+ aufeinanderfolgenden ask_user_choice-Runden wurden ältere
Choice-Chains nur als Text geladen. Claude sah die früheren tool_use/
tool_result-Paare nicht → kein Kontext über bereits beantwortete Fragen
→ Agent stellte dieselben Fragen erneut (Dauerschleife).

Fix: fullChainStartIndex-Logik traversiert jetzt rückwärts durch alle
zusammenhängenden Choice-Chains (erkannt an tool_result mit Iteration 999).
Alle werden vollständig geladen, damit die gesamte Frage-Antwort-Historie
für Claude sichtbar bleibt.
2026-03-09 19:44:07 +01:00
Meleki fb9ff23ad4 fix: server_tool_use/result (bash_code_execution) korrekt verarbeiten
- server_tool_use-Blöcke werden jetzt in DB persistiert und in
  History-Rekonstruktion als Raw-JSON eingefügt
- Generische *_tool_result-Behandlung (bash_code_execution_tool_result,
  code_execution_tool_result etc.) in allen drei Chat-Pfaden:
  StreamChat, ChatNonStreaming, RunAgentChat
- ProcessStream: serverToolResultBlocks analog zu webSearchResultBlocks
- BuildHistoryFromDb: server_tool_use + server_tool_result werden
  korrekt in Assistant-Content-Array rekonstruiert
- Behebt API 400: tool_use without corresponding tool_result
2026-03-09 11:52:58 +01:00
Meleki 5d090e160b feat: Windows-Kompatibilität
- WorkspaceHelper: Zentrale Hilfsmethoden (IsWindows, TempDir, IsSubPathOf,
  GetRelativePath, ShellExecutable, ShellArguments)
- ToolService: execute nutzt cmd.exe auf Windows, GetRelativePath mit
  Forward-Slashes, IsSubPathOf für case-insensitive Pfadprüfung
- SessionEndpoint: /tmp → Path.GetTempPath(), bash → cmd.exe,
  Fire-and-forget via .bat statt systemd-run auf Windows
- ChatService: /tmp → WorkspaceHelper.TempDir
- MemoryService: IsSubPathOf + GetRelativePath
- WorkspaceEndpoint: HandleBrowse zeigt Laufwerke auf Windows,
  IsSubPathOf statt StartsWith
- InfoEndpoint: gott.exe auf Windows, isWindows-Flag in API-Response
- Frontend: File-Explorer mit Laufwerks-Navigation auf Windows
2026-03-09 11:35:04 +01:00
Meleki cdad7faad4 fix: tool_end SSE-Event nicht mehr auf 500 Zeichen kürzen + tool_result History-Truncation
- tool_end SSE-Event: 500-Zeichen-Limit entfernt (2 Stellen), damit
  todo_write und andere Tools beim Streaming vollständig angezeigt werden
- BuildHistoryFromDb: TruncateToolResult (20k) auf tool_result-Messages
  angewendet, um Token-Overflow bei History-Rebuild zu verhindern
  (609k Tokens > 200k Limit nach awaiting_user_choice)
- TruncateToolResult/MaxToolResultChars auf internal geändert
- TODO.md: todo_write-Bug als erledigt markiert
2026-03-09 09:40:30 +01:00
Meleki dcedbaa074 refactor: Backend deduplizieren – 13 Dateien, -528 Zeilen netto
ChatContext: 3 identische Context-Klassen (PreparerContext, ReviewContext,
FinalizerContext) zu einer SubAgentContext-Klasse zusammengefasst.

ChatService: 3x40 Zeilen Sub-Agent-Setup durch BuildSubAgentContext() ersetzt.

AnthropicService: 5 Hilfsmethoden extrahiert – ExtractWebSearchSources(),
TruncateToolResult(), AddToolsToPayload(), ParseServerToolUse(), TrackUsage().

WorkspaceEndpoint: 5 Session/Agent-Endpoint-Paare durch generische Core-Handler
mit basePath-Parameter ersetzt. Ungenutzte rmdir-Endpoints entfernt.

AgentEndpoint: Doppeltes Agent-DTO-Mapping durch MapAgentList() ersetzt.

SessionEndpoint: Doppelte Session/Agent-Auflösung durch ResolvePromptContext() ersetzt.

DatabaseService: Toten Code entfernt (SetSessionTelegramChatId,
ClearSessionTelegramChatId, GetSessions, GetUserSessions). ConvertDataUrlToWebP
und ResizeDataUrlToWebP zu einer Methode zusammengefasst.

TelegramEndpoint: Bot-DTO-Mapping durch MapBotResponse() dedupliziert.

KreaEndpoint + SkillEndpoint: Thumbnail-Generierung in ImageService.GenerateThumbnail()
extrahiert, SixLabors-Imports aus Endpoints entfernt.

CronjobEndpoint: 7x ctx.Items[UserId] durch ctx.GetUserId() ersetzt.
2026-03-09 09:18:49 +01:00
Meleki 57560cbbea refactor: MaxHistory + ReminderInterval in appsettings auslagern
- MaxHistory (Default: 120): Max History-Messages pro API-Request
- ReminderInterval (Default: 30): System-Prompt Reminder alle N Messages (0 = deaktiviert)
- Beide Werte über Server-Settings-UI konfigurierbar
- Hardcoded Werte in ChatService durch konfigurierbare Felder ersetzt
2026-03-09 07:03:47 +01:00
Meleki 8357bc66c5 "Understood." übersetzt auf "Verstanden." 2026-03-09 06:50:06 +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 83945689a6 Remove tool_choice agent option - auto-detect based on workspace/skills/memory
- Remove tool_choice from AgentEndpoint (create, update, list responses)
- ChatService: automatically set tool_choice='any' when workspace, memory
  or skills present, null otherwise. Same for preparer/review/finalizer
- SystemPromptBuilder: remove 3 toolAny-conditional prompt blocks
  (KRITISCH, Verhalten, ERINNERUNG)
- Frontend: remove checkbox, badge and JS references
- Agent.ToolChoice DB field preserved for backward compat, no longer read
2026-03-09 05:39:09 +01:00
Meleki bed4b1687e fix: openclaw-import Messages aus LLM-History nicht mehr ausfiltern
Der Tag-Filter in BuildHistoryFromDb filterte alle Messages mit Tag
aus, sofern der Tag nicht dem angeforderten includeTag entsprach.
openclaw-import ist jedoch kein Sub-Agent-Tag (wie preparer/review/
finalizer), sondern ein Herkunfts-Tag und muss immer in der History
enthalten sein.
2026-03-08 20:41:32 +01:00
Meleki 14e721f95b fix(preparer): Logik invertiert - Default=Forward, [QUESTION]=Stopp
Kernproblem: Claude vergisst [FORWARD]-Tag → Preparer leitet nie weiter.

Lösung - Logik umgedreht:
- Jede Antwort wird automatisch an Session-Agent weitergeleitet (Default)
- Nur bei explizitem [QUESTION]-Tag wird gestoppt (Rückfrage an User)
- [FORWARD] wird weiterhin erkannt und entfernt, ist aber optional

Weitere Fixes:
- Preparer bekommt eigene History mit includeTag='preparer',
  damit er den Kontext seiner vorherigen Rückfragen sieht
- Session-Agent bekommt saubere History ohne Sub-Agent-Messages
  (nach Preparer-Phase frisch aus DB geladen)
- [QUESTION] wird im Frontend-Markdown ausgeblendet
2026-03-07 16:35:29 +01:00
Meleki 43d3e9dc26 fix: Tag-Feld für Sub-Agent-Messages – verhindert API 400 bei tool_use ohne tool_result
- MessageRecord: neues Tag-Feld (null=normal, preparer/review/finalizer=Sub-Agent)
- DatabaseService: Migration tag-Spalte, INSERT-Statements erweitert
- AnthropicService: RunAgentChat setzt Tag=agentType bei allen 4 SaveMessage-Aufrufen
- ChatService: BuildHistoryFromDb filtert getaggte Messages aus API-History

Sub-Agent-Messages bleiben in der DB (Frontend-Anzeige), werden aber
nie an die Claude API geschickt – löst das Problem für Preparer,
Review und Finalizer gleichermaßen.
2026-03-07 15:37:28 +01:00
Meleki 494f431963 feat: Vorbereiter-Agent (Preparer) für Sessions
- Neues optionales Session-Feld 'preparerAgentId' (DB + Model + API)
- PreparerContext im ChatContext für Agent-Konfiguration
- RunPreparer() in AnthropicService: führt Preparer vor dem Worker aus
  - [FORWARD] → aufbereiteter Prompt wird an Session-Agent weitergegeben
  - Ohne [FORWARD] → Rückfrage an User, Flow stoppt (preparer_query)
- Preparer-System-Prompt: erklärt Rolle, [FORWARD]-Mechanismus, Vorarbeit
- Preparer kann eigene Tools + Fähigkeiten aktiv nutzen
- ChatEndpoint: Preparer-Phase vor StreamChat integriert
- Frontend: SSE-Events (preparer_start/text/tool_use/done)
- Preparer-Bubble (Info-Farbe) mit Status Weitergeleitet/Rückfrage
- [Preparer: Name] → hübscher Header, [FORWARD] ausgeblendet
- [Vorbereitet von Name] → dezenter Header in User-Bubble
- Agent-Picker im Session-Form (vor Review-Agent)
2026-03-07 15:23:22 +01:00
Meleki 8e0ae90dc6 Plan-Modus: System-Prompt-Blöcke kontextabhängig anpassen
- SystemPromptBuilder.BuildBlocks/Build bekommt planMode-Parameter
- Im Plan-Modus: Tools-Block zeigt nur Read-only-Tools (read_file, list_files, glob, grep)
- Im Plan-Modus: KRITISCH, Verhalten, Erinnerung und Git-Blöcke werden übersprungen
- Im Plan-Modus: Skills als 'nicht ausführbar' markiert
- Plan-Modus-Block zentral im SystemPromptBuilder statt doppelt in AnthropicService + SessionEndpoint
- ChatService reicht planMode an SystemPromptBuilder durch
- SessionEndpoint reicht planMode Query-Parameter an BuildBlocks durch
- System-Prompt-Modal zeigt korrekte Blöcke je nach Plan-Modus-Status
2026-03-07 12:20:44 +01:00
Meleki 6d95f9aec2 feat: Plan-Modus – Toggle im Chat zum Umschalten zwischen Plan/Ausführung
- Toggle-Button (🗺️) im Chat-Input-Bereich neben Explorer
- Plan-Modus wird per ChatRequest.planMode an Backend gesendet
- Backend: Write-Tools gefiltert (nur read_file, list_files, glob, grep,
  todo_write, memory_*, ask_user_choice bleiben), System-Prompt-Block
  ergänzt der Änderungen verbietet, tool_choice nie 'any' erzwungen
- ChainRecord.PlanMode: pro Chain gespeichert (informativ für History)
- Chain-Meta-Badge '📋 Plan-Modus' bei Plan-Chains
- Choice-Response erbt planMode vom vorherigen Chain
- CSS: .plan-mode-active Styling (Primary-Color Highlight)
- Placeholder wechselt zu 'Plannen...' wenn aktiv
- Plan-Modus wird bei Session-Wechsel zurückgesetzt
2026-03-07 12:07:39 +01:00
Meleki 89ceb61948 feat: Agent-Einstellung 'Rückfragen erlauben' (allowUserChoice)
- Neues Feld AllowUserChoice (bool, default true) im AgentRecord
- DB-Migration: allow_user_choice Spalte mit DEFAULT 1
- Agent-Form: Checkbox 'Rückfragen erlauben' nach 'Tool-Nutzung erzwingen'
- ToolService.GetToolDefinitions: neuer Parameter includeUserChoice
- ask_user_choice Tool wird nur eingebunden wenn Agent es erlaubt
- Review-Agents und Non-Streaming (Cronjobs) erhalten nie ask_user_choice
- ChatEndpoint reicht Agent.AllowUserChoice an StreamChat durch
2026-03-07 11:36:02 +01:00
Meleki 5f3e308975 feat: ask_user_choice Tool – interaktive Auswahlmöglichkeiten im Chat
Neues Tool 'ask_user_choice' analog zum AskUserQuestion aus dem Claude Agent SDK.
Claude kann dem User Multiple-Choice-Fragen stellen, wenn es mehrere sinnvolle
Wege gibt. Der User wählt per Button, Claude arbeitet mit der Antwort weiter.

Backend:
- ToolService: ask_user_choice Tool-Definition (question + choices[2-5])
- AnthropicService/ProcessStream: Tool wird NICHT ausgeführt, sondern als
  SSE-Event 'user_choice' an den Client gesendet. stopReason wird auf
  'awaiting_user_choice' gesetzt (mit Guard gegen Überschreibung durch
  message_delta)
- ChatEndpoint: Erkennung von Choice-Responses (choiceToolCallId + choiceResult),
  tool_result wird in die korrekte Chain gespeichert (wo der tool_use liegt),
  toolChoice wird auf 'auto' gesetzt damit Claude frei antworten kann
- ChatService: FindChainWithToolCall() zum Auffinden der richtigen Chain,
  BuildHistoryFromDb() erweitert um Choice-Chain-Erkennung (wenn letzte Chain
  leer/nur tool_result → vorletzte Chain vollständig rekonstruieren)
- ChatModels: ChatRequest um ChoiceToolCallId + ChoiceResult erweitert

Frontend:
- api.js: apiChatChoice() für Choice-Responses
- chat.js: handleStreamEvent() als shared Handler extrahiert (sendMessage +
  handleChoiceClick nutzen denselben Code), handleChoiceClick() startet neuen
  Stream nach Button-Klick
- ui.js: addChoiceBubble() (live/interaktiv) + addChoiceBubbleStatic() (History)
- history.js: Choice-Bubbles in _renderMessagesIntoFragment + renderMessages,
  Voraus-Suche nach zugehörigem tool_result, unbeantwortet = klickbare Buttons
- chat.css: Styling für Choice-Bubbles (Primary-Color-Outline-Buttons, Hover,
  Selected/Unselected States)

Robustheit:
- Backend-Fallback wenn Claude choices als String statt Array sendet
- Frontend-Guard: Array.isArray(choices) an allen 4 Render-Stellen
- Page-Refresh mit offener Choice → aktive Buttons werden korrekt gerendert
2026-03-07 11:30:55 +01:00
Meleki 4bec740765 feat: Finalizer-Agent – dritter Agent der nach Worker + Review einschreitet
Backend:
- SessionRecord + DB-Migration: finalizer_agent_id auf sessions
- ChatContext.FinalizerContext (Model, SystemPrompt, Tools, Workspace)
- ChatService: FinalizerContext aufbauen (analog zu ReviewContext)
- AnthropicService: RunFinalizer() nach Review-Phase (oder direkt nach Worker)
- RunReviewAgentChat() refactored zu generischem RunAgentChat()
  mit agentType-Parameter ('review' | 'finalizer') für SSE-Events und DB-Tags
- SSE-Events: finalizer_start, finalizer_text, finalizer_tool_use, finalizer_done

Frontend:
- Session-Page: Finalizer-Agent-Picker (im 'Weitere Einstellungen' Bereich)
- Chat: SSE-Events für Finalizer-Phase verarbeiten
- UI: addReviewBubble/finalizeReviewBubble unterstützen agentType 'finalizer'
  mit eigener Farbe (success-green) und Flag-Checkered-Icon
- renderMarkdown: [Finalizer: AgentName] Tags parsen
- History: Finalizer-Messages als .finalizer-bubble rendern
- Shared-Page: Finalizer-Messages korrekt erkennen und stylen
- Dashboard: Finalizer-Badge (flag-checkered) auf Session-Cards
2026-03-06 23:35:30 +01:00