diff --git a/AGENTS.md b/AGENTS.md index 1f8d51a..69f4316 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,8 +11,13 @@ bare clone with no workspace, the full guide is at `; don't write either into a config file. - **Keep `main` mounted over the whole of `/root`.** OpenCode spreads its state across `~/.local`, `~/.config` and `~/.cache`, and users keep projects under `~`; a narrower mount drops data from restarts and backups. +- **The Configure Model Providers action owns only the providers it writes.** They are + the `opencode.json` entries carrying `package: @opencode/ai/providers/openai-compatible`; + rebuild those from the form, and leave every other entry — and a `model` that names + none of them — as you found it. diff --git a/README.md b/README.md index 744dc10..9852191 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,40 @@ 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` | JSONC | `$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. +Comments and trailing commas are accepted, but saving reserializes the file as +JSON without its comments or formatting. ## Dependencies @@ -124,13 +133,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. -The package writes no OpenCode configuration, so provider and model setup is -upstream's own, in the web app. +Model providers are not preconfigured. Hosted providers connect in the web app +itself, under **Settings → Providers**; the **Configure Model Providers** action +adds an OpenAI-compatible endpoint the web app's own catalog has no entry for. The +package adds no files OpenCode did not already expect of it. ## 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 @@ -147,6 +158,33 @@ 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.** When OpenCode should use an OpenAI-compatible endpoint the + web app's own catalog has no entry for — a vLLM, LM Studio, or Ollama server on + your network. Hosted providers connect in the web app itself, under + **Settings → Providers**. +- **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`. Entries carrying + `package: @opencode/ai/providers/openai-compatible` are rebuilt; an ID collision + with any other entry is rejected before either file changes. Every other entry, + and a `model` that names none of the managed entries, is left as it was. The + `model` key is set when a provider's **Default** toggle is on, or dropped when it + names a provider this save removes. 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 with the OpenAI-compatible entries and + is the authority for them: leaving one out disconnects it, and an empty form + disconnects them all. A literal API key on an existing entry is prefilled and + moved into `providerKeys` on save. Providers using another package are not + listed and are not touched. +- **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`. @@ -226,14 +264,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 fec625e..df66bb7 100644 --- a/instructions.md +++ b/instructions.md @@ -29,10 +29,13 @@ 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. Choose a model. Out of the box OpenCode uses a free model hosted by - OpenCode, so your prompts and code are sent to OpenCode's servers. To use - your own provider instead, open **Settings → Providers** and connect it (an - API key, or your OpenCode Console account). +4. Choose a model. Out of the box OpenCode uses a free model hosted by OpenCode, + so your prompts and code are sent to OpenCode's servers. To use a hosted + provider instead, open **Settings → Providers** in the web app and connect it + (an API key, or your OpenCode Console account). For an OpenAI-compatible + endpoint the app's catalog cannot reach — your own vLLM, LM Studio, or Ollama + server — run the **Configure Model Providers** action from StartOS; 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 +55,38 @@ 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 + +Hosted providers connect inside the web app, under **Settings → Providers**. The +**Configure Model Providers** action is for an OpenAI-compatible endpoint the +app's catalog has no entry for — a vLLM, LM Studio, or Ollama server on your +network. Run it from StartOS; 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. OpenAI-compatible endpoints you configured by hand are +also listed, with any literal API key filled in. Providers connected in the web +app are not affected. If an ID is already in use outside this list, choose a +different ID. + ### Changing the password Run **Set Admin Password** again at any time to generate a new password. The diff --git a/package-lock.json b/package-lock.json index 90ae35a..5913b16 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,7 +6,8 @@ "": { "name": "opencode-startos", "dependencies": { - "@start9labs/start-sdk": "4.1.0" + "@start9labs/start-sdk": "4.1.0", + "jsonc-parser": "3.3.1" } }, "node_modules/@eslint-community/eslint-utils": { @@ -1206,6 +1207,12 @@ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "license": "MIT" }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "license": "MIT" + }, "node_modules/keyv": { "version": "4.5.4", "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", diff --git a/package.json b/package.json index 488b02a..ba339ce 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,8 @@ { "name": "opencode-startos", "dependencies": { - "@start9labs/start-sdk": "4.1.0" + "@start9labs/start-sdk": "4.1.0", + "jsonc-parser": "3.3.1" }, "overrides": { "@start9labs/start-sdk": "$@start9labs/start-sdk" diff --git a/startos/actions/configureProviders.ts b/startos/actions/configureProviders.ts new file mode 100644 index 0000000..78dccf8 --- /dev/null +++ b/startos/actions/configureProviders.ts @@ -0,0 +1,309 @@ +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' + +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 + +// Other provider packages remain untouched, including when form IDs collide. +const isManaged = (provider: Record): boolean => + asString(provider.package) === openAiCompatiblePackage + +// `model` is `"provider/model"` in the file, or the object OpenCode resolves it to. +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. + 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 OpenAI-compatible entries; each key comes from a literal in the + // entry, or from the `startos` volume the action stored it in. + async ({ effects }) => { + const config = await opencodeJson.read().once() + const providerKeys = await storeJson.read((s) => s.providerKeys).once() + const defaultProvider = defaultModelOf(config?.model)?.split('/')[0] + + return { + providers: Object.entries(config?.providers ?? {}) + .map(([id, value]) => [id, asRecord(value)] as const) + .filter(([, provider]) => isManaged(provider)) + .map(([id, provider]) => { + const settings = asRecord(provider.settings) + const configuredKey = asString(settings.apiKey) + return { + id, + name: asString(provider.name) ?? id, + baseURL: asString(settings.baseURL) ?? '', + apiKey: + configuredKey && !/\{(?:env|file):/.test(configuredKey) + ? configuredKey + : (asString(providerKeys?.[id]) ?? null), + models: Object.keys(asRecord(provider.models)), + isDefault: id === defaultProvider, + } + }), + } + }, + + // execution + async ({ effects, input }) => { + const providerKeys = Object.fromEntries( + input.providers + .filter((provider) => provider.apiKey) + .map((provider) => [provider.id, provider.apiKey]), + ) + const marked = input.providers.find((provider) => provider.isDefault) + let shownModel: string | undefined + + await opencodeJson.update(effects, async (current) => { + const config = current ?? {} + const existing = asRecord(config.providers) + + // Only the entries this action owns are rebuilt. Every other entry — one the + // user or OpenCode added — is copied through untouched. + const providers: Record = {} + const managedIds = new Set() + for (const [id, value] of Object.entries(existing)) { + const provider = asRecord(value) + if (isManaged(provider)) managedIds.add(id) + else providers[id] = value + } + + for (const provider of input.providers) { + if ( + Object.hasOwn(existing, provider.id) && + !managedIds.has(provider.id) + ) { + throw new Error( + i18n( + 'Provider ID "${id}" belongs to a provider configured outside this action. Choose another ID.', + { id: provider.id }, + ), + ) + } + + const previous = asRecord(existing[provider.id]) + const settings = asRecord(previous.settings) + const previousModels = asRecord(previous.models) + + settings.baseURL = provider.baseURL + if (provider.apiKey) { + settings.apiKey = `{env:${providerKeyEnvVar(provider.id)}}` + } else { + delete settings.apiKey + } + + 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: openAiCompatiblePackage, + settings, + models, + } + } + + // `model` is left as it was unless this save sets it, or it names a provider + // this save removes. + const previousDefault = defaultModelOf(config.model) + const previousProvider = previousDefault?.split('/')[0] + shownModel = previousDefault + let model: unknown = config.model + if (marked) { + const next = `${marked.id}/${marked.models[0]}` + model = next + shownModel = next + } else if ( + previousProvider !== undefined && + managedIds.has(previousProvider) && + !input.providers.some((provider) => provider.id === previousProvider) + ) { + model = undefined + shownModel = undefined + } + + await storeJson.update(effects, (current) => ({ + ...current, + providerKeys, + })) + + return { + ...config, + $schema: configSchema, + providers, + model, + } + }) + + 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, + })), + ...(shownModel + ? [ + { + type: 'single' as const, + name: i18n('Default Model'), + description: null, + value: shownModel, + 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..c1e8ab8 --- /dev/null +++ b/startos/fileModels/opencode.json.ts @@ -0,0 +1,38 @@ +import { FileHelper, z } from '@start9labs/start-sdk' +import { parse, type ParseError } from 'jsonc-parser' +import { i18n } from '../i18n' +import { sdk } from '../sdk' + +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), +}) + +// OpenCode accepts comments and trailing commas in `opencode.json`. +export const opencodeJson = FileHelper.raw( + { base: sdk.volumes.main, subpath: '.config/opencode/opencode.json' }, + (config: OpencodeConfig) => JSON.stringify(config, null, 2), + (text) => { + const errors: ParseError[] = [] + const config: unknown = parse(text, errors, { allowTrailingComma: true }) + if (errors.length) { + throw new Error( + i18n( + 'The OpenCode configuration contains invalid JSONC. Fix opencode.json before configuring providers.', + ), + ) + } + return config + }, + (config) => shape.parse(config), +) + +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 6b5e276..534a43b 100644 --- a/startos/fileModels/store.json.ts +++ b/startos/fileModels/store.json.ts @@ -3,6 +3,9 @@ import { sdk } from '../sdk' const shape = z.looseObject({ adminPassword: z.string().optional().catch(undefined), + // API keys for the providers the Configure Model Providers action writes, keyed + // by provider id; `main.ts` passes each to the server as `OPENCODE_KEY_`. + 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..cbb6a8e 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -20,6 +20,32 @@ 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, + 'Provider ID "${id}" belongs to a provider configured outside this action. Choose another ID.': 34, + 'The OpenCode configuration contains invalid JSONC. Fix opencode.json before configuring providers.': 35, } as const /** diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index 6d3a387..6d5e4fa 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -14,6 +14,30 @@ 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', + 34: 'El ID de proveedor "${id}" pertenece a un proveedor configurado fuera de esta acción. Elige otro ID.', + 35: 'La configuración de OpenCode contiene JSONC no válido. Corrige opencode.json antes de configurar los proveedores.', }, de_DE: { 0: 'Weboberfläche', @@ -28,6 +52,30 @@ 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', + 34: 'Die Anbieter-ID „${id}“ gehört zu einem außerhalb dieser Aktion konfigurierten Anbieter. Wählen Sie eine andere ID.', + 35: 'Die OpenCode-Konfiguration enthält ungültiges JSONC. Korrigieren Sie opencode.json, bevor Sie Anbieter konfigurieren.', }, pl_PL: { 0: 'Interfejs webowy', @@ -42,6 +90,30 @@ 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', + 34: 'Identyfikator dostawcy „${id}” należy do dostawcy skonfigurowanego poza tą akcją. Wybierz inny identyfikator.', + 35: 'Konfiguracja OpenCode zawiera nieprawidłowy JSONC. Popraw opencode.json przed skonfigurowaniem dostawców.', }, fr_FR: { 0: 'Interface web', @@ -56,5 +128,29 @@ 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', + 34: 'L’identifiant de fournisseur « ${id} » appartient à un fournisseur configuré en dehors de cette action. Choisissez un autre identifiant.', + 35: 'La configuration OpenCode contient du JSONC invalide. Corrigez opencode.json avant de configurer les fournisseurs.', }, } satisfies Record diff --git a/startos/main.ts b/startos/main.ts index a486a5c..a078865 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 }) => { const adminPassword = await storeJson @@ -12,6 +12,18 @@ export const main = sdk.setupMain(async ({ effects }) => { throw new Error('The admin password has not been set') } + // Reactive: a key change rebuilds the daemon and restarts the server so it gains + // the new `OPENCODE_KEY_*` variable. A provider entry alone needs no restart. + 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, @@ -35,6 +47,7 @@ export const main = sdk.setupMain(async ({ effects }) => { env: { OPENCODE_PASSWORD: adminPassword, OPENCODE_DISABLE_AUTOUPDATE: '1', + ...providerEnv, }, }, ready: { diff --git a/startos/utils.ts b/startos/utils.ts index b464446..0af7554 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -1 +1,11 @@ export const uiPort = 4096 + +// The package OpenCode uses for any OpenAI-compatible endpoint, and the marker the +// Configure Model Providers action uses to recognize the entries it owns. +export const openAiCompatiblePackage = + '@opencode/ai/providers/openai-compatible' + +// The variable a provider's API key reaches the server in, derived from its id +// (restricted to `[a-z0-9-]` by the form, so ids 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 }) => {},