Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-2190]): correct OpenCode models map to nest under provider.ollama (bare ids)

Adam Eivy01eda4c57359
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3983ff9c3f..1c96717092 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## CoS Agents
-- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time with the effective model declared, fixing the TUI eval path for local Ollama models.
+- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time, declaring the provider's configured models (plus the model being run) under `provider.ollama.models` with bare ids — the exact shape OpenCode's `@ai-sdk/openai-compatible` provider validates `--model ollama/<id>` against. Applied across every OpenCode spawn path (CoS CLI/TUI agents, the toolkit CLI/TUI runners, and the light fire-and-collect CLI run), and a migration backfills existing installs' `data/providers.json` so a configured model's map is persisted too. Fixes the TUI eval path for local Ollama models.
- **An explicit per-task model pin is now always honored — no more silent, expensive downgrades.** When you set a specific model on a CoS task, PortOS validated it against the provider's `models` list and, on any mismatch, *silently fell back to the provider's default (heaviest) model*. Because `claude-code-tui` lists the dated id `claude-haiku-4-5-20251001` while `claude-code` lists the undated `claude-haiku-4-5`, picking "haiku" on the TUI provider quietly ran **Opus** instead. Explicit user-specified models are now passed through to the CLI even when they're not in the convenience list (the CLIs accept any valid id; a genuine typo surfaces as a provider error rather than a costly silent substitution). Auto-selected models still fall back to the tier default as before.
- **Worktree tasks now default to opening a PR instead of auto-merging to your default branch.** A CoS task run in an isolated worktree with "Open PR" off merges its commits straight back to the main development branch on completion — fine for trusted agents, dangerous for unreviewed local-model work. Creating a worktree task now defaults "Open PR" on (in the UI, enabling Worktree checks it; via the API, a worktree user-task without an explicit `openPR` defaults to `true`). You can still turn it off per-task for a quick auto-merge, and internal automation (autopilot, self-improvement) keeps its existing auto-merge behavior so nothing starts silently waiting on a human to merge a PR.
diff --git a/scripts/migrations/164-opencode-ollama-config-models-map.js b/scripts/migrations/164-opencode-ollama-config-models-map.js
index 026b634a47..48f512a217 100644
--- a/scripts/migrations/164-opencode-ollama-config-models-map.js
+++ b/scripts/migrations/164-opencode-ollama-config-models-map.js
@@ -10,7 +10,7 @@
* silently produced zero output.
*
* The primary fix builds `OPENCODE_CONFIG_CONTENT` dynamically at spawn time
- * (`withOpencodeConfigEnv` in `server/lib/providerModels.js`), folding in the
+ * (`buildOpencodeEnvVars` in `server/lib/opencodeConfig.js`), folding in the
* provider's configured models + the model being run. This migration keeps the
* STORED config honest/consistent for installs that already configured models
* (e.g. a `defaultModel` or a populated `models[]`): it injects the matching
diff --git a/server/lib/README.md b/server/lib/README.md
index 39208c6df5..db17fa10a3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -93,7 +93,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptPartials.js` | Mustache-style partial expansion. |
| `mediaModels.js` | Single source of truth for image/video model metadata. |
| `providerModels.js` | Provider model resolution sentinel + helpers. |
-| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` with the models map for Ollama-backed OpenCode providers. Fixes --model rejection. |
+| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
| `runners.js` | Image-runner family constants. |
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index b82732e544..274303aeaf 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -18,7 +18,7 @@
import { spawn } from 'child_process';
import { buildCliArgs } from './cliProviderArgs.js';
-import { withOpencodeConfigEnv } from './providerModels.js';
+import { buildOpencodeEnvVars } from './opencodeConfig.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';
/**
@@ -98,11 +98,11 @@ export function runCliProviderPrompt(args = {}) {
// CLAUDECODE is deleted from the child env so a nested invocation doesn't
// think it's running inside the parent Claude Code session.
- // withOpencodeConfigEnv rebuilds OPENCODE_CONFIG_CONTENT with a declared
- // models map for OpenCode Ollama providers (no-op otherwise) so the injected
- // `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.
- // effectiveProvider carries the per-call model as defaultModel.
- const childEnv = { ...process.env, ...withOpencodeConfigEnv(effectiveProvider) };
+ // buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared
+ // models map for OpenCode Ollama providers (empty/no-op otherwise) so the
+ // injected `--model ollama/<id>` isn't rejected as "not valid" — see
+ // issue-2190. effectiveProvider carries the per-call model as defaultModel.
+ const childEnv = { ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(effectiveProvider, effectiveProvider.defaultModel) };
delete childEnv.CLAUDECODE;
// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap
diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.js
index 9bd5c53897..91871b6e34 100644
--- a/server/lib/opencodeConfig.js
+++ b/server/lib/opencodeConfig.js
@@ -1,74 +1,112 @@
/**
* OpenCode configuration helpers.
*
- * OpenCode (the CLI) requires a models map in its config for any --model flag
- * to be accepted. The shipped OPENCODE_CONFIG_CONTENT was missing this map,
- * causing every --model to be rejected as "not valid". This module builds the
- * config dynamically at spawn time from the effective model.
+ * OpenCode (the CLI) requires every model addressable via `--model` to be
+ * declared in its config. For a custom `@ai-sdk/openai-compatible` provider
+ * (how we wire the local Ollama daemon), models live UNDER the provider entry
+ * as `provider.<id>.models.<bareModelId>` — there is no top-level `models` map
+ * in OpenCode's schema, and the keys are the BARE model id (the part after the
+ * `provider/` namespace), NOT the `ollama/`-prefixed form passed to `--model`.
+ *
+ * The shipped `OPENCODE_CONFIG_CONTENT` declared the Ollama provider but omitted
+ * that models map, so OpenCode (>=1.17) rejected every `--model ollama/<id>` as
+ * "Model ollama/… is not valid" — the pasted prompt sat in the input box, the
+ * agent produced zero output, and the idle reaper marked it complete (issue
+ * -2190). This module builds the config dynamically at spawn time, declaring the
+ * provider's configured models (+ the model being run) under
+ * `provider.ollama.models` with bare ids.
*/
-import { isOpencodeCommand, prefixOpencodeModel } from './providerModels.js';
+import { isOpencodeCommand } from './providerModels.js';
/**
- * Base OpenCode config structure for Ollama-backed providers (permission +
- * provider block). The models map is added dynamically per-run.
+ * Base OpenCode provider entry for the local Ollama daemon (openai-compatible).
+ * The per-run models map is added under this by `buildOpencodeConfig`.
*/
-const OPENCODE_OLLAMA_BASE_CONFIG = {
- permission: 'allow',
- provider: {
- ollama: {
- npm: '@ai-sdk/openai-compatible',
- name: 'Ollama (local)',
- options: { baseURL: 'http://localhost:11434/v1' },
- },
- },
+const OPENCODE_OLLAMA_BASE_PROVIDER = {
+ npm: '@ai-sdk/openai-compatible',
+ name: 'Ollama (local)',
+ options: { baseURL: 'http://localhost:11434/v1' },
};
+// Strip a leading `ollama/` namespace so a model id can key the config `models`
+// map (which lives under the `ollama` provider — keys are bare ids). Idempotent
+// for an already-bare id. A `/`-bearing Ollama id (`hf.co/user/model:tag`)
+// namespaced as `ollama/hf.co/...` strips back to the correct bare key since
+// only the leading namespace is removed.
+const stripOllamaPrefix = (id) =>
+ typeof id === 'string' && id.startsWith('ollama/') ? id.slice('ollama/'.length) : id;
+
/**
- * Build an OpenCode config object with the models map populated from the
- * effective model. Returns the base config (no models) if no model is provided.
+ * Normalize an id or list of ids to the unique, non-empty, prefix-stripped bare
+ * model ids that key the OpenCode `models` map.
+ * @param {string|string[]|null|undefined} models
+ * @returns {string[]}
+ */
+export function toBareModelIds(models) {
+ const list = Array.isArray(models) ? models : [models];
+ return [...new Set(
+ list
+ .filter((m) => typeof m === 'string' && m.length > 0)
+ .map(stripOllamaPrefix)
+ .filter((m) => typeof m === 'string' && m.length > 0),
+ )];
+}
+
+/**
+ * Build an OpenCode config object declaring the given models under the Ollama
+ * provider. Accepts a single id or a list (bare or `ollama/`-prefixed — both are
+ * normalized to bare keys). Returns the base config with no `models` key when no
+ * usable id is provided (identical to the shipped base — no regression).
*
- * @param {string|null|undefined} prefixedModel - Model id with ollama/ prefix
+ * @param {string|string[]|null|undefined} models
* @returns {object} OpenCode config object
*/
-export function buildOpencodeConfig(prefixedModel) {
- if (!prefixedModel) {
- return { ...OPENCODE_OLLAMA_BASE_CONFIG };
+export function buildOpencodeConfig(models) {
+ const bareIds = toBareModelIds(models);
+ const ollama = { ...OPENCODE_OLLAMA_BASE_PROVIDER };
+ if (bareIds.length > 0) {
+ ollama.models = Object.fromEntries(
+ bareIds.map((id) => [id, { name: id, tool_call: true }]),
+ );
}
- return {
- ...OPENCODE_OLLAMA_BASE_CONFIG,
- models: {
- [prefixedModel]: { name: prefixedModel, tool_call: true },
- },
- };
+ return { permission: 'allow', provider: { ollama } };
}
/**
- * Build OPENCODE_CONFIG_CONTENT env var value for an Ollama-backed OpenCode
- * provider. Returns the JSON string ready to set as an env var.
+ * Build the `OPENCODE_CONFIG_CONTENT` env var value (JSON string) declaring the
+ * given models under the Ollama provider.
*
- * @param {string|null|undefined} prefixedModel - Model id with ollama/ prefix
- * @returns {string} JSON string for OPENCODE_CONFIG_CONTENT env var
+ * @param {string|string[]|null|undefined} models
+ * @returns {string} JSON string for OPENCODE_CONFIG_CONTENT
*/
-export function buildOpencodeConfigContent(prefixedModel) {
- return JSON.stringify(buildOpencodeConfig(prefixedModel));
+export function buildOpencodeConfigContent(models) {
+ return JSON.stringify(buildOpencodeConfig(models));
}
/**
* Build dynamic env vars for an OpenCode Ollama provider spawn. Returns an
- * object with OPENCODE_CONFIG_CONTENT if the provider is Ollama-backed OpenCode,
- * otherwise returns an empty object.
+ * object with `OPENCODE_CONFIG_CONTENT` (models map declared) for Ollama-backed
+ * OpenCode providers, otherwise an empty object (caller keeps existing env).
+ *
+ * The declared models are the union of the provider's configured models, its
+ * default model, and the model being run this invocation — so whichever
+ * `--model ollama/<id>` the spawner passes is always accepted.
*
- * @param {{command?:string, ollamaBacked?:boolean}} provider
- * @param {string|null|undefined} model - Raw model id (will be prefixed)
- * @returns {{OPENCODE_CONFIG_CONTENT?: string}} Env vars to merge
+ * @param {{command?:string, ollamaBacked?:boolean, models?:string[], defaultModel?:string|null}} provider
+ * @param {string|null|undefined} model - the model being run (may differ from defaultModel)
+ * @returns {{OPENCODE_CONFIG_CONTENT?: string}} env vars to merge
*/
export function buildOpencodeEnvVars(provider, model) {
if (!isOpencodeCommand(provider?.command) || provider?.ollamaBacked !== true) {
return {};
}
- const prefixedModel = prefixOpencodeModel(provider, model);
+ const ids = [
+ ...(Array.isArray(provider?.models) ? provider.models : []),
+ provider?.defaultModel,
+ model,
+ ];
return {
- OPENCODE_CONFIG_CONTENT: buildOpencodeConfigContent(prefixedModel),
+ OPENCODE_CONFIG_CONTENT: buildOpencodeConfigContent(ids),
};
}
diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.js
index a7cb5f8d22..a091ad26e7 100644
--- a/server/lib/opencodeConfig.test.js
+++ b/server/lib/opencodeConfig.test.js
@@ -3,95 +3,120 @@ import {
buildOpencodeConfig,
buildOpencodeConfigContent,
buildOpencodeEnvVars,
+ toBareModelIds,
} from './opencodeConfig.js';
+describe('toBareModelIds', () => {
+ it('strips the ollama/ namespace, drops empties, and dedupes', () => {
+ expect(toBareModelIds(['ollama/qwen2.5:7b', 'qwen2.5:7b', '', null, 'llama3.1:8b']))
+ .toEqual(['qwen2.5:7b', 'llama3.1:8b']);
+ });
+
+ it('accepts a single id', () => {
+ expect(toBareModelIds('ollama/mistral:7b')).toEqual(['mistral:7b']);
+ });
+
+ it('keeps a slash-bearing id intact after stripping only the leading namespace', () => {
+ expect(toBareModelIds('ollama/hf.co/user/model:tag')).toEqual(['hf.co/user/model:tag']);
+ });
+});
+
describe('buildOpencodeConfig', () => {
- it('returns base config without models map when no model provided', () => {
+ it('returns base config without a models map when no model provided', () => {
const cfg = buildOpencodeConfig(null);
expect(cfg.permission).toBe('allow');
expect(cfg.provider.ollama).toMatchObject({
npm: '@ai-sdk/openai-compatible',
name: 'Ollama (local)',
});
+ // no top-level models key, and none under the provider
expect(cfg.models).toBeUndefined();
+ expect(cfg.provider.ollama.models).toBeUndefined();
});
- it('includes the prefixed model in the models map', () => {
+ it('declares the BARE model id under provider.ollama.models (not a top-level map)', () => {
const cfg = buildOpencodeConfig('ollama/qwen2.5:7b');
- expect(cfg.models).toEqual({
- 'ollama/qwen2.5:7b': { name: 'ollama/qwen2.5:7b', tool_call: true },
+ // OpenCode has no top-level models map — it must be nested per-provider
+ expect(cfg.models).toBeUndefined();
+ expect(cfg.provider.ollama.models).toEqual({
+ 'qwen2.5:7b': { name: 'qwen2.5:7b', tool_call: true },
});
});
- it('preserves the model id exactly as passed', () => {
+ it('declares multiple models with bare keys', () => {
+ const cfg = buildOpencodeConfig(['ollama/qwen2.5:7b', 'llama3.1:8b']);
+ expect(Object.keys(cfg.provider.ollama.models).sort()).toEqual(['llama3.1:8b', 'qwen2.5:7b']);
+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toEqual({ name: 'qwen2.5:7b', tool_call: true });
+ });
+
+ it('preserves a slash-bearing bare model id', () => {
const cfg = buildOpencodeConfig('ollama/hf.co/user/model:tag');
- expect(cfg.models['ollama/hf.co/user/model:tag']).toBeDefined();
+ expect(cfg.provider.ollama.models['hf.co/user/model:tag']).toBeDefined();
});
});
describe('buildOpencodeConfigContent', () => {
- it('returns valid JSON', () => {
+ it('returns valid JSON with the models map nested under the provider', () => {
const json = buildOpencodeConfigContent('ollama/qwen2.5:7b');
expect(() => JSON.parse(json)).not.toThrow();
const parsed = JSON.parse(json);
- expect(parsed.models['ollama/qwen2.5:7b']).toEqual({
- name: 'ollama/qwen2.5:7b',
+ expect(parsed.provider.ollama.models['qwen2.5:7b']).toEqual({
+ name: 'qwen2.5:7b',
tool_call: true,
});
});
- it('serializes the base config for null model', () => {
- const json = buildOpencodeConfigContent(null);
- const parsed = JSON.parse(json);
+ it('serializes the base config (no models) for null model', () => {
+ const parsed = JSON.parse(buildOpencodeConfigContent(null));
expect(parsed.permission).toBe('allow');
- expect(parsed.models).toBeUndefined();
+ expect(parsed.provider.ollama.models).toBeUndefined();
});
});
describe('buildOpencodeEnvVars', () => {
it('returns empty object for non-OpenCode providers', () => {
- const result = buildOpencodeEnvVars({ command: 'claude' }, 'claude-opus-4');
- expect(result).toEqual({});
+ expect(buildOpencodeEnvVars({ command: 'claude' }, 'claude-opus-4')).toEqual({});
});
it('returns empty object for OpenCode providers without ollamaBacked', () => {
- const result = buildOpencodeEnvVars(
+ expect(buildOpencodeEnvVars(
{ command: 'opencode', ollamaBacked: false },
- 'anthropic/claude-sonnet'
- );
- expect(result).toEqual({});
+ 'anthropic/claude-sonnet',
+ )).toEqual({});
});
- it('returns dynamic OPENCODE_CONFIG_CONTENT for Ollama-backed OpenCode', () => {
- const result = buildOpencodeEnvVars(
- { command: 'opencode', ollamaBacked: true },
- 'qwen2.5:7b'
- );
+ it('declares the run model (bare) under provider.ollama.models', () => {
+ const result = buildOpencodeEnvVars({ command: 'opencode', ollamaBacked: true, models: [] }, 'qwen2.5:7b');
expect(result.OPENCODE_CONFIG_CONTENT).toBeDefined();
const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
- // prefixOpencodeModel adds the ollama/ prefix
- expect(cfg.models['ollama/qwen2.5:7b']).toEqual({
- name: 'ollama/qwen2.5:7b',
- tool_call: true,
- });
+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toEqual({ name: 'qwen2.5:7b', tool_call: true });
+ });
+
+ it('unions the provider models, defaultModel, and the run model (deduped, bare)', () => {
+ const provider = {
+ command: 'opencode', ollamaBacked: true,
+ models: ['qwen2.5:7b', 'llama3.1:8b'], defaultModel: 'llama3.1:8b',
+ };
+ const cfg = JSON.parse(buildOpencodeEnvVars(provider, 'mistral:7b').OPENCODE_CONFIG_CONTENT);
+ expect(Object.keys(cfg.provider.ollama.models).sort()).toEqual(['llama3.1:8b', 'mistral:7b', 'qwen2.5:7b']);
});
- it('handles absolute path to opencode binary', () => {
- const result = buildOpencodeEnvVars(
- { command: '/opt/homebrew/bin/opencode', ollamaBacked: true },
- 'qwen2.5:7b'
- );
+ it('handles an absolute path to the opencode binary', () => {
+ const result = buildOpencodeEnvVars({ command: '/opt/homebrew/bin/opencode', ollamaBacked: true, models: [] }, 'qwen2.5:7b');
const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
- expect(cfg.models['ollama/qwen2.5:7b']).toBeDefined();
+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toBeDefined();
});
- it('handles null model gracefully', () => {
- const result = buildOpencodeEnvVars(
- { command: 'opencode', ollamaBacked: true },
- null
- );
+ it('handles null model gracefully (no models map when nothing is configured)', () => {
+ const result = buildOpencodeEnvVars({ command: 'opencode', ollamaBacked: true, models: [] }, null);
expect(result.OPENCODE_CONFIG_CONTENT).toBeDefined();
const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
- expect(cfg.models).toBeUndefined();
+ expect(cfg.provider.ollama.models).toBeUndefined();
+ });
+
+ it('falls back to defaultModel when no run model is passed', () => {
+ const result = buildOpencodeEnvVars({ command: 'opencode', ollamaBacked: true, models: [], defaultModel: 'qwen2.5:7b' }, null);
+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);
+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toBeDefined();
});
});
diff --git a/server/services/runner.js b/server/services/runner.js
index e559fe139a..87c7d70852 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -6,7 +6,8 @@ import { spawn } from 'child_process';
import { writeFile, readFile } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
-import { hasModelFlag, extractBakedModel, withOpencodeConfigEnv } from '../lib/providerModels.js';
+import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
+import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
import { buildCliArgs } from '../lib/cliProviderArgs.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
@@ -204,10 +205,10 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
// Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted
// agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.
- // withOpencodeConfigEnv rebuilds OPENCODE_CONFIG_CONTENT with a declared
- // models map for OpenCode Ollama providers (no-op otherwise) so the injected
+ // buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared models
+ // map for OpenCode Ollama providers (empty/no-op otherwise) so the injected
// `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.
- const childEnv = { ...process.env, ...withOpencodeConfigEnv(provider, provider.defaultModel) };
+ const childEnv = { ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(provider, provider.defaultModel) };
delete childEnv.CLAUDECODE;
Object.assign(childEnv, agentGuardEnv(childEnv));