diff --git a/AGENTS.md b/AGENTS.md index 37d4130..49aa800 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,11 +18,17 @@ bare clone with no workspace, the full guide is at `; neither can be handed + to it as a hash. `startos/fileModels/store.json.ts` holds both on the `startos` + volume, which no subcontainer mounts, and `opencode.json` refers to a key as + `{env:…}` rather than carrying it. +- **`opencode.json` is written by the Configure Model Providers action, never + generated at startup.** OpenCode reloads that file live, so a provider change needs + no restart — but a new or changed key does, which is why `main.ts` reads + `providerKeys` reactively. Rebuild the `providers` map from the form on every save: + that is what makes leaving an entry out disconnect the provider. - **`startos/main.ts` mounts the `main` volume over the container's entire home** (`/root`), which is where OpenCode keeps sessions, provider credentials, cloned repositories, and projects. Narrowing the mountpoint drops user data from backups. diff --git a/README.md b/README.md index c7f9d4d..db2316c 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ The package declares two volumes. | Volume | Mount point | Contents | | --------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `main` | `/root` (read-write) | The container's entire home: sessions, credentials, repositories, projects, and OpenCode's own config, state, and cache. | -| `startos` | not mounted | StartOS-side state: `store.json`, holding the generated login password. | +| `startos` | not mounted | StartOS-side state: `store.json`, holding the generated login password and the configured providers' API keys. | `main` is mounted over the image's home directory, so everything OpenCode writes under `/root` persists across restarts and updates: @@ -68,31 +68,38 @@ under `/root` persists across restarts and updates: lost on restart; treat anything only in there as scratch. The `startos` volume is deliberately not mounted into `opencode-sub`, so the -running server never sees the password file — it receives the password through -the `OPENCODE_PASSWORD` environment variable instead. +running server never sees the file itself — it receives the login password as +`OPENCODE_PASSWORD` and each configured provider's API key as an +`OPENCODE_KEY_` variable instead. ## File Models -The package owns exactly one file model: `store.json` on the `startos` volume. +The package owns two file models. -| File | Format | Key | Seeded by | Rewritten by | -| -------------------- | ------ | --------------- | --------------------------------- | ---------------------------- | -| `startos/store.json` | JSON | `adminPassword` | the **Set Admin Password** action | the same action, on each run | +| File | Format | Keys | Seeded by | Rewritten by | +| ------------------------------------- | ------ | ------------------------------- | ---------------------------------------- | ---------------------------- | +| `startos/store.json` | JSON | `adminPassword`, `providerKeys` | the **Set Admin Password** action | the two actions, on each run | +| `main/.config/opencode/opencode.json` | JSON | `$schema`, `providers`, `model` | the **Configure Model Providers** action | the same action, on each run | `adminPassword` is stored in clear text because the server reads it verbatim from `OPENCODE_PASSWORD` and cannot be given a hash. There is no default: it is absent until the user runs the action, which is what the [task](#tasks) waits -for. +for. `providerKeys` maps a configured provider's id to its API key, and has no +default either. -The schema is permissive (`z.looseObject`, every key optional), so the file is -never rewritten by the package on its own — only the action writes it, and it -only ever merges the one key. A hand edit to `adminPassword` therefore survives: -the running server watches the file and restarts with the new value. Nothing -else re-asserts or normalizes the file. +Both schemas are permissive (`z.looseObject`, every key optional), and the +package writes each file only from an action — never at startup, and never to +normalize or repair it. A hand edit therefore survives: -OpenCode's **own** configuration file (`~/.config/opencode/opencode.json`, or -`opencode.jsonc`, on the `main` volume) is not modeled by this package. OpenCode -writes and reads it, and the package neither seeds nor rewrites it. +- In `store.json`, the running server watches the file and restarts with the new + value. +- In `opencode.json`, OpenCode watches the file and reloads it without a restart. + The package leaves every key it does not own — including whatever OpenCode + writes there itself — as it found it. + +`opencode.json` is OpenCode's own global configuration, at the path OpenCode +reads it from. The package models it so the Configure Model Providers action can +write provider entries; it is not generated, replaced, or seeded otherwise. ## Dependencies @@ -124,14 +131,15 @@ complete and nothing to configure on disk. 3. The user opens the `ui` interface, signs in on the web page with the username `opencode` and that password. -Model providers are not preconfigured; connecting one is part of using the app, -not part of install. Nothing upstream is disabled or skipped, and the package -adds no files OpenCode did not already expect. +Model providers are not preconfigured; connecting one happens after install, +through the **Configure Model Providers** action rather than during it. Nothing +upstream is disabled or skipped, and the package adds no files OpenCode did not +already expect. ## Actions -One user-facing action. The OS carries its id, name, description, warning, and -status gating; what follows is what the metadata cannot express. +Two user-facing actions. The OS carries each one's id, name, description, +warning, and status gating; what follows is what the metadata cannot express. ### `set-admin-password` — Set Admin Password @@ -149,6 +157,27 @@ status gating; what follows is what the metadata cannot express. - **Outputs.** The username `opencode` (unmasked, copyable) and the new password (masked, copyable). +### `configure-providers` — Configure Model Providers + +- **When to run it.** After install, and whenever the set of models OpenCode can + use changes. It is the only way to connect a model: the packaged OpenCode web + interface has no provider screen of its own. +- **What it changes.** For each provider in the form, an entry in the `providers` + map of `main/.config/opencode/opencode.json`, and its API key under + `providerKeys` in `startos/store.json`. The `model` key is set to the provider + whose **Default** toggle is on, or dropped if that provider is removed. A new + or changed API key restarts the service, because the server receives it as an + `OPENCODE_KEY_` environment variable; a change that touches no key is + picked up by the running server without a restart. +- **Cost.** Seconds. Nothing outside the two files above is touched, and no + session, repository, or project is affected. +- **Repeat safety.** The form is prefilled from the current configuration and is + the authority for it: what the form lists is what the file holds afterwards, so + saving it unchanged changes nothing and leaving a provider out disconnects it. + An empty form therefore disconnects every provider. +- **Outputs.** Each provider with the model IDs it serves, and the default model + when one is set. + ## Tasks One task, raised by `startos/init/watchCredentials.ts`. @@ -207,8 +236,12 @@ required. 2. **The `opencode pair` pairing-link flow is not wired up.** Sign in with the password from the **Set Admin Password** action instead of a one-time pairing link or QR code. -3. **Model provider credentials are not preconfigured.** Connect a provider in - the web UI after install; the package ships no provider configuration. +3. **Model providers are configured from StartOS, not from the app.** The + packaged OpenCode web interface has no provider screen, so providers are added + with the **Configure Model Providers** action. It covers OpenAI-compatible + endpoints — your own vLLM, LM Studio, or Ollama server, or a hosted API such + as OpenRouter. Provider families outside that shape are not configured by the + package. 4. **OpenCode's self-updater is disabled** in the container. The server is updated by updating the StartOS package, not from inside the app. 5. **The container runs as `root`.** The upstream image does, and the package does @@ -232,14 +265,17 @@ volumes: startos: unmounted file_models: - startos/store.json + - main/.config/opencode/opencode.json startos_managed_env_vars: - OPENCODE_PASSWORD - OPENCODE_DISABLE_AUTOUPDATE + - OPENCODE_KEY_ dependencies: none interfaces: ui: { type: ui, port: 4096 } actions: - set-admin-password + - configure-providers tasks: - { action: set-admin-password, severity: critical } health_checks: diff --git a/instructions.md b/instructions.md index 4a37a65..13b22a0 100644 --- a/instructions.md +++ b/instructions.md @@ -30,9 +30,9 @@ StartOS server. You use it from a browser: 3. On the **Connect to a server** screen, click **Use password**. The server address is already filled in — leave it as it is — paste the password, and click **Connect**. -4. In the web app, open **Settings → Providers** and connect a model provider - (an API key, or your OpenCode Console account). OpenCode can't do anything - until it has a model to use. +4. Before OpenCode can answer anything it needs a model to use. From StartOS, run + the **Configure Model Providers** action and add your provider — see + [Connecting a model provider](#connecting-a-model-provider). 5. Back on the home screen, click **Add project** and choose a folder to work in. Pick a folder inside your home directory (`~/…`, shown as `root` when you browse from `/`) — that is where your server keeps data across restarts. @@ -52,6 +52,35 @@ open past sessions, and change settings from the sidebar. The same address also serves the HTTP API under `/api/*`, if you want to drive the server from your own scripts. +### Connecting a model provider + +OpenCode talks to any OpenAI-compatible endpoint — a vLLM, LM Studio, or Ollama +server you run yourself, or a hosted API such as OpenRouter. You add one from +StartOS, not from the web app, with the **Configure Model Providers** action. +Each entry asks for: + +- **ID** — a short name used to identify the provider (`vllm`). Lowercase + letters, digits, and dashes. +- **Name** — how the provider appears in OpenCode's model list (`Lab vLLM`). +- **Base URL** — the endpoint's API root, including `/v1`, for example + `http://192.168.1.50:8000/v1`. +- **API Key** — only if the endpoint checks one. Leave it blank for a local + server that accepts any request. It is kept on the StartOS side and is never + written into the configuration file. +- **Models** — one entry per model ID the endpoint serves, for example + `glm-5.3`. If you are not sure of the exact IDs, the endpoint lists them under + `/v1/models`. +- **Default** — turn this on to make the first model in the list the one new + sessions start on. + +Save, and the models are available in the web app right away — refresh the page +if the picker still looks empty. + +Run the action again to change an endpoint or add another provider, and delete a +provider by removing its entry from the list. The API key of a provider you have +already configured is filled in when the form opens, so leave it as it is unless +you are replacing it. + ### Changing the password Run **Set Admin Password** again at any time to generate a new password. The @@ -71,6 +100,10 @@ login password back as they were. password from the **Set Admin Password** action instead. - **The server does not update itself.** OpenCode's in-app update check is turned off; update the service by updating this package in StartOS. +- **Providers are configured from StartOS, not from the app.** The web app in this + version has no provider screen — use the **Configure Model Providers** action. + It connects OpenAI-compatible endpoints, such as vLLM, LM Studio, Ollama, and + OpenRouter. ### If you publish the interface through a tunnel diff --git a/startos/actions/configureProviders.ts b/startos/actions/configureProviders.ts new file mode 100644 index 0000000..4d69d18 --- /dev/null +++ b/startos/actions/configureProviders.ts @@ -0,0 +1,283 @@ +import { opencodeJson } from '../fileModels/opencode.json' +import { storeJson } from '../fileModels/store.json' +import { i18n } from '../i18n' +import { sdk } from '../sdk' +import { openAiCompatiblePackage, providerKeyEnvVar } from '../utils' + +const { InputSpec, List, Value } = sdk + +const configSchema = 'https://opencode.ai/config.json' + +// The config file is read back as `unknown` for `providers` and `model` (see the +// file model), so everything crossing that boundary is narrowed here. +const asRecord = (value: unknown): Record => + value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {} + +const asString = (value: unknown): string | undefined => + typeof value === 'string' && value !== '' ? value : undefined + +// `model` is `"provider/model"` in the file, but an object once OpenCode has +// resolved it, so both spellings are read. +const defaultModelOf = (model: unknown): string | undefined => { + const direct = asString(model) + if (direct) return direct + const { providerID, model: modelID } = asRecord(model) + const provider = asString(providerID) + const id = asString(modelID) + return provider && id ? `${provider}/${id}` : undefined +} + +const providerShape = InputSpec.of({ + id: Value.text({ + name: i18n('ID'), + description: i18n( + 'A short identifier for this provider, used to select it. Lowercase letters, digits, and dashes, for example `vllm`.', + ), + required: true, + default: null, + maxLength: 48, + patterns: [ + { + regex: '^[a-z0-9][a-z0-9-]*$', + description: i18n( + 'Lowercase letters, digits, and dashes, starting with a letter or digit', + ), + }, + ], + }), + name: Value.text({ + name: i18n('Name'), + description: i18n( + 'How the provider is named in the OpenCode model list, for example `Lab vLLM`.', + ), + required: true, + default: null, + maxLength: 64, + }), + baseURL: Value.text({ + name: i18n('Base URL'), + description: i18n( + 'The OpenAI-compatible API base URL, including `/v1`, for example `http://192.168.1.50:8000/v1`.', + ), + required: true, + default: null, + patterns: [ + { + // The SDK anchors a pattern with `^…$` unless both are already present, + // so a leading-only `^` would demand the whole value be `http://`. + regex: 'https?://.+', + description: i18n('Must start with http:// or https://'), + }, + ], + }), + apiKey: Value.text({ + name: i18n('API Key'), + description: i18n( + 'Only if the endpoint checks it. Leave blank for a local server that accepts any request.', + ), + required: false, + default: null, + masked: true, + }), + models: Value.list( + List.text( + { + name: i18n('Models'), + description: i18n( + 'One entry per model ID the endpoint serves, for example `glm-5.3`. The endpoint lists them under `/v1/models`.', + ), + default: [], + minLength: 1, + maxLength: null, + }, + { placeholder: i18n('Model ID') }, + ), + ), + isDefault: Value.toggle({ + name: i18n('Default'), + description: i18n('Use the first model listed above for new sessions.'), + default: false, + }), +}) + +const inputSpec = InputSpec.of({ + providers: Value.list( + List.obj( + { + name: i18n('Providers'), + description: i18n( + 'One entry per endpoint. Remove an entry to disconnect that provider.', + ), + default: [], + minLength: null, + maxLength: null, + }, + { + spec: providerShape, + displayAs: 'name', + uniqueBy: 'id', + }, + ), + ), +}) + +export const configureProviders = sdk.Action.withInput( + // id + 'configure-providers', + + // metadata + { + name: i18n('Configure Model Providers'), + description: i18n( + 'Connect the OpenAI-compatible model providers OpenCode can use — your own vLLM, LM Studio, or Ollama server, or a hosted API.', + ), + warning: null, + allowedStatuses: 'any', + group: null, + visibility: 'enabled', + }, + + // input spec + inputSpec, + + // prefill — the providers already configured, with their keys read back from + // the `startos` volume (the config file only holds a reference to each key) + async ({ effects }) => { + const config = await opencodeJson.read().once() + const providerKeys = await storeJson.read((s) => s.providerKeys).once() + const defaultModel = defaultModelOf(config?.model) + const defaultProvider = defaultModel?.split('/')[0] + + return { + providers: Object.entries(config?.providers ?? {}).map(([id, value]) => { + const provider = asRecord(value) + const settings = asRecord(provider.settings) + const models = asRecord(provider.models) + const key = providerKeys?.[id] + + return { + id, + name: asString(provider.name) ?? id, + baseURL: asString(settings.baseURL) ?? '', + apiKey: asString(key) ?? null, + models: Object.keys(models), + isDefault: id === defaultProvider, + } + }), + } + }, + + // execution + async ({ effects, input }) => { + // The keys go to the `startos` volume first: it triggers the restart that + // gives the server the new `OPENCODE_KEY_*` variables, and the config write + // that follows is picked up live by the running server either way. + // + // `update`, not `merge`: a merge would leave the key of a provider the user + // just removed in place, silently keeping it in the server's environment. + const providerKeys = Object.fromEntries( + input.providers + .filter((provider) => provider.apiKey) + .map((provider) => [provider.id, provider.apiKey]), + ) + await storeJson.update(effects, (current) => ({ + ...current, + providerKeys, + })) + + const marked = input.providers.find((provider) => provider.isDefault) + const model = marked ? `${marked.id}/${marked.models[0]}` : undefined + + await opencodeJson.update(effects, (current) => { + const config = current ?? {} + const existing = asRecord(config.providers) + const previousDefault = defaultModelOf(config.model) + // A default pointing at a provider this save drops would leave new + // sessions on a model nothing serves, so it is dropped with it. The check + // is against the form, not the file — the provider may be in the file and + // already removed from the form. + const keepsDefault = + previousDefault !== undefined && + input.providers.some( + (provider) => provider.id === previousDefault.split('/')[0], + ) + + const providers: Record = {} + for (const provider of input.providers) { + const previous = asRecord(existing[provider.id]) + const settings = asRecord(previous.settings) + const previousModels = asRecord(previous.models) + + if (provider.apiKey) { + settings.apiKey = `{env:${providerKeyEnvVar(provider.id)}}` + } else { + delete settings.apiKey + } + settings.baseURL = provider.baseURL + + const models: Record = {} + for (const modelId of provider.models) { + models[modelId] = { + ...asRecord(previousModels[modelId]), + name: modelId, + modelID: modelId, + } + } + + providers[provider.id] = { + ...previous, + name: provider.name, + package: asString(previous.package) ?? openAiCompatiblePackage, + settings, + models, + } + } + + return { + ...config, + $schema: configSchema, + providers, + model: marked ? model : keepsDefault ? previousDefault : undefined, + } + }) + + return { + version: '1', + title: i18n('Model Providers'), + message: i18n( + 'Saved. These providers are available in OpenCode, and new sessions start on the default model if one is set.', + ), + result: { + type: 'group', + value: [ + ...input.providers.map((provider) => ({ + type: 'single' as const, + name: provider.name, + description: provider.id, + value: provider.models.join(', '), + masked: false, + copyable: true, + qr: false, + launchable: false, + })), + ...(marked && model + ? [ + { + type: 'single' as const, + name: i18n('Default Model'), + description: null, + value: model, + masked: false, + copyable: true, + qr: false, + launchable: false, + }, + ] + : []), + ], + }, + } + }, +) diff --git a/startos/actions/index.ts b/startos/actions/index.ts index 9055a34..599d403 100644 --- a/startos/actions/index.ts +++ b/startos/actions/index.ts @@ -1,4 +1,7 @@ import { sdk } from '../sdk' +import { configureProviders } from './configureProviders' import { setAdminPassword } from './setAdminPassword' -export const actions = sdk.Actions.of().addAction(setAdminPassword) +export const actions = sdk.Actions.of() + .addAction(setAdminPassword) + .addAction(configureProviders) diff --git a/startos/fileModels/opencode.json.ts b/startos/fileModels/opencode.json.ts new file mode 100644 index 0000000..48bcf48 --- /dev/null +++ b/startos/fileModels/opencode.json.ts @@ -0,0 +1,31 @@ +import { FileHelper, z } from '@start9labs/start-sdk' +import { sdk } from '../sdk' + +// OpenCode's global configuration, at the path OpenCode itself reads it on the +// `main` volume (which is mounted at `/root`). The package models it so the +// Configure Model Providers action can add providers without a shell. +// +// `providers` and `model` are deliberately left unvalidated beyond their +// top-level type: `providers` is a map the action rebuilds, and `model` is +// either `"provider/model"` or the object OpenCode resolves it to. Validating +// their contents would let one hand-edited entry make `merge()` throw, which +// fails the action rather than repairing the file. +const shape = z.looseObject({ + $schema: z.string().optional().catch(undefined), + model: z.unknown().optional().catch(undefined), + providers: z.record(z.string(), z.unknown()).optional().catch(undefined), +}) + +export const opencodeJson = FileHelper.json( + { base: sdk.volumes.main, subpath: '.config/opencode/opencode.json' }, + shape, +) + +export type OpencodeProvider = { + name?: unknown + package?: unknown + settings?: unknown + models?: unknown +} + +export type OpencodeConfig = z.infer diff --git a/startos/fileModels/store.json.ts b/startos/fileModels/store.json.ts index 0bd4196..f7047d9 100644 --- a/startos/fileModels/store.json.ts +++ b/startos/fileModels/store.json.ts @@ -7,6 +7,11 @@ const shape = z.looseObject({ // so it cannot be stored as a hash. It lives on the `startos` volume, which no // subcontainer mounts, so the service never sees the file itself. adminPassword: z.string().optional().catch(undefined), + // API keys for configured model providers, keyed by the provider id. `main.ts` + // passes each one to the server as `OPENCODE_KEY_`, which is the variable + // the generated entry in OpenCode's own config refers to — so the key reaches + // the server without ever being written to the config file on `main`. + providerKeys: z.record(z.string(), z.unknown()).optional().catch(undefined), }) export const storeJson = FileHelper.json( diff --git a/startos/i18n/dictionaries/default.ts b/startos/i18n/dictionaries/default.ts index 5dc706d..ea50576 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -20,6 +20,30 @@ const dict = { // init/watchCredentials.ts 'Set the admin password before signing in': 11, + + // actions/configureProviders.ts + 'Configure Model Providers': 12, + 'Connect the OpenAI-compatible model providers OpenCode can use — your own vLLM, LM Studio, or Ollama server, or a hosted API.': 13, + Providers: 14, + 'One entry per endpoint. Remove an entry to disconnect that provider.': 15, + ID: 16, + 'A short identifier for this provider, used to select it. Lowercase letters, digits, and dashes, for example `vllm`.': 17, + 'Lowercase letters, digits, and dashes, starting with a letter or digit': 18, + Name: 19, + 'How the provider is named in the OpenCode model list, for example `Lab vLLM`.': 20, + 'Base URL': 21, + 'The OpenAI-compatible API base URL, including `/v1`, for example `http://192.168.1.50:8000/v1`.': 22, + 'Must start with http:// or https://': 23, + 'API Key': 24, + 'Only if the endpoint checks it. Leave blank for a local server that accepts any request.': 25, + Models: 26, + 'One entry per model ID the endpoint serves, for example `glm-5.3`. The endpoint lists them under `/v1/models`.': 27, + 'Model ID': 28, + Default: 29, + 'Use the first model listed above for new sessions.': 30, + 'Model Providers': 31, + 'Saved. These providers are available in OpenCode, and new sessions start on the default model if one is set.': 32, + 'Default Model': 33, } as const /** diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index 6d3a387..cca666a 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -14,6 +14,28 @@ export default { 9: 'Nombre de usuario', 10: 'Contraseña', 11: 'Establece la contraseña de administrador antes de iniciar sesión', + 12: 'Configurar proveedores de modelos', + 13: 'Conecta los proveedores de modelos compatibles con OpenAI que OpenCode puede usar: tu propio servidor vLLM, LM Studio u Ollama, o una API alojada.', + 14: 'Proveedores', + 15: 'Una entrada por endpoint. Elimina una entrada para desconectar ese proveedor.', + 16: 'ID', + 17: 'Un identificador corto para este proveedor, usado para seleccionarlo. Letras minúsculas, dígitos y guiones, por ejemplo `vllm`.', + 18: 'Letras minúsculas, dígitos y guiones, empezando por una letra o un dígito', + 19: 'Nombre', + 20: 'Cómo se nombra el proveedor en la lista de modelos de OpenCode, por ejemplo `Lab vLLM`.', + 21: 'URL base', + 22: 'La URL base de la API compatible con OpenAI, incluido `/v1`, por ejemplo `http://192.168.1.50:8000/v1`.', + 23: 'Debe empezar por http:// o https://', + 24: 'Clave de API', + 25: 'Solo si el endpoint la comprueba. Déjala en blanco para un servidor local que acepte cualquier solicitud.', + 26: 'Modelos', + 27: 'Una entrada por cada ID de modelo que sirve el endpoint, por ejemplo `glm-5.3`. El endpoint los lista en `/v1/models`.', + 28: 'ID del modelo', + 29: 'Predeterminado', + 30: 'Usa el primer modelo de la lista para las sesiones nuevas.', + 31: 'Proveedores de modelos', + 32: 'Guardado. Estos proveedores están disponibles en OpenCode, y las sesiones nuevas empiezan con el modelo predeterminado si hay uno definido.', + 33: 'Modelo predeterminado', }, de_DE: { 0: 'Weboberfläche', @@ -28,6 +50,28 @@ export default { 9: 'Benutzername', 10: 'Passwort', 11: 'Legen Sie das Administratorpasswort fest, bevor Sie sich anmelden', + 12: 'Modellanbieter konfigurieren', + 13: 'Verbinden Sie die OpenAI-kompatiblen Modellanbieter, die OpenCode nutzen kann – Ihren eigenen vLLM-, LM-Studio- oder Ollama-Server oder eine gehostete API.', + 14: 'Anbieter', + 15: 'Ein Eintrag pro Endpunkt. Entfernen Sie einen Eintrag, um diesen Anbieter zu trennen.', + 16: 'ID', + 17: 'Eine kurze Kennung für diesen Anbieter, mit der er ausgewählt wird. Kleinbuchstaben, Ziffern und Bindestriche, zum Beispiel `vllm`.', + 18: 'Kleinbuchstaben, Ziffern und Bindestriche, beginnend mit einem Buchstaben oder einer Ziffer', + 19: 'Name', + 20: 'Wie der Anbieter in der Modellliste von OpenCode heißt, zum Beispiel `Lab vLLM`.', + 21: 'Basis-URL', + 22: 'Die Basis-URL der OpenAI-kompatiblen API, einschließlich `/v1`, zum Beispiel `http://192.168.1.50:8000/v1`.', + 23: 'Muss mit http:// oder https:// beginnen', + 24: 'API-Schlüssel', + 25: 'Nur wenn der Endpunkt ihn prüft. Lassen Sie das Feld leer bei einem lokalen Server, der jede Anfrage akzeptiert.', + 26: 'Modelle', + 27: 'Ein Eintrag pro Modell-ID, die der Endpunkt anbietet, zum Beispiel `glm-5.3`. Der Endpunkt listet sie unter `/v1/models` auf.', + 28: 'Modell-ID', + 29: 'Standard', + 30: 'Verwendet das erste aufgeführte Modell für neue Sitzungen.', + 31: 'Modellanbieter', + 32: 'Gespeichert. Diese Anbieter stehen in OpenCode zur Verfügung, und neue Sitzungen starten mit dem Standardmodell, sofern eines festgelegt ist.', + 33: 'Standardmodell', }, pl_PL: { 0: 'Interfejs webowy', @@ -42,6 +86,28 @@ export default { 9: 'Nazwa użytkownika', 10: 'Hasło', 11: 'Ustaw hasło administratora przed zalogowaniem', + 12: 'Konfiguruj dostawców modeli', + 13: 'Podłącz dostawców modeli zgodnych z OpenAI, z których może korzystać OpenCode — własny serwer vLLM, LM Studio lub Ollama albo hostowane API.', + 14: 'Dostawcy', + 15: 'Jeden wpis na endpoint. Usuń wpis, aby odłączyć tego dostawcę.', + 16: 'Identyfikator', + 17: 'Krótki identyfikator tego dostawcy, używany do jego wyboru. Małe litery, cyfry i myślniki, na przykład `vllm`.', + 18: 'Małe litery, cyfry i myślniki, zaczynając od litery lub cyfry', + 19: 'Nazwa', + 20: 'Jak dostawca jest nazwany na liście modeli OpenCode, na przykład `Lab vLLM`.', + 21: 'Adres bazowy', + 22: 'Bazowy adres API zgodnego z OpenAI, wraz z `/v1`, na przykład `http://192.168.1.50:8000/v1`.', + 23: 'Musi zaczynać się od http:// lub https://', + 24: 'Klucz API', + 25: 'Tylko jeśli endpoint go sprawdza. Pozostaw puste dla lokalnego serwera, który akceptuje każde żądanie.', + 26: 'Modele', + 27: 'Jeden wpis na identyfikator modelu udostępnianego przez endpoint, na przykład `glm-5.3`. Endpoint wymienia je pod `/v1/models`.', + 28: 'Identyfikator modelu', + 29: 'Domyślny', + 30: 'Używa pierwszego modelu z listy dla nowych sesji.', + 31: 'Dostawcy modeli', + 32: 'Zapisano. Ci dostawcy są dostępni w OpenCode, a nowe sesje zaczynają od modelu domyślnego, jeśli został ustawiony.', + 33: 'Model domyślny', }, fr_FR: { 0: 'Interface web', @@ -56,5 +122,27 @@ export default { 9: "Nom d'utilisateur", 10: 'Mot de passe', 11: 'Définissez le mot de passe administrateur avant de vous connecter', + 12: 'Configurer les fournisseurs de modèles', + 13: "Connectez les fournisseurs de modèles compatibles OpenAI qu'OpenCode peut utiliser — votre propre serveur vLLM, LM Studio ou Ollama, ou une API hébergée.", + 14: 'Fournisseurs', + 15: 'Une entrée par point de terminaison. Supprimez une entrée pour déconnecter ce fournisseur.', + 16: 'Identifiant', + 17: 'Un identifiant court pour ce fournisseur, utilisé pour le sélectionner. Lettres minuscules, chiffres et tirets, par exemple `vllm`.', + 18: 'Lettres minuscules, chiffres et tirets, commençant par une lettre ou un chiffre', + 19: 'Nom', + 20: "Le nom du fournisseur dans la liste des modèles d'OpenCode, par exemple `Lab vLLM`.", + 21: 'URL de base', + 22: "L'URL de base de l'API compatible OpenAI, `/v1` inclus, par exemple `http://192.168.1.50:8000/v1`.", + 23: 'Doit commencer par http:// ou https://', + 24: 'Clé API', + 25: 'Uniquement si le point de terminaison la vérifie. Laissez vide pour un serveur local qui accepte toute requête.', + 26: 'Modèles', + 27: 'Une entrée par identifiant de modèle servi par le point de terminaison, par exemple `glm-5.3`. Le point de terminaison les liste sous `/v1/models`.', + 28: 'Identifiant du modèle', + 29: 'Par défaut', + 30: 'Utilise le premier modèle de la liste pour les nouvelles sessions.', + 31: 'Fournisseurs de modèles', + 32: "Enregistré. Ces fournisseurs sont disponibles dans OpenCode, et les nouvelles sessions démarrent sur le modèle par défaut s'il est défini.", + 33: 'Modèle par défaut', }, } satisfies Record diff --git a/startos/main.ts b/startos/main.ts index cad401a..13c452b 100644 --- a/startos/main.ts +++ b/startos/main.ts @@ -1,7 +1,7 @@ import { storeJson } from './fileModels/store.json' import { i18n } from './i18n' import { sdk } from './sdk' -import { uiPort } from './utils' +import { providerKeyEnvVar, uiPort } from './utils' export const main = sdk.setupMain(async ({ effects }) => { // Reactive: when the password changes (set or rotated by the action), the @@ -20,6 +20,20 @@ export const main = sdk.setupMain(async ({ effects }) => { throw new Error('The admin password has not been set') } + // Reactive: saving a provider with an API key changes this map, which rebuilds + // the daemon spec and restarts the server so it gains the `OPENCODE_KEY_*` + // variables the provider entries in OpenCode's own config refer to. Provider + // entries themselves need no restart — OpenCode reloads that file live. + const providerKeys = + (await storeJson.read((s) => s.providerKeys).const(effects)) ?? {} + const providerEnv = Object.fromEntries( + Object.entries(providerKeys) + .filter( + (entry): entry is [string, string] => typeof entry[1] === 'string', + ) + .map(([id, key]) => [providerKeyEnvVar(id), key]), + ) + return sdk.Daemons.of(effects).addDaemon('opencode', { subcontainer: sdk.SubContainer.of( effects, @@ -49,6 +63,7 @@ export const main = sdk.setupMain(async ({ effects }) => { OPENCODE_PASSWORD: adminPassword, // Never let the container try to replace its own binary. OPENCODE_DISABLE_AUTOUPDATE: '1', + ...providerEnv, }, }, ready: { diff --git a/startos/utils.ts b/startos/utils.ts index 23f1d9e..3aac37f 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -2,3 +2,14 @@ // exported on. Kept in one place so startos/main.ts (which launches it and // health-checks it) and startos/interfaces.ts (which exposes it) cannot drift. export const uiPort = 4096 + +// The upstream package OpenCode uses for any OpenAI-compatible endpoint — a +// self-hosted vLLM, LM Studio, or Ollama server, or a hosted gateway. +export const openAiCompatiblePackage = + '@opencode/ai/providers/openai-compatible' + +// The variable a provider's API key is passed to the server in, derived from the +// provider id the user chose. Those ids are restricted to `[a-z0-9-]` by the +// configure-providers form, so two ids can never collide on one variable. +export const providerKeyEnvVar = (providerId: string) => + `OPENCODE_KEY_${providerId.toUpperCase().replace(/[^A-Z0-9]/g, '_')}` diff --git a/startos/versions/current.ts b/startos/versions/current.ts index 3be2a2d..9d4bf28 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,13 +1,18 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' export const current = VersionInfo.of({ - version: '2.4.1:0', + version: '2.4.1:1', releaseNotes: { - en_US: 'Initial release of the OpenCode package for StartOS.', - es_ES: 'Lanzamiento inicial del paquete OpenCode para StartOS.', - de_DE: 'Erstveröffentlichung des OpenCode-Pakets für StartOS.', - pl_PL: 'Pierwsze wydanie pakietu OpenCode dla StartOS.', - fr_FR: 'Version initiale du paquet OpenCode pour StartOS.', + en_US: + 'Add a Configure Model Providers action, which connects an OpenAI-compatible provider — your own vLLM, LM Studio, or Ollama server, or a hosted API — without a shell.', + es_ES: + 'Añade una acción Configurar proveedores de modelos, que conecta un proveedor compatible con OpenAI —tu propio servidor vLLM, LM Studio u Ollama, o una API alojada— sin usar la terminal.', + de_DE: + 'Fügt die Aktion „Modellanbieter konfigurieren" hinzu, die einen OpenAI-kompatiblen Anbieter verbindet – Ihren eigenen vLLM-, LM-Studio- oder Ollama-Server oder eine gehostete API – ganz ohne Shell.', + pl_PL: + 'Dodaje akcję „Konfiguruj dostawców modeli", która podłącza dostawcę zgodnego z OpenAI — własny serwer vLLM, LM Studio lub Ollama albo hostowane API — bez użycia terminala.', + fr_FR: + "Ajoute l'action « Configurer les fournisseurs de modèles », qui connecte un fournisseur compatible OpenAI — votre propre serveur vLLM, LM Studio ou Ollama, ou une API hébergée — sans passer par le shell.", }, migrations: { up: async ({ effects }) => {},