diff --git a/AGENTS.md b/AGENTS.md index bfbceca..34d1bf3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,3 +38,4 @@ verified, tried, and decided belongs in the commit message and the PR body. - **Don't widen the AMD matcher to a bare `amdgpu` match.** ROCm fails on integrated Radeon, and StartOS's regex engine has no lookahead to exclude them, so it stays a positive allowlist of discrete product names. - **Don't shorten the health check's one-hour grace period.** It covers the model download on first start. - **New presets go in `startos/actions/presets.ts`**, with `minMemoryGB` set to the weights plus roughly 25% for the KV cache. +- **Keep the Web UI host on Basic auth and the API host on Bearer.** One binding takes one `ProxyAuth`, and StartOS enforces it on the bridge address too, so moving siblings to `api-multi` or merging the hosts locks out browsers or other services. diff --git a/README.md b/README.md index 538e666..328064b 100644 --- a/README.md +++ b/README.md @@ -57,9 +57,10 @@ The AMD requirement matches discrete cards by product name rather than excluding One volume, and most of it is downloaded models. -| Volume | Mount Point | Purpose | -| ------ | ----------- | ------------------------------------------------------------------------------- | -| `main` | `/data` | `store.json`, the GGUF model cache under `models/`, and HuggingFace's own cache | +| Volume | Mount Point | Purpose | +| -------- | ----------- | ------------------------------------------------------------------------------------------ | +| `main` | `/data` | `store.json`, the GGUF model cache under `models/`, and HuggingFace's own cache | +| `public` | (none) | `credentials.json` with the API key; dependent services mount it read-only to read the key | Models are the bulk of it — a single quantized model runs from roughly one to forty gigabytes depending on size. @@ -67,11 +68,12 @@ llama.cpp keeps the cache in the HuggingFace hub layout: each repo is `models/mo ## File Models -One model. Two of its keys decide whether the service can run at all; the third only exists so a form can remember what you last told it. +Two models. Two of `store.json`'s keys decide whether the service can run at all; the others only exist so a form can remember what you last told it. -| File | Format | Modelled | Written by | -| ------------ | ------ | ----------------------- | ----------------------------------------- | -| `store.json` | JSON | Yes — `FileHelper.json` | The Set Model and Set UI Password actions | +| File | Format | Modelled | Written by | +| ------------------ | ------ | ----------------------- | ------------------------------------------ | +| `store.json` | JSON | Yes — `FileHelper.json` | The Set Model and Set UI Password actions | +| `credentials.json` | JSON | Yes — `FileHelper.json` | Init (when missing) and the API Key action | | Key | Notes | | ---------------- | ----------------------------------------------------------------------------------------------- | @@ -82,6 +84,8 @@ One model. Two of its keys decide whether the service can run at all; the third Nothing else writes the file, and neither `serveArgs` nor `uiPassword` is defaulted — both are absent until you run their action, and each absence raises a task. +`credentials.json` on the `public` volume holds one key, `apiKey`: the Bearer token for the OpenAI-compatible API interface. Init generates it (32 alphanumeric characters) whenever it is missing — on install, on update from a version without it, or after it is deleted — so it is never empty while the service runs. + `modelSelection` holds the chosen `selection` plus a `custom` object with the last Custom submission's fields; picking another entry leaves `custom` in place so Custom stays prefilled. `modelSettings` is a list of `{hfRepo, hfFile, ctx, ngl, extraArgs}`, one per model, replaced on each submit of that model. Entries are matched to the list by the weights they resolve to — the same cached file, or the same quant tag before download — so a Custom model keeps its settings once it shows up as a downloaded entry. Stores from before `modelSettings` fall back to `modelSelection.custom`. The daemon reads neither, so they cannot disagree with `serveArgs` about what is actually running — at worst they prefill a form with a stale answer. **No configuration file reaches the application.** Two environment variables are set, both redirecting caches onto the volume so downloaded weights survive a container rebuild: @@ -99,15 +103,17 @@ None. ## Network Access and Interfaces -One interface, serving both the OpenAI-compatible API and llama.cpp's built-in chat UI. +Two interfaces, on two hosts that both forward to llama-server's internal port 8080. They serve the same thing — the OpenAI-compatible API and the built-in chat UI — and differ only in the credential the StartOS proxy demands. -| Interface | Id | Type | Port | Description | -| ---------------- | ----- | ---- | ---- | ------------------------------------ | -| llama.cpp Server | `api` | ui | 8080 | The API and the built-in chat client | +| Interface | Id | Host | Type | Internal port | Auth at the proxy | +| --------------------- | ------------ | ----------- | ---- | ------------- | ---------------------------------------- | +| Web UI | `api` | `api-multi` | ui | 8080 | Basic, `admin` + `uiPassword` | +| OpenAI-compatible API | `openai-api` | `api-key` | api | 8080 | Bearer, `apiKey` from `credentials.json` | -**Authentication is added by StartOS, not by llama.cpp.** The server itself runs keyless; the binding declares HTTP basic auth at the edge, with the username `admin` and the password from `store.json`. Until a password is set the binding is configured with an empty one — which never serves anything, because the service is blocked from starting by a `critical` task at the same time. +**Authentication is added by StartOS, not by llama.cpp.** The server itself runs keyless. Since StartOS 0.4.1 the proxy enforces a binding's auth on its plaintext bridge address (`10.0.3.1:`) as well as on the LAN, so other services are challenged like any other client. Browsers can only answer a Basic challenge and OpenAI clients only send a Bearer key, which is why there are two hosts. -An OpenAI-compatible client therefore needs those basic-auth credentials as well as whatever it would normally send. +- **Web UI:** until a password is set the binding is configured with an empty one — which never serves anything, because the service is blocked from starting by a `critical` task at the same time. +- **OpenAI-compatible API:** the binding exists only once the key does; init creates it before the interfaces are set. Dependent services resolve this host's bridge address (`apiKeyHostId`, `apiPort` from `startos/utils.ts`) and read the key from the `public` volume. A key of the wrong type or value gets `401` with `WWW-Authenticate: Bearer`. ## Installation and First-Run Flow @@ -122,7 +128,7 @@ The first start after choosing a model **downloads it**, which is why the health ## Actions -Three actions, all user-facing. +Four actions, all user-facing. ### Set Model @@ -146,6 +152,15 @@ Generates the password for the API and chat UI. - **Repeat safety:** safe to re-run, but it **replaces** the existing password — every saved client login has to be updated. When a password already exists it asks for confirmation first; the first run does not. - **Outputs:** the username `admin` and the new password. +### API Key + +Shows the Bearer key for the OpenAI-compatible API interface. + +- **Input:** one toggle, **Generate a new key**, off by default. +- **What it changes:** nothing when the toggle is off. When on — or when no key exists — it writes a new `apiKey` to `credentials.json`, which rebinds the API host with the new token. llama-server does not restart. +- **Repeat safety:** safe to re-run. Rotating breaks every client still sending the old key; dependent StartOS services that read the key reactively pick up the new one when they restart. +- **Outputs:** the key, masked and copyable. + ### Delete Model Cache Removes one downloaded model to reclaim disk. @@ -181,16 +196,16 @@ With no model selected the daemon idles rather than exiting, and the check's fai ## Backups and Restore -The `main` volume is backed up — `sdk.Backups.ofVolumes('main')` — with one exclusion: `setOptions({ exclude: ['models/'] })` leaves out `/data/models`, the model cache. No dump step. +The `main` and `public` volumes are backed up — `sdk.Backups.ofVolumes('main', 'public')` — with one exclusion: `setOptions({ exclude: ['models/'] })` leaves out `/data/models`, the model cache. No dump step. -- **Included:** `store.json` with the model selection and password. +- **Included:** `store.json` with the model selection and password, and `credentials.json` with the API key, so dependent services keep working after a restore. - **Excluded:** every downloaded model. Weights are re-downloadable from upstream, so the backup stays small rather than being dominated by the cache. -- **Restore:** the selection and password come back and no tasks are raised. The selected model is downloaded again on the first start, inside the health check's one-hour grace. +- **Restore:** the selection, password and API key come back and no tasks are raised. The selected model is downloaded again on the first start, inside the health check's one-hour grace. ## Limitations and Differences 1. **Two settings are required before the service does anything**, and each is enforced by a blocking task rather than defaulted. -2. **Authentication is the reverse proxy's, not llama.cpp's.** Every client, including API clients, must send basic-auth credentials. +2. **Authentication is the reverse proxy's, not llama.cpp's.** Browsers log in to the Web UI interface with Basic auth; API clients send the API key as a Bearer token to the OpenAI-compatible API interface. Neither credential works on the other interface. 3. **Which accelerator variant you get is decided by StartOS**, from the hardware present; it is not a setting. 4. **Integrated AMD graphics fall back to the generic CPU build.** ROCm is matched only for discrete cards. 5. **The Vulkan variant matches Intel GPUs only**, on the `i915` driver. @@ -217,17 +232,21 @@ subcontainers: - detect-mem # temporary; preset sizing volumes: main: /data + public: null # credentials.json, read by dependents file_models: - store.json + - credentials.json startos_managed_env_vars: - LLAMA_CACHE - HF_HOME dependencies: [] interfaces: - api: { type: ui, port: 8080 } # basic auth enforced at the edge, username "admin" + api: { type: ui, host: api-multi, port: 8080 } # Basic at the edge, username "admin" + openai-api: { type: api, host: api-key, port: 8080 } # Bearer at the edge, key in public/credentials.json actions: - set-model - set-ui-password + - api-key - delete-model-cache tasks: - { action: set-ui-password, severity: critical } diff --git a/instructions.md b/instructions.md index 9e1a607..d48ad1b 100644 --- a/instructions.md +++ b/instructions.md @@ -7,9 +7,8 @@ ## What you get on StartOS -- An OpenAI-compatible HTTP API at `/v1`, serving one GGUF model at a time. -- The upstream chat UI at the same URL — open the interface in a browser to chat without setting up a client. -- A password-protected login (username `admin`) on the UI and API, so only you can use them. Other StartOS AI apps that depend on llama.cpp (such as Open WebUI) connect over the internal network with no login to copy. +- The upstream chat UI on the **Web UI** interface — open it in a browser to chat without setting up a client. It asks for a login (username `admin`). +- An OpenAI-compatible HTTP API on the **OpenAI-compatible API** interface, at `/v1`, serving one GGUF model at a time. It takes an API key instead of a login. Other StartOS AI apps that connect to llama.cpp (such as Open WebUI) read the key themselves, so there is nothing to copy. - Curated GGUF presets, plus a Custom option that accepts any HuggingFace GGUF repo. - Persistent model cache on the package volume — downloads happen once and survive restarts. The cache is excluded from backups; after a restore, the selected model downloads again on first start. @@ -24,20 +23,20 @@ Complete both tasks, then start the service from the dashboard. The first launch ### Chat UI -Open the **llama.cpp Server** interface from the Dashboard. Your browser will prompt for a login — enter `admin` and the password from **Set UI Password**. The upstream chat UI is at `/`; pick a conversation and start typing. +Open the **Web UI** interface from the Dashboard. Your browser will prompt for a login — enter `admin` and the password from **Set UI Password**. The upstream chat UI is at `/`; pick a conversation and start typing. ### OpenAI-compatible API -Point any OpenAI-compatible client at the same URL with `/v1` appended: +Use the **OpenAI-compatible API** interface for clients and apps, with `/v1` appended: -- **Base URL:** `/v1` -- **Authentication:** the interface is gated by HTTP basic auth — username `admin`, password from **Set UI Password**. Most OpenAI clients only offer an "API key" field (sent as a bearer token), which the proxy won't accept; for those, use a client that supports basic auth, or call the API with `curl -u admin:`. +- **Base URL:** `/v1` +- **API key:** the key from the **API Key** action. The Web UI password does not work here, and the key does not work on the Web UI interface. - **Model name:** llama.cpp serves a single model, so most clients accept any string or an empty value here. Quick test from the command line: ```sh -curl -s -u admin: /v1/chat/completions \ +curl -s -H "Authorization: Bearer " /v1/chat/completions \ -H "Content-Type: application/json" \ -d '{"messages":[{"role":"user","content":"Say hello in one short sentence."}]}' ``` @@ -46,6 +45,7 @@ curl -s -u admin: /v1/chat/completions \ - **Set Model** — switch to a different preset, a model you already downloaded, or a custom GGUF. The form opens on the model you are running, with its settings filled in, so you can change its context size or flags and submit; submitting without changes does not restart anything. Each model remembers its own settings, so switching away and back keeps them. The service restarts with the new weights; uncached models download on this restart. - **Set UI Password** — generate a new web UI password (username stays `admin`). Use it for first-time setup or to rotate the password later; when rotating, it asks you to confirm, since saved logins stop working. +- **API Key** — show the key for the OpenAI-compatible API interface. Turn on **Generate a new key** to replace it; clients outside StartOS then need the new key, and StartOS apps pick it up when they restart. - **Delete Model Cache** — pick a downloaded model from the list, with its size, and remove it to reclaim disk space. The model you are currently running can't be deleted; switch to another one with Set Model first. A deleted model will be re-downloaded if you select it again. ## Limitations diff --git a/startos/actions/apiKey.ts b/startos/actions/apiKey.ts new file mode 100644 index 0000000..80772d2 --- /dev/null +++ b/startos/actions/apiKey.ts @@ -0,0 +1,61 @@ +import { credentialsJson } from '../fileModels/credentials.json' +import { i18n } from '../i18n' +import { sdk } from '../sdk' +import { generateApiKey } from '../utils' + +const { InputSpec, Value } = sdk + +const inputSpec = InputSpec.of({ + rotate: Value.toggle({ + name: i18n('Generate a new key'), + description: i18n( + 'Replace the key. Clients outside StartOS must be updated with the new one; services on this server pick it up when they restart.', + ), + default: false, + }), +}) + +export const apiKey = sdk.Action.withInput( + 'api-key', + + async ({ effects }) => ({ + name: i18n('API Key'), + description: i18n( + 'Show the key for the OpenAI-compatible API interface, or generate a new one.', + ), + warning: null, + allowedStatuses: 'any', + group: null, + visibility: 'enabled', + }), + + inputSpec, + + async ({ effects }) => null, + + async ({ effects, input }) => { + let key = await credentialsJson.read((c) => c.apiKey).once() + if (input.rotate || !key) { + key = generateApiKey() + await credentialsJson.merge(effects, { apiKey: key }) + } + + return { + version: '1', + title: i18n('API Key'), + message: i18n( + 'Send this key as "Authorization: Bearer " to the OpenAI-compatible API interface. In most clients, set the base URL to that interface\'s address with /v1 appended and paste this as the API key.', + ), + result: { + type: 'single', + name: i18n('API Key'), + description: null, + value: key, + masked: true, + copyable: true, + qr: false, + launchable: false, + }, + } + }, +) diff --git a/startos/actions/index.ts b/startos/actions/index.ts index b5afa95..b39702a 100644 --- a/startos/actions/index.ts +++ b/startos/actions/index.ts @@ -2,8 +2,10 @@ import { sdk } from '../sdk' import { setModel } from './setModel' import { setUiPassword } from './setUiPassword' import { deleteModelCache } from './deleteModelCache' +import { apiKey } from './apiKey' export const actions = sdk.Actions.of() .addAction(setModel) .addAction(setUiPassword) + .addAction(apiKey) .addAction(deleteModelCache) diff --git a/startos/backups.ts b/startos/backups.ts index 618fbd5..53b2b5c 100644 --- a/startos/backups.ts +++ b/startos/backups.ts @@ -2,7 +2,7 @@ import { sdk } from './sdk' export const { createBackup, restoreInit } = sdk.setupBackups( async ({ effects }) => - sdk.Backups.ofVolumes('main').setOptions({ + sdk.Backups.ofVolumes('main', 'public').setOptions({ exclude: ['models/'], }), ) diff --git a/startos/fileModels/credentials.json.ts b/startos/fileModels/credentials.json.ts new file mode 100644 index 0000000..d4205f5 --- /dev/null +++ b/startos/fileModels/credentials.json.ts @@ -0,0 +1,15 @@ +import { FileHelper, z } from '@start9labs/start-sdk' +import { sdk } from '../sdk' + +/** + * On the `public` volume, which dependent services mount read-only to read the + * API host's Bearer key. + */ +const shape = z.looseObject({ + apiKey: z.string().optional().catch(undefined), +}) + +export const credentialsJson = FileHelper.json( + { base: sdk.volumes.public, subpath: 'credentials.json' }, + shape, +) diff --git a/startos/i18n/dictionaries/default.ts b/startos/i18n/dictionaries/default.ts index f3481ee..377c0bc 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -9,8 +9,10 @@ const dict = { 'No model selected. Run the "Set Model" action.': 4, // interfaces.ts - 'llama.cpp Server': 5, - 'OpenAI-compatible API and built-in chat UI': 6, + 'Web UI': 5, + 'The built-in chat UI, for your browser. Log in as "admin" with the password from Set UI Password.': 6, + 'OpenAI-compatible API': 54, + 'For OpenAI-compatible clients and apps. Requires the key from the API Key action. Append /v1 to the address.': 55, // actions/setModel.ts 'Set Model': 7, @@ -65,6 +67,13 @@ const dict = { Username: 51, Password: 52, + // actions/apiKey.ts + 'Generate a new key': 56, + 'Replace the key. Clients outside StartOS must be updated with the new one; services on this server pick it up when they restart.': 57, + 'API Key': 58, + 'Show the key for the OpenAI-compatible API interface, or generate a new one.': 59, + 'Send this key as "Authorization: Bearer " to the OpenAI-compatible API interface. In most clients, set the base URL to that interface\'s address with /v1 appended and paste this as the API key.': 60, + // init/initializeService.ts 'Generate a password to log in to the llama.cpp web UI': 39, 'Select which AI model llama.cpp should serve': 40, diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index 2dd3380..f8d8a9e 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -7,8 +7,8 @@ export default { 2: 'La API de llama.cpp está lista', 3: 'La API de llama.cpp no está lista', 4: 'No hay modelo seleccionado. Ejecute la acción "Establecer modelo".', - 5: 'Servidor llama.cpp', - 6: 'API compatible con OpenAI e interfaz de chat integrada', + 5: 'Interfaz web', + 6: 'La interfaz de chat integrada, para su navegador. Inicie sesión como "admin" con la contraseña de Establecer contraseña de la interfaz.', 7: 'Establecer modelo', 8: 'Elija un preset GGUF curado dimensionado para su hardware, o proporcione un modelo personalizado de HuggingFace. El modelo se descargará en el primer inicio si no está en caché.', 9: 'Cambiar el modelo reiniciará el servicio y puede requerir descargar un nuevo modelo.', @@ -56,6 +56,13 @@ export default { 51: 'Nombre de usuario', 52: 'Contraseña', 53: 'Ese modelo descargado ya no está en la caché.', + 54: 'API compatible con OpenAI', + 55: 'Para clientes y aplicaciones compatibles con OpenAI. Requiere la clave de la acción Clave de API. Añada /v1 a la dirección.', + 56: 'Generar una clave nueva', + 57: 'Reemplaza la clave. Los clientes fuera de StartOS deben actualizarse con la nueva; los servicios de este servidor la adoptan al reiniciarse.', + 58: 'Clave de API', + 59: 'Muestra la clave de la interfaz API compatible con OpenAI o genera una nueva.', + 60: 'Envíe esta clave como "Authorization: Bearer " a la interfaz API compatible con OpenAI. En la mayoría de los clientes, establezca la URL base en la dirección de esa interfaz con /v1 añadido y pegue esto como clave de API.', }, de_DE: { 0: 'Starte llama.cpp!', @@ -63,8 +70,8 @@ export default { 2: 'Die llama.cpp-API ist bereit', 3: 'Die llama.cpp-API ist nicht bereit', 4: 'Kein Modell ausgewählt. Führen Sie die Aktion „Modell festlegen“ aus.', - 5: 'llama.cpp-Server', - 6: 'OpenAI-kompatible API und integrierte Chat-Oberfläche', + 5: 'Web-Oberfläche', + 6: 'Die integrierte Chat-Oberfläche für Ihren Browser. Melden Sie sich als „admin“ mit dem Passwort aus „UI-Passwort festlegen“ an.', 7: 'Modell festlegen', 8: 'Wählen Sie ein kuratiertes GGUF-Preset für Ihre Hardware oder geben Sie ein eigenes HuggingFace-Modell an. Das Modell wird beim ersten Start heruntergeladen, falls noch nicht zwischengespeichert.', 9: 'Das Ändern des Modells startet den Dienst neu und erfordert möglicherweise den Download eines neuen Modells.', @@ -112,6 +119,13 @@ export default { 51: 'Benutzername', 52: 'Passwort', 53: 'Dieses heruntergeladene Modell ist nicht mehr im Cache.', + 54: 'OpenAI-kompatible API', + 55: 'Für OpenAI-kompatible Clients und Apps. Erfordert den Schlüssel aus der Aktion „API-Schlüssel“. Hängen Sie /v1 an die Adresse an.', + 56: 'Neuen Schlüssel erzeugen', + 57: 'Ersetzt den Schlüssel. Clients außerhalb von StartOS müssen mit dem neuen aktualisiert werden; Dienste auf diesem Server übernehmen ihn beim Neustart.', + 58: 'API-Schlüssel', + 59: 'Zeigt den Schlüssel für die OpenAI-kompatible API-Schnittstelle an oder erzeugt einen neuen.', + 60: 'Senden Sie diesen Schlüssel als „Authorization: Bearer “ an die OpenAI-kompatible API-Schnittstelle. In den meisten Clients setzen Sie die Basis-URL auf die Adresse dieser Schnittstelle mit angehängtem /v1 und fügen dies als API-Schlüssel ein.', }, pl_PL: { 0: 'Uruchamianie llama.cpp!', @@ -119,8 +133,8 @@ export default { 2: 'API llama.cpp jest gotowe', 3: 'API llama.cpp nie jest gotowe', 4: 'Nie wybrano modelu. Uruchom akcję „Ustaw model”.', - 5: 'Serwer llama.cpp', - 6: 'API zgodne z OpenAI i wbudowany interfejs czatu', + 5: 'Interfejs WWW', + 6: 'Wbudowany interfejs czatu do przeglądarki. Zaloguj się jako „admin” hasłem z akcji „Ustaw hasło interfejsu”.', 7: 'Ustaw model', 8: 'Wybierz wyselekcjonowany preset GGUF dopasowany do sprzętu lub podaj własny model HuggingFace. Model zostanie pobrany przy pierwszym uruchomieniu, jeśli nie jest zapisany w pamięci podręcznej.', 9: 'Zmiana modelu zrestartuje usługę i może wymagać pobrania nowego modelu.', @@ -168,6 +182,13 @@ export default { 51: 'Nazwa użytkownika', 52: 'Hasło', 53: 'Tego pobranego modelu nie ma już w pamięci podręcznej.', + 54: 'API zgodne z OpenAI', + 55: 'Dla klientów i aplikacji zgodnych z OpenAI. Wymaga klucza z akcji Klucz API. Dopisz /v1 do adresu.', + 56: 'Wygeneruj nowy klucz', + 57: 'Zastępuje klucz. Klienty spoza StartOS trzeba zaktualizować nowym kluczem; usługi na tym serwerze pobiorą go przy ponownym uruchomieniu.', + 58: 'Klucz API', + 59: 'Pokazuje klucz do interfejsu API zgodnego z OpenAI lub generuje nowy.', + 60: 'Wysyłaj ten klucz jako „Authorization: Bearer ” do interfejsu API zgodnego z OpenAI. W większości klientów ustaw bazowy URL na adres tego interfejsu z dopisanym /v1 i wklej to jako klucz API.', }, fr_FR: { 0: 'Démarrage de llama.cpp !', @@ -175,8 +196,8 @@ export default { 2: "L'API llama.cpp est prête", 3: "L'API llama.cpp n'est pas prête", 4: "Aucun modèle sélectionné. Exécutez l'action « Définir le modèle ».", - 5: 'Serveur llama.cpp', - 6: 'API compatible OpenAI et interface de chat intégrée', + 5: 'Interface web', + 6: 'L’interface de discussion intégrée, pour votre navigateur. Connectez-vous en tant que « admin » avec le mot de passe de l’action « Définir le mot de passe de l’interface ».', 7: 'Définir le modèle', 8: 'Choisissez un préréglage GGUF dimensionné pour votre matériel, ou fournissez un modèle HuggingFace personnalisé. Le modèle sera téléchargé au premier démarrage s’il n’est pas déjà en cache.', 9: 'Changer de modèle redémarre le service et peut nécessiter le téléchargement d’un nouveau modèle.', @@ -224,5 +245,12 @@ export default { 51: 'Nom d’utilisateur', 52: 'Mot de passe', 53: 'Ce modèle téléchargé n’est plus dans le cache.', + 54: 'API compatible OpenAI', + 55: 'Pour les clients et applications compatibles OpenAI. Nécessite la clé de l’action Clé d’API. Ajoutez /v1 à l’adresse.', + 56: 'Générer une nouvelle clé', + 57: 'Remplace la clé. Les clients hors de StartOS doivent être mis à jour avec la nouvelle ; les services de ce serveur la reprennent à leur redémarrage.', + 58: 'Clé d’API', + 59: 'Affiche la clé de l’interface API compatible OpenAI, ou en génère une nouvelle.', + 60: 'Envoyez cette clé sous la forme « Authorization: Bearer » à l’interface API compatible OpenAI. Dans la plupart des clients, définissez l’URL de base sur l’adresse de cette interface suivie de /v1 et collez ceci comme clé d’API.', }, } satisfies Record diff --git a/startos/init/initializeService.ts b/startos/init/initializeService.ts index c9812ba..cc94bc2 100644 --- a/startos/init/initializeService.ts +++ b/startos/init/initializeService.ts @@ -1,12 +1,25 @@ import { setModel } from '../actions/setModel' import { setUiPassword } from '../actions/setUiPassword' +import { credentialsJson } from '../fileModels/credentials.json' import { storeJson } from '../fileModels/store.json' import { i18n } from '../i18n' import { sdk } from '../sdk' +import { generateApiKey } from '../utils' // Runs on every init (install, update, restore, and plain restart), and // re-runs reactively when the watched files change. export const initializeService = sdk.setupOnInit(async (effects) => { + // The API host's Bearer key: a machine key that dependent services read, so + // it is generated rather than asked for. Clearing it rotates it. + const apiKey = await credentialsJson.read((c) => c.apiKey).const(effects) + if (!apiKey) { + await credentialsJson.merge( + effects, + { apiKey: generateApiKey() }, + { allowWriteAfterConst: true }, + ) + } + // Prompt for a UI password whenever none is set — the proxy basic-auth gate // stays locked (setupInterfaces uses a throwaway) until the user runs this. const uiPassword = await storeJson.read((s) => s?.uiPassword).const(effects) diff --git a/startos/interfaces.ts b/startos/interfaces.ts index 085dfc1..92ac0a4 100644 --- a/startos/interfaces.ts +++ b/startos/interfaces.ts @@ -1,31 +1,40 @@ import { i18n } from './i18n' import { sdk } from './sdk' +import { credentialsJson } from './fileModels/credentials.json' import { storeJson } from './fileModels/store.json' -import { apiHostId, apiPort, uiUsername } from './utils' +import { apiHostId, apiKeyHostId, apiPort, uiUsername } from './utils' export const setInterfaces = sdk.setupInterfaces(async ({ effects }) => { - // llama-server itself runs keyless; the OS reverse proxy enforces basic auth - // at the edge. The Set UI Password critical task blocks the service from - // starting until a password is set, so the empty fallback never serves. + // llama-server itself runs keyless; the OS reverse proxy enforces auth at the + // edge, on the bridge address as well as the LAN. Browsers can only answer a + // Basic challenge and OpenAI clients only send a Bearer key, so each gets its + // own host on the same port. The Set UI Password critical task blocks the + // service from starting until a password is set, so the empty fallback never + // serves. const password = (await storeJson.read((s) => s?.uiPassword).const(effects)) ?? '' + const apiKey = await credentialsJson.read((c) => c.apiKey).const(effects) - const apiMulti = sdk.MultiHost.of(effects, apiHostId) - const apiMultiOrigin = await apiMulti.bindPort(apiPort, { - protocol: 'http', - addSsl: { - auth: { - type: 'basic', - credentials: [{ username: uiUsername, password }], - realm: null, + const uiMultiOrigin = await sdk.MultiHost.of(effects, apiHostId).bindPort( + apiPort, + { + protocol: 'http', + addSsl: { + auth: { + type: 'basic', + credentials: [{ username: uiUsername, password }], + realm: null, + }, }, }, - }) + ) - const api = sdk.createInterface(effects, { - name: i18n('llama.cpp Server'), + const ui = sdk.createInterface(effects, { + name: i18n('Web UI'), id: 'api', - description: i18n('OpenAI-compatible API and built-in chat UI'), + description: i18n( + 'The built-in chat UI, for your browser. Log in as "admin" with the password from Set UI Password.', + ), type: 'ui', masked: false, schemeOverride: null, @@ -34,7 +43,36 @@ export const setInterfaces = sdk.setupInterfaces(async ({ effects }) => { query: {}, }) - const apiReceipt = await apiMultiOrigin.export([api]) + const receipts = [await uiMultiOrigin.export([ui])] + + // Init generates the key; until it exists the API host stays unbound. + if (apiKey) { + const apiMultiOrigin = await sdk.MultiHost.of( + effects, + apiKeyHostId, + ).bindPort(apiPort, { + protocol: 'http', + addSsl: { + auth: { type: 'bearer', tokens: [apiKey], realm: null }, + }, + }) + + const api = sdk.createInterface(effects, { + name: i18n('OpenAI-compatible API'), + id: 'openai-api', + description: i18n( + 'For OpenAI-compatible clients and apps. Requires the key from the API Key action. Append /v1 to the address.', + ), + type: 'api', + masked: false, + schemeOverride: null, + username: null, + path: '', + query: {}, + }) + + receipts.push(await apiMultiOrigin.export([api])) + } - return [apiReceipt] + return receipts }) diff --git a/startos/manifest/index.ts b/startos/manifest/index.ts index 67d5e20..73ee1cb 100644 --- a/startos/manifest/index.ts +++ b/startos/manifest/index.ts @@ -107,7 +107,7 @@ export const manifest = setupManifest({ marketingUrl: 'https://github.com/ggml-org/llama.cpp', donationUrl: null, description: { short, long }, - volumes: ['main'], + volumes: ['main', 'public'], images: { 'llama-cpp': mutable( imageConfigs[variant as keyof typeof imageConfigs] ?? diff --git a/startos/utils.ts b/startos/utils.ts index cdeed33..f982a70 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -1,9 +1,16 @@ +import { utils } from '@start9labs/start-sdk' + export const apiPort = 8080 export const apiHostId = 'api-multi' +export const apiKeyHostId = 'api-key' + export const uiUsername = 'admin' +export const generateApiKey = () => + utils.getDefaultString({ charset: 'a-z,A-Z,0-9', len: 32 }) + export const variant = (process.env.VARIANT || 'generic') as | 'generic' | 'nvidia' diff --git a/startos/versions/current.ts b/startos/versions/current.ts index 5f388b2..4b995a7 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,53 +1,33 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' export const current = VersionInfo.of({ - version: '11960:0', + version: '11960:1', releaseNotes: { - en_US: `Updated llama.cpp to build b11960 at the stable v0.8.0 release. - -- Adds LiquidAI LFM3 text, vision and audio models, DeepSeek V4.1 Flash, SenseNova U1 and other architectures. Compatible audio models gain realtime conversation and transcription APIs and a text-to-speech endpoint. -- The chat UI gains conversation search, conversation compaction and template-specific reasoning controls. Improves tool calling, model downloads, GPU performance and caching of CPU-resident MoE experts. -- Limits grammar recursion and rejects deeply nested JSON to prevent crashes. Existing model settings and downloaded GGUF weights need no conversion; custom saved slot caches may need to be recreated after updating. -- Updates the StartOS SDK to 3.1.1 with container-startup fixes. Retains the protective CA-store upgrade. - -[Full upstream release notes](https://github.com/ggml-org/llama.cpp/releases/tag/v0.8.0) -[Changes since the previous build](https://github.com/ggml-org/llama.cpp/compare/b11669...b11960)`, - es_ES: `Actualiza llama.cpp a la compilación b11960 de la versión estable v0.8.0. - -- Añade modelos LiquidAI LFM3 de texto, visión y audio, DeepSeek V4.1 Flash, SenseNova U1 y otras arquitecturas. Los modelos de audio compatibles incorporan API de conversación y transcripción en tiempo real y un endpoint de síntesis de voz. -- La interfaz de chat incorpora búsqueda y compactación de conversaciones y controles de razonamiento específicos de cada plantilla. Mejora las llamadas a herramientas, las descargas de modelos, el rendimiento de GPU y la caché de expertos MoE residentes en la CPU. -- Limita la recursión de las gramáticas y rechaza JSON con anidamiento excesivo para evitar fallos. La configuración del modelo y los pesos GGUF descargados no necesitan conversión; puede ser necesario recrear las cachés de ranuras guardadas mediante opciones personalizadas tras actualizar. -- Actualiza el SDK de StartOS a 3.1.1 con correcciones del arranque de contenedores. Mantiene la actualización protectora del almacén de certificados CA. - -[Notas completas de la versión original](https://github.com/ggml-org/llama.cpp/releases/tag/v0.8.0) -[Cambios desde la compilación anterior](https://github.com/ggml-org/llama.cpp/compare/b11669...b11960)`, - de_DE: `Aktualisiert llama.cpp auf Build b11960 der stabilen Veröffentlichung v0.8.0. - -- Ergänzt LiquidAI-LFM3-Modelle für Text, Bild und Audio, DeepSeek V4.1 Flash, SenseNova U1 und weitere Architekturen. Kompatible Audiomodelle erhalten APIs für Echtzeitgespräche und Transkription sowie einen Endpunkt für Sprachsynthese. -- Die Chat-Oberfläche erhält Gesprächssuche, Gesprächskomprimierung und vorlagenspezifische Reasoning-Steuerung. Verbessert Werkzeugaufrufe, Modelldownloads, GPU-Leistung und das Caching von MoE-Experten im CPU-Speicher. -- Begrenzt Grammatikrekursion und weist tief verschachteltes JSON zur Vermeidung von Abstürzen zurück. Modelleinstellungen und heruntergeladene GGUF-Gewichte benötigen keine Konvertierung; benutzerdefinierte gespeicherte Slot-Caches müssen nach dem Update möglicherweise neu erstellt werden. -- Aktualisiert das StartOS-SDK auf 3.1.1 mit Korrekturen beim Containerstart. Die schützende Aktualisierung des CA-Zertifikatsspeichers bleibt erhalten. - -[Vollständige Upstream-Veröffentlichungsnotizen](https://github.com/ggml-org/llama.cpp/releases/tag/v0.8.0) -[Änderungen seit dem vorherigen Build](https://github.com/ggml-org/llama.cpp/compare/b11669...b11960)`, - pl_PL: `Aktualizuje llama.cpp do kompilacji b11960 ze stabilnego wydania v0.8.0. - -- Dodaje modele LiquidAI LFM3 obsługujące tekst, obraz i dźwięk, DeepSeek V4.1 Flash, SenseNova U1 oraz inne architektury. Zgodne modele dźwiękowe zyskują API rozmów i transkrypcji w czasie rzeczywistym oraz endpoint syntezy mowy. -- Interfejs czatu zyskuje wyszukiwanie i kompresję rozmów oraz sterowanie rozumowaniem zależne od szablonu. Ulepsza wywoływanie narzędzi, pobieranie modeli, wydajność GPU i pamięć podręczną ekspertów MoE znajdujących się w pamięci CPU. -- Ogranicza rekurencję gramatyk i odrzuca głęboko zagnieżdżony JSON, aby zapobiegać awariom. Ustawienia modelu i pobrane wagi GGUF nie wymagają konwersji; po aktualizacji może być konieczne ponowne utworzenie zapisanych pamięci podręcznych slotów używanych z własnymi opcjami. -- Aktualizuje SDK StartOS do 3.1.1 z poprawkami uruchamiania kontenerów. Zachowuje ochronną aktualizację magazynu certyfikatów CA. - -[Pełne informacje o wydaniu projektu źródłowego](https://github.com/ggml-org/llama.cpp/releases/tag/v0.8.0) -[Zmiany od poprzedniej kompilacji](https://github.com/ggml-org/llama.cpp/compare/b11669...b11960)`, - fr_FR: `Met à jour llama.cpp vers la compilation b11960 de la version stable v0.8.0. - -- Ajoute les modèles LiquidAI LFM3 pour le texte, la vision et l’audio, DeepSeek V4.1 Flash, SenseNova U1 et d’autres architectures. Les modèles audio compatibles gagnent des API de conversation et de transcription en temps réel ainsi qu’un point d’accès de synthèse vocale. -- L’interface de discussion gagne la recherche et la compression des conversations ainsi que des contrôles de raisonnement propres aux modèles de conversation. Améliore les appels d’outils, les téléchargements de modèles, les performances GPU et le cache des experts MoE résidant en mémoire CPU. -- Limite la récursion des grammaires et rejette les objets JSON trop imbriqués pour éviter les plantages. Les réglages du modèle et les poids GGUF téléchargés ne nécessitent aucune conversion ; les caches d’emplacement enregistrés avec des options personnalisées peuvent devoir être recréés après la mise à jour. -- Met à jour le SDK StartOS vers 3.1.1 avec des corrections du démarrage des conteneurs. Conserve la mise à niveau protectrice du magasin de certificats CA. - -[Notes complètes de la version amont](https://github.com/ggml-org/llama.cpp/releases/tag/v0.8.0) -[Modifications depuis la compilation précédente](https://github.com/ggml-org/llama.cpp/compare/b11669...b11960)`, + en_US: `Adds an OpenAI-compatible API interface with its own API key, so other services and API clients can reach llama.cpp again. + +- Since StartOS 0.4.1, the web UI's password also protects llama.cpp's address inside the server. Services such as Open WebUI and DeepSeek Harness can't send that password, so their requests failed. +- The new interface takes the key shown by the API Key action, which can also replace it. Services on this server read the key automatically once they are updated to support it. +- The browser interface, now named Web UI, keeps its address and password.`, + es_ES: `Añade una interfaz API compatible con OpenAI con su propia clave de API, para que otros servicios y clientes de API vuelvan a llegar a llama.cpp. + +- Desde StartOS 0.4.1, la contraseña de la interfaz web también protege la dirección de llama.cpp dentro del servidor. Servicios como Open WebUI y DeepSeek Harness no pueden enviar esa contraseña, por lo que sus solicitudes fallaban. +- La nueva interfaz acepta la clave que muestra la acción Clave de API, que también puede reemplazarla. Los servicios de este servidor leen la clave automáticamente una vez actualizados para admitirla. +- La interfaz del navegador, ahora llamada Interfaz web, conserva su dirección y contraseña.`, + de_DE: `Fügt eine OpenAI-kompatible API-Schnittstelle mit eigenem API-Schlüssel hinzu, sodass andere Dienste und API-Clients llama.cpp wieder erreichen. + +- Seit StartOS 0.4.1 schützt das Passwort der Web-Oberfläche auch die Adresse von llama.cpp innerhalb des Servers. Dienste wie Open WebUI und DeepSeek Harness können dieses Passwort nicht senden, daher schlugen ihre Anfragen fehl. +- Die neue Schnittstelle akzeptiert den Schlüssel, den die Aktion „API-Schlüssel“ anzeigt und auch ersetzen kann. Dienste auf diesem Server lesen den Schlüssel automatisch, sobald sie dafür aktualisiert sind. +- Die Browser-Schnittstelle, jetzt „Web-Oberfläche“ genannt, behält Adresse und Passwort.`, + pl_PL: `Dodaje interfejs API zgodny z OpenAI z własnym kluczem API, dzięki czemu inne usługi i klienty API znów mogą łączyć się z llama.cpp. + +- Od StartOS 0.4.1 hasło interfejsu WWW chroni również adres llama.cpp wewnątrz serwera. Usługi takie jak Open WebUI i DeepSeek Harness nie potrafią wysłać tego hasła, więc ich żądania kończyły się błędem. +- Nowy interfejs przyjmuje klucz pokazywany przez akcję Klucz API, która może go też wymienić. Usługi na tym serwerze odczytują klucz automatycznie po aktualizacji, która to obsługuje. +- Interfejs przeglądarkowy, teraz nazwany Interfejs WWW, zachowuje adres i hasło.`, + fr_FR: `Ajoute une interface API compatible OpenAI avec sa propre clé d’API, pour que les autres services et clients d’API puissent de nouveau joindre llama.cpp. + +- Depuis StartOS 0.4.1, le mot de passe de l’interface web protège aussi l’adresse de llama.cpp à l’intérieur du serveur. Des services comme Open WebUI et DeepSeek Harness ne peuvent pas envoyer ce mot de passe, leurs requêtes échouaient donc. +- La nouvelle interface accepte la clé affichée par l’action Clé d’API, qui peut aussi la remplacer. Les services de ce serveur lisent la clé automatiquement une fois mis à jour pour la prendre en charge. +- L’interface du navigateur, désormais nommée Interface web, conserve son adresse et son mot de passe.`, }, migrations: { up: async ({ effects }) => {},