char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
539f24529
char/aliceai-t5-moe
1/** 2* 3* SERVICES 4* 5* Stateless service layer for API communication and data operations. 6* Services handle protocol-level concerns (HTTP, WebSocket, MCP, IndexedDB) 7* without managing reactive state — that responsibility belongs to stores. 8* 9* **Design Principles:** 10* - All methods are static — no instance state 11* - Pure I/O operations (network requests, database queries) 12* - No Svelte runes or reactive primitives 13* - Error handling at the protocol level; business-level error handling in stores 14* 15* **Architecture (bottom to top):** 16* - **Services** (this layer): Stateless protocol communication 17* - **Stores**: Reactive state management consuming services 18* - **Components**: UI consuming stores 19* 20*/ 21 22/** 23* **ChatService** - Chat Completions API communication layer 24* 25* Handles direct communication with the llama-server's `/v1/chat/completions` endpoint. 26* Provides streaming and non-streaming response parsing, message format conversion 27* (DatabaseMessage → API format), and request lifecycle management. 28* 29* **Terminology - Chat vs Conversation:** 30* - **Chat**: The active interaction space with the Chat Completions API. Ephemeral and 31* runtime-focused — sending messages, receiving streaming responses, managing request lifecycles. 32* - **Conversation**: The persistent database entity storing all messages and metadata. 33* Managed by conversationsStore, conversations persist across sessions. 34* 35* **Architecture & Relationships:** 36* - **ChatService** (this class): Stateless API communication layer 37* - Handles HTTP requests/responses with the llama-server 38* - Manages streaming and non-streaming response parsing 39* - Converts database messages to API format (multimodal, tool calls) 40* - Handles error translation with user-friendly messages 41* 42* - **chatStore**: Primary consumer — uses ChatService for all AI model communication 43* - **agenticStore**: Uses ChatService for multi-turn agentic loop streaming 44* - **conversationsStore**: Provides message context for API requests 45* 46* **Key Responsibilities:** 47* - Streaming response handling with real-time content/reasoning/tool-call callbacks 48* - Non-streaming response parsing with complete response extraction 49* - Database message to API format conversion (attachments, tool calls, multimodal) 50* - Tool call delta merging for incremental streaming aggregation 51* - Request parameter assembly (sampling, penalties, custom params) 52* - File attachment processing (images, PDFs, audio, text, MCP prompts/resources) 53* - Reasoning content stripping from prompt history to avoid KV cache pollution 54* - Error translation (network, timeout, server errors → user-friendly messages) 55* 56* @see chatStore in stores/chat/index.svelte.ts — primary consumer for chat state management 57* @see agenticStore in stores/agentic/index.svelte.ts — uses ChatService for agentic loop streaming 58* @see conversationsStore in stores/conversations/index.svelte.ts — provides message context 59*/ 60export { ChatService } from './chat.service' ; 61 62/** 63* **DatabaseService** - IndexedDB persistence layer via Dexie ORM 64* 65* Provides stateless data access for conversations and messages using IndexedDB. 66* Handles all low-level storage operations including branching tree structures, 67* cascade deletions, and transaction safety for multi-table operations. 68* 69* **Architecture & Relationships (bottom to top):** 70* - **DatabaseService** (this class): Stateless IndexedDB operations 71* - Lowest layer — direct Dexie/IndexedDB communication 72* - Pure CRUD operations without business logic 73* - Handles branching tree structure (parent-child relationships) 74* - Provides transaction safety for multi-table operations 75* 76* - **conversationsStore**: Reactive state management layer 77* - Uses DatabaseService for all persistence operations 78* - Manages conversation list, active conversation, and messages in memory 79* 80* - **chatStore**: Active AI interaction management 81* - Uses conversationsStore for conversation context 82* - Directly uses DatabaseService for message CRUD during streaming 83* 84* **Key Responsibilities:** 85* - Conversation CRUD (create, read, update, delete) 86* - Message CRUD with branching support (parent-child relationships) 87* - Root message and system prompt creation 88* - Cascade deletion of message branches (descendants) 89* - Transaction-safe multi-table operations 90* - Conversation import with duplicate detection 91* 92* **Database Schema:** 93* - `conversations`: id, lastModified, currNode, name 94* - `messages`: id, convId, type, role, timestamp, parent, children 95* 96* **Branching Model:** 97* Messages form a tree structure where each message can have multiple children, 98* enabling conversation branching and alternative response paths. The conversation's 99* `currNode` tracks the currently active branch endpoint. 100* 101* @see conversationsStore in stores/conversations/index.svelte.ts — reactive layer on top of DatabaseService 102* @see chatStore in stores/chat/index.svelte.ts — uses DatabaseService directly for message CRUD during streaming 103*/ 104export { DatabaseService } from './database.service' ; 105 106/** 107* **ConversationTransferService** - Conversation import/export format layer 108* 109* Owns the JSONL session format (SESSION header + MESSAGE records), ZIP 110* archiving and browser downloads. Stateless; DB access and store refreshes 111* stay in conversationsStore. 112*/ 113export { ConversationTransferService } from './conversation-transfer.service' ; 114 115/** 116* **ModelsService** - Model management API communication 117* 118* Handles communication with model-related endpoints for both MODEL (single model) 119* and ROUTER (multi-model) server modes. Provides model listing, loading/unloading, 120* and status checking without managing any model state. 121* 122* **Architecture & Relationships:** 123* - **ModelsService** (this class): Stateless HTTP communication 124* - Sends requests to model endpoints 125* - Parses and returns typed API responses 126* - Provides model status utility methods 127* 128* - **modelsStore**: Primary consumer — manages reactive model state 129* - Calls ModelsService for all model API operations 130* - Handles polling, caching, and state updates 131* 132* **Key Responsibilities:** 133* - List available models via OpenAI-compatible `/v1/models` endpoint 134* - Load/unload models via `/models/load` and `/models/unload` (ROUTER mode) 135* - Model status queries (loaded, loading) 136* 137* **Server Mode Behavior:** 138* - **MODEL mode**: Only `list()` is relevant — single model always loaded 139* - **ROUTER mode**: Full lifecycle — `list()`, `listRouter()`, `load()`, `unload()` 140* 141* **Endpoints:** 142* - `GET /v1/models` — OpenAI-compatible model list (both modes) 143* - `POST /models/load` — Load a model (ROUTER mode only) 144* - `POST /models/unload` — Unload a model (ROUTER mode only) 145* 146* @see modelsStore in stores/models/index.svelte.ts — primary consumer for reactive model state 147*/ 148export { ModelsService } from './models.service' ; 149 150/** 151* **PropsService** - Server properties and capabilities retrieval 152* 153* Fetches server configuration, model information, and capabilities from the `/props` 154* endpoint. Supports both global server props and per-model props (ROUTER mode). 155* 156* **Architecture & Relationships:** 157* - **PropsService** (this class): Stateless HTTP communication 158* - Fetches server properties from `/props` endpoint 159* - Handles authentication and request parameters 160* - Returns typed `ApiLlamaCppServerProps` responses 161* 162* - **serverStore**: Consumes global server properties (role detection, connection state) 163* - **modelsStore**: Consumes per-model properties (modalities, context size) 164* - **settingsStore**: Syncs default generation parameters from props response 165* 166* **Key Responsibilities:** 167* - Fetch global server properties (default generation settings, modalities) 168* - Fetch per-model properties in ROUTER mode via `?model=<id>` parameter 169* - Handle autoload control to prevent unintended model loading 170* 171* **API Behavior:** 172* - `GET /props` → Global server props (MODEL mode: includes modalities) 173* - `GET /props?model=<id>` → Per-model props (ROUTER mode: model-specific modalities) 174* - `&autoload=false` → Prevents model auto-loading when querying props 175* 176* @see serverStore in stores/server.svelte.ts — consumes global server props 177* @see modelsStore in stores/models/index.svelte.ts — consumes per-model props for modalities 178* @see settingsStore in stores/settings/index.svelte.ts — syncs default generation params from props 179*/ 180export { PropsService } from './props.service' ; 181 182/** 183* **ParameterSyncService** - Server defaults and user settings synchronization 184* 185* Manages the complex logic of merging server-provided default parameters with 186* user-configured overrides. Ensures the UI reflects the actual server state 187* while preserving user customizations. Tracks parameter sources (server default 188* vs user override) for display in the settings UI. 189* 190* **Architecture & Relationships:** 191* - **ParameterSyncService** (this class): Stateless sync logic 192* - Pure functions for parameter extraction, merging, and diffing 193* - No side effects — receives data in, returns data out 194* - Handles floating-point precision normalization 195* 196* - **settingsStore**: Primary consumer — calls sync methods during: 197* - Initial load (`syncWithServerDefaults`) 198* - Settings reset (`forceSyncWithServerDefaults`) 199* - Parameter info queries (`getParameterInfo`) 200* 201* - **PropsService**: Provides raw server props that feed into extraction 202* 203* **Key Responsibilities:** 204* - Extract syncable parameters from server `/props` response 205* - Merge server defaults with user overrides (user wins) 206* - Track parameter source (Custom vs Default) for UI badges 207* - Validate server parameter values by type (number, string, boolean) 208* - Create diffs between current settings and server defaults 209* - Floating-point precision normalization for consistent comparisons 210* 211* **Parameter Source Priority:** 212* 1. **User Override** (Custom badge) — explicitly set by user in settings 213* 2. **Server Default** (Default badge) — from `/props` endpoint 214* 3. **App Default** — hardcoded fallback when server props unavailable 215* 216* **Exports:** 217* - `ParameterSyncService` class — static methods for sync logic 218* - `SYNCABLE_PARAMETERS` — mapping of UI setting keys to server parameter keys 219* 220* @see settingsStore in stores/settings/index.svelte.ts — primary consumer for settings sync 221* @see SettingsChatParameterSourceIndicator — displays parameter source badges in UI 222*/ 223export { ParameterSyncService } from './parameter-sync.service' ; 224 225/** 226* **MCPService** - Low-level MCP protocol communication layer 227* 228* Implements the client-side MCP (Model Context Protocol) SDK operations for connecting 229* to MCP servers, discovering capabilities, and executing protocol operations. 230* Supports multiple transport types: WebSocket, StreamableHTTP, and SSE (legacy fallback). 231* 232* **Architecture & Relationships:** 233* - **MCPService** (this class): Stateless protocol communication 234* - Creates and manages transport connections (WebSocket, StreamableHTTP, SSE) 235* - Wraps MCP SDK client operations with error handling 236* - Formats tool results and extracts server info 237* - Provides abort signal support for cancellable operations 238* 239* - **mcpStore**: Reactive business logic facade 240* - Uses MCPService for all protocol-level operations 241* - Manages connection lifecycle, health checks, reconnection 242* - Handles tool name conflict resolution and server coordination 243* 244* - **mcpResourceStore** (composed as mcpStore.resources): Reactive resource state 245* - Receives resource data fetched via MCPService 246* - Manages resource caching, subscriptions, and attachments 247* 248* - **agenticStore**: Agentic loop orchestration 249* - Executes tool calls via mcpStore → MCPService chain 250* 251* **Key Responsibilities:** 252* - Transport creation with automatic fallback (StreamableHTTP → SSE) 253* - Server connection with detailed phase tracking and progress callbacks 254* - Tool discovery (`listTools`) and execution (`callTool`) with abort support 255* - Prompt listing (`listPrompts`) and retrieval (`getPrompt`) with arguments 256* - Resource operations: list, read, subscribe/unsubscribe, template support 257* - Completion suggestions for prompt arguments and resource URI templates 258* - CORS proxy routing via llama-server for cross-origin MCP servers 259* - Tool result formatting (text, images, embedded resources) 260* 261* **Transport Hierarchy:** 262* 1. **WebSocket** — bidirectional, no CORS proxy support 263* 2. **StreamableHTTP** — modern HTTP-based, supports CORS proxy 264* 3. **SSE** — legacy fallback, supports CORS proxy 265* 266* @see mcpStore in stores/mcp/index.svelte.ts — reactive business logic facade on top of MCPService 267* @see mcpStore.resources in stores/mcp/resources.svelte.ts — reactive resource state management 268* @see agenticStore in stores/agentic/index.svelte.ts — uses MCPService (via mcpStore) for tool execution 269* @see MCP Protocol Specification: https://modelcontextprotocol.io/specification/2025-06-18 270*/ 271export { MCPService } from './mcp.service' ; 272 273/** 274* **SandboxService** - Browser JavaScript execution in a browser sandbox 275* 276* Stateless executor for the run_javascript browser tool. Model generated 277* code runs in a Web Worker spawned inside a sandboxed iframe with an opaque 278* origin: no access to the app origin, its storage or its API, and outgoing 279* requests carry a null origin. The code never touches a main thread, so the 280* parent enforces the timeout by removing the iframe, which terminates the 281* worker at the browser level. 282* 283* **Architecture & Relationships:** 284* - **SandboxService** (this class): Stateless sandbox execution 285* - **toolsStore**: Exposes the tool definition when the sandbox is enabled 286* - **agenticStore**: Dispatches ToolSource.BROWSER calls here 287* 288* @see buildSandboxToolDefinition in utils/sandbox-tool - tool schema sent to the LLM 289* @see agenticStore in stores/agentic/index.svelte.ts - tool dispatch 290*/ 291export { SandboxService } from './sandbox.service' ; 292 293/** 294* **RouterService** — Dynamic route URL construction utility 295* 296* Stateless utility for building dynamic route URLs from ROUTES base paths. 297* Static routes (START, MCP_SERVERS) live in ROUTES constants; 298* dynamic routes (CHAT, SETTINGS) are constructed here by appending parameters. 299* 300* **Architecture & Relationships:** 301* - **RouterService** (this class): Stateless URL construction 302* - Builds dynamic route URLs from ROUTES base paths 303* - No side effects — receives route parameters, returns route strings 304* 305* - **ROUTES constant** (constants/routes.ts): Static route base paths 306* - **All components/stores**: Call RouterService for dynamic route URLs 307* 308* **Key Responsibilities:** 309* - Build chat URLs for specific conversations: `RouterService.chat(id)` → `#/chat/:id` 310* 311* @see ROUTES in constants/routes.ts — static route base paths 312*/ 313export { RouterService } from './router.service' ; 314 315/** 316* **MigrationService** — Unified data migration hook 317* 318* Centralizes all data migrations (localStorage, IndexedDB, legacy formats) into a single 319* initialization point. All migrations are NON-DESTRUCTIVE - legacy data is preserved 320* for downgrade compatibility (no rollback needed). 321* 322* **Current Migrations:** 323* 1. **localStorage prefix**: Copy LlamaCppWebui.* → LlamaUi.* (both preserved) 324* 2. **IndexedDB database**: Copy LlamacppWebui → LlamaUi (both preserved) 325* 3. **Legacy message format**: Marker-based → Structured format 326* 4. **Theme key**: Copy standalone `theme` → config object (both preserved) 327* 328* **Usage:** 329* ```typescript 330* import { MigrationService } from '$lib/services'; 331* 332* // Run all migrations on app startup (non-destructive) 333* await MigrationService.runAllMigrations(); 334* 335* // Check migration status 336* const state = MigrationService.getState(); 337* ``` 338* 339* @see migration.service.ts — full implementation (non-destructive) 340*/ 341export { MigrationService } from './migration.service' ; 342 343/** 344* **SettingsService** - localStorage persistence layer for settings 345* 346* Stateless read/write of the settings config and user-override keys. Business 347* logic (default merging, mobile defaults, theme migration) stays in the store. 348* 349* @see settingsStore in stores/settings/index.svelte.ts - reactive state + business logic 350*/ 351export { SettingsService } from './settings.service' ;