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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-2190]): build OpenCode Ollama config with a models map at spawn time
Adam Eivy163f7a592c5a
diff --git a/scripts/migrations/164-opencode-ollama-config-models-map.js b/scripts/migrations/164-opencode-ollama-config-models-map.jsnew file mode 100644index 0000000000..026b634a47--- /dev/null+++ b/scripts/migrations/164-opencode-ollama-config-models-map.js@@ -0,0 +1,117 @@+/**+ * Backfill the OpenCode Ollama providers' inline config with a declared+ * `models` map (issue-2190).+ *+ * Background: the OpenCode Ollama providers (`opencode-ollama`,+ * `opencode-ollama-tui`, shipped by migrations 149/152) declare the Ollama+ * daemon in `OPENCODE_CONFIG_CONTENT` but omit a `models` map. OpenCode+ * (>=1.17) rejects any `--model ollama/<id>` whose `<id>` isn't declared under+ * `provider.ollama.models` ("Model ollama/… is not valid") — so every run+ * silently produced zero output.+ *+ * The primary fix builds `OPENCODE_CONFIG_CONTENT` dynamically at spawn time+ * (`withOpencodeConfigEnv` in `server/lib/providerModels.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+ * `models` map so the persisted config no longer lies about which models are+ * valid. When a provider has no models configured yet, the stored config is+ * left untouched — the dynamic spawn build supplies the map at runtime.+ *+ * Purely a config rewrite; providers, active provider, and every other field+ * stay untouched. Idempotent: re-running with the map already present is a+ * no-op. Frozen historical record — later default changes ride their own+ * migrations rather than mutating this one.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++const PROVIDERS_REL_PATH = 'data/providers.json';+const TARGET_IDS = ['opencode-ollama', 'opencode-ollama-tui'];++// Strip a leading `ollama/` namespace so a model id keys the config `models`+// map (which lives under the `ollama` provider — keys are bare ids). Mirrors+// stripOllamaPrefix in server/lib/providerModels.js.+const stripOllamaPrefix = (id) =>+ typeof id === 'string' && id.startsWith('ollama/') ? id.slice('ollama/'.length) : id;++// Collect the unique, prefix-stripped model ids a provider might address.+function collectModelIds(provider) {+ const ids = [...(Array.isArray(provider?.models) ? provider.models : []), provider?.defaultModel]+ .filter((m) => typeof m === 'string' && m.length > 0)+ .map(stripOllamaPrefix)+ .filter((m) => typeof m === 'string' && m.length > 0);+ return [...new Set(ids)];+}++export default {+ async up({ rootDir }) {+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install builds OpenCode config dynamically at spawn)`);+ return;+ }++ let config;+ try {+ config = JSON.parse(raw);+ } catch (err) {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);+ return;+ }++ if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);+ return;+ }++ let changed = false;++ for (const id of TARGET_IDS) {+ const provider = config.providers[id];+ if (!provider || typeof provider !== 'object') continue;++ const stored = provider.envVars?.OPENCODE_CONFIG_CONTENT;+ if (typeof stored !== 'string' || stored.length === 0) continue;++ const ids = collectModelIds(provider);+ if (ids.length === 0) {+ console.log(`ℹ️ ${PROVIDERS_REL_PATH}: ${id} has no models configured — leaving stored config (dynamic spawn build supplies the map)`);+ continue;+ }++ let cfg;+ try {+ cfg = JSON.parse(stored);+ } catch {+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: ${id} OPENCODE_CONFIG_CONTENT is not valid JSON — skipping`);+ continue;+ }+ if (!cfg || typeof cfg !== 'object') continue;+ if (!cfg.provider || typeof cfg.provider !== 'object') cfg.provider = {};+ if (!cfg.provider.ollama || typeof cfg.provider.ollama !== 'object') {+ cfg.provider.ollama = { npm: '@ai-sdk/openai-compatible', name: 'Ollama (local)', options: { baseURL: 'http://localhost:11434/v1' } };+ }++ const modelsMap = Object.fromEntries(ids.map((m) => [m, { name: m, tool_call: true }]));+ const nextContent = JSON.stringify({ ...cfg, provider: { ...cfg.provider, ollama: { ...cfg.provider.ollama, models: modelsMap } } });++ if (nextContent !== stored) {+ provider.envVars.OPENCODE_CONFIG_CONTENT = nextContent;+ changed = true;+ console.log(`📝 ${PROVIDERS_REL_PATH}: ${id} — declared ${ids.length} model(s) in OPENCODE_CONFIG_CONTENT`);+ }+ }++ if (changed) {+ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);+ } else {+ console.log(`✅ ${PROVIDERS_REL_PATH}: OpenCode Ollama config models map already up to date — no change`);+ }+ },+};diff --git a/scripts/migrations/164-opencode-ollama-config-models-map.test.js b/scripts/migrations/164-opencode-ollama-config-models-map.test.jsnew file mode 100644index 0000000000..8973b38300--- /dev/null+++ b/scripts/migrations/164-opencode-ollama-config-models-map.test.js@@ -0,0 +1,143 @@+/**+ * Test for migration 164 — backfill the OpenCode Ollama providers' inline+ * config with a declared `models` map (issue-2190). Picked up by+ * server/vitest.config.js's `../scripts/**\/*.test.js` glob.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './164-opencode-ollama-config-models-map.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const BASE_CONFIG = '{"permission":"allow","provider":{"ollama":{"npm":"@ai-sdk/openai-compatible","name":"Ollama (local)","options":{"baseURL":"http://localhost:11434/v1"}}}}';++const opencodeProvider = (overrides = {}) => ({+ id: 'opencode-ollama',+ type: 'cli',+ command: 'opencode',+ ollamaBacked: true,+ models: [],+ defaultModel: null,+ envVars: { OPENCODE_CONFIG_CONTENT: BASE_CONFIG },+ ...overrides,+});++describe('migration 164 — OpenCode Ollama config models map', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-164-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('injects a models map from a configured defaultModel', async () => {+ writeJson(providersPath, {+ providers: { 'opencode-ollama': opencodeProvider({ defaultModel: 'qwen2.5:7b' }) },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ const cfg = JSON.parse(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(cfg.provider.ollama.models).toEqual({ 'qwen2.5:7b': { name: 'qwen2.5:7b', tool_call: true } });+ // base config preserved+ expect(cfg.permission).toBe('allow');+ expect(cfg.provider.ollama.options.baseURL).toBe('http://localhost:11434/v1');+ });++ it('unions the models array + defaultModel across both providers', async () => {+ writeJson(providersPath, {+ providers: {+ 'opencode-ollama': opencodeProvider({ models: ['qwen2.5:7b', 'llama3.1:8b'], defaultModel: 'qwen2.5:7b' }),+ 'opencode-ollama-tui': opencodeProvider({ id: 'opencode-ollama-tui', type: 'tui', models: ['mistral:7b'] }),+ },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ const cli = JSON.parse(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(Object.keys(cli.provider.ollama.models).sort()).toEqual(['llama3.1:8b', 'qwen2.5:7b']);+ const tui = JSON.parse(out.providers['opencode-ollama-tui'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(Object.keys(tui.provider.ollama.models)).toEqual(['mistral:7b']);+ });++ it('strips the ollama/ namespace from stored ids', async () => {+ writeJson(providersPath, {+ providers: { 'opencode-ollama': opencodeProvider({ models: ['ollama/qwen2.5:7b'] }) },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ const cfg = JSON.parse(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toBeDefined();+ expect(cfg.provider.ollama.models['ollama/qwen2.5:7b']).toBeUndefined();+ });++ it('leaves the stored config untouched when no models are configured', async () => {+ writeJson(providersPath, {+ providers: { 'opencode-ollama': opencodeProvider() },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ expect(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT).toBe(BASE_CONFIG);+ });++ it('is idempotent — a second run makes no further change', async () => {+ writeJson(providersPath, {+ providers: { 'opencode-ollama': opencodeProvider({ defaultModel: 'qwen2.5:7b' }) },+ });++ await migration.up({ rootDir });+ const first = readFileSync(providersPath, 'utf-8');+ await migration.up({ rootDir });+ const second = readFileSync(providersPath, 'utf-8');+ expect(second).toBe(first);+ });++ it('leaves unrelated providers and active provider untouched', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: {+ 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' },+ 'opencode-ollama': opencodeProvider({ defaultModel: 'qwen2.5:7b' }),+ },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ expect(out.activeProvider).toBe('claude-code');+ expect(out.providers['claude-code']).toEqual({ id: 'claude-code', type: 'cli', command: 'claude' });+ });++ it('skips gracefully when providers.json is missing', async () => {+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });++ it('skips a provider whose OPENCODE_CONFIG_CONTENT is not valid JSON', async () => {+ writeJson(providersPath, {+ providers: {+ 'opencode-ollama': opencodeProvider({ defaultModel: 'qwen2.5:7b', envVars: { OPENCODE_CONFIG_CONTENT: 'not json' } }),+ },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ expect(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT).toBe('not json');+ });+});diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 6d8d9c05c3..b82732e544 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -18,6 +18,7 @@import { spawn } from 'child_process';import { buildCliArgs } from './cliProviderArgs.js';+import { withOpencodeConfigEnv } from './providerModels.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';/**@@ -97,7 +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.- const childEnv = { ...process.env, ...provider.envVars };+ // 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) };delete childEnv.CLAUDECODE;// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrapdiff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex 2993bfd2dd..11bf6d37d0 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -59,6 +59,105 @@ export function prefixOpencodeModel(provider, model) {return id.startsWith('ollama/') ? id : `ollama/${id}`;}+/**+ * Canonical OpenCode config for the local Ollama daemon. Declares Ollama as an+ * openai-compatible provider under the config-provider key `ollama` (matching+ * `prefixOpencodeModel`'s `ollama/` namespace) and auto-approves tools+ * (`permission: "allow"` — the OpenCode equivalent of claude's+ * `--dangerously-skip-permissions`, appropriate for PortOS's single-user+ * trusted box). Used as the base when a provider has no stored+ * `OPENCODE_CONFIG_CONTENT` or it fails to parse. Kept in lockstep with the+ * seeds (`providers.sample.json`, `data.reference/providers.json`) and the+ * provider migrations (149/152/164).+ */+const DEFAULT_OPENCODE_OLLAMA_PROVIDER = {+ npm: '@ai-sdk/openai-compatible',+ name: 'Ollama (local)',+ options: { baseURL: 'http://localhost:11434/v1' },+};++// Strip a leading `ollama/` namespace from a model id so it can key the+// OpenCode config `models` map (which lives UNDER the `ollama` provider, so the+// 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 the `OPENCODE_CONFIG_CONTENT` value dynamically at spawn time for an+ * OpenCode Ollama provider. The shipped seed declares the Ollama provider but no+ * `models` map, and OpenCode (>=1.17) rejects any `--model ollama/<id>` whose+ * `<id>` isn't declared in `provider.ollama.models` ("Model ollama/… is not+ * valid"). This injects that map from the provider's configured models plus the+ * model actually being run, so the `--model` the spawner passes is always+ * accepted.+ *+ * Pure. Returns `null` for a non-OpenCode command (caller keeps existing env+ * untouched). The base structure is parsed from the provider's stored+ * `OPENCODE_CONFIG_CONTENT` (so a user's custom baseURL/permission survives),+ * falling back to the canonical default when absent or unparseable.+ *+ * @param {{command?:string, models?:string[], defaultModel?:string|null, envVars?:object}} provider+ * @param {string|null} [model] - the model being run this invocation (may differ from defaultModel)+ * @returns {string|null} JSON string for OPENCODE_CONFIG_CONTENT, or null if not an OpenCode provider+ */+export function buildOpencodeConfigContent(provider, model = null) {+ if (!isOpencodeCommand(provider?.command)) return null;++ const stored = provider?.envVars?.OPENCODE_CONFIG_CONTENT;+ let config = null;+ if (typeof stored === 'string' && stored.length > 0) {+ try {+ config = JSON.parse(stored);+ } catch {+ config = null; // fall through to the canonical default below+ }+ }+ if (!config || typeof config !== 'object') {+ config = { permission: 'allow', provider: {} };+ }+ if (!config.provider || typeof config.provider !== 'object') {+ config.provider = {};+ }+ if (!config.provider.ollama || typeof config.provider.ollama !== 'object') {+ config.provider.ollama = { ...DEFAULT_OPENCODE_OLLAMA_PROVIDER };+ }++ // Union of every model this provider might address: its configured list, its+ // default, and the model being run right now. Deduped, prefix-stripped.+ const ids = [...(Array.isArray(provider?.models) ? provider.models : []), provider?.defaultModel, model]+ .filter((m) => typeof m === 'string' && m.length > 0)+ .map(stripOllamaPrefix)+ .filter((m) => typeof m === 'string' && m.length > 0);+ const unique = [...new Set(ids)];++ if (unique.length > 0) {+ config.provider.ollama.models = Object.fromEntries(+ unique.map((id) => [id, { name: id, tool_call: true }]),+ );+ }++ return JSON.stringify(config);+}++/**+ * Return the spawn env vars for a provider, overriding `OPENCODE_CONFIG_CONTENT`+ * with a dynamically-built config (declared models map) for OpenCode Ollama+ * providers. A drop-in replacement for `...provider.envVars` at spawn sites —+ * returns the provider's own envVars unchanged for every non-OpenCode provider.+ *+ * @param {object} provider+ * @param {string|null} [model]+ * @returns {object} env vars object (never undefined)+ */+export function withOpencodeConfigEnv(provider, model = null) {+ const base = provider?.envVars || {};+ const content = buildOpencodeConfigContent(provider, model);+ if (content == null) return base;+ return { ...base, OPENCODE_CONFIG_CONTENT: content };+}+/*** Claude Code on AWS Bedrock wants region-prefixed model ids* (`global.anthropic.claude-opus-4-8`, `us.anthropic.claude-opus-4-1-...-v1:0`).diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsindex a646165f16..a5971e16ca 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -12,6 +12,8 @@ import {toBedrockModelId,resolveBedrockCliModel,prefixOpencodeModel,+ buildOpencodeConfigContent,+ withOpencodeConfigEnv,isOpencodeCommand,isClaudeCommand,isOllamaClaudeProvider,@@ -93,6 +95,79 @@ describe('providerModels', () => {});});+ describe('buildOpencodeConfigContent', () => {+ const STORED = '{"permission":"allow","provider":{"ollama":{"npm":"@ai-sdk/openai-compatible","name":"Ollama (local)","options":{"baseURL":"http://localhost:11434/v1"}}}}';++ it('returns null for a non-opencode provider (caller keeps env untouched)', () => {+ expect(buildOpencodeConfigContent({ command: 'claude' }, 'qwen2.5:7b')).toBeNull();+ expect(buildOpencodeConfigContent({ command: 'codex' }, 'gpt-5')).toBeNull();+ });++ it('injects a models map for the run model, preserving the stored base config', () => {+ const provider = { command: 'opencode', ollamaBacked: true, models: [], envVars: { OPENCODE_CONFIG_CONTENT: STORED } };+ const cfg = JSON.parse(buildOpencodeConfigContent(provider, 'qwen2.5:7b'));+ expect(cfg.permission).toBe('allow');+ expect(cfg.provider.ollama.options.baseURL).toBe('http://localhost:11434/v1');+ expect(cfg.provider.ollama.models).toEqual({ 'qwen2.5:7b': { name: 'qwen2.5:7b', tool_call: true } });+ });++ it('unions configured models, defaultModel, and the run model (deduped)', () => {+ const provider = {+ command: 'opencode', ollamaBacked: true,+ models: ['qwen2.5:7b', 'llama3.1:8b'], defaultModel: 'llama3.1:8b',+ envVars: { OPENCODE_CONFIG_CONTENT: STORED },+ };+ const cfg = JSON.parse(buildOpencodeConfigContent(provider, 'mistral:7b'));+ expect(Object.keys(cfg.provider.ollama.models).sort()).toEqual(['llama3.1:8b', 'mistral:7b', 'qwen2.5:7b']);+ });++ it('strips the ollama/ namespace so keys are bare ids', () => {+ const provider = { command: 'opencode', ollamaBacked: true, models: [], envVars: { OPENCODE_CONFIG_CONTENT: STORED } };+ const cfg = JSON.parse(buildOpencodeConfigContent(provider, 'ollama/qwen2.5:7b'));+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toEqual({ name: 'qwen2.5:7b', tool_call: true });+ expect(cfg.provider.ollama.models['ollama/qwen2.5:7b']).toBeUndefined();+ });++ it('falls back to a canonical default when the stored config is absent or unparseable', () => {+ const provider = { command: 'opencode', ollamaBacked: true, models: ['qwen2.5:7b'], envVars: {} };+ const cfg = JSON.parse(buildOpencodeConfigContent(provider, null));+ expect(cfg.permission).toBe('allow');+ expect(cfg.provider.ollama.npm).toBe('@ai-sdk/openai-compatible');+ expect(cfg.provider.ollama.models['qwen2.5:7b']).toBeDefined();++ const broken = { command: 'opencode', ollamaBacked: true, models: ['x:1'], envVars: { OPENCODE_CONFIG_CONTENT: 'not json' } };+ const cfg2 = JSON.parse(buildOpencodeConfigContent(broken, null));+ expect(cfg2.provider.ollama.models['x:1']).toBeDefined();+ });++ it('omits the models key entirely when no ids are known (no regression from the shipped base)', () => {+ const provider = { command: 'opencode', ollamaBacked: true, models: [], defaultModel: null, envVars: { OPENCODE_CONFIG_CONTENT: STORED } };+ const cfg = JSON.parse(buildOpencodeConfigContent(provider, null));+ expect(cfg.provider.ollama.models).toBeUndefined();+ });+ });++ describe('withOpencodeConfigEnv', () => {+ it('overrides OPENCODE_CONFIG_CONTENT for opencode providers, preserving other env vars', () => {+ const provider = {+ command: 'opencode', ollamaBacked: true, models: ['qwen2.5:7b'],+ envVars: { OPENCODE_CONFIG_CONTENT: '{"provider":{"ollama":{}}}', OTHER: 'keep' },+ };+ const env = withOpencodeConfigEnv(provider, 'qwen2.5:7b');+ expect(env.OTHER).toBe('keep');+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT).provider.ollama.models['qwen2.5:7b']).toBeDefined();+ });++ it('returns provider.envVars unchanged for non-opencode providers', () => {+ const envVars = { CLAUDE_CODE_USE_BEDROCK: '1' };+ expect(withOpencodeConfigEnv({ command: 'claude', envVars }, 'claude-opus-4-8')).toBe(envVars);+ });++ it('returns an empty object (not undefined) when a provider has no envVars', () => {+ expect(withOpencodeConfigEnv({ command: 'claude' })).toEqual({});+ });+ });+describe('resolveCliModel', () => {it('returns null for the codex sentinel so --model is omitted', () => {expect(resolveCliModel(CODEX_CONFIGURED_DEFAULT)).toBeNull();diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 54b8405497..f683fabf75 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -57,6 +57,7 @@ import {buildTuiInvocation,detectMissingTuiBinary,} from './tuiHandshake.js';+import { withOpencodeConfigEnv } from './providerModels.js';// One-shot defaults that don't apply to the long-running agent path:// - hard run cap (5 min vs unbounded for agents)@@ -161,7 +162,10 @@ ${prompt}`;// through to a spawned Claude Code TUI would make the child think it's// nested. Other AI spawn paths (runner.js, agentCliSpawning.js) strip it// for the same reason.- const childEnv = { ...process.env, ...(provider.envVars || {}), TERM: 'xterm-256color', COLORTERM: 'truecolor' };+ // 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.+ const childEnv = { ...process.env, ...withOpencodeConfigEnv(provider, provider.defaultModel), TERM: 'xterm-256color', COLORTERM: 'truecolor' };delete childEnv.CLAUDECODE;let ptyProcess;diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 8c6d951eaa..5b1561bad4 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -26,7 +26,7 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';-import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';+import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, withOpencodeConfigEnv } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';const AGENTS_DIR = PATHS.cosAgents;@@ -424,7 +424,10 @@ export async function spawnDirectly({// The pm2 shim must be prepended onto the FINAL PATH (after any// provider.envVars override) so a `--dangerously-skip-permissions` agent// can't `pm2 kill` the shared daemon.- env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()+ // withOpencodeConfigEnv rebuilds OPENCODE_CONFIG_CONTENT with a declared+ // models map for OpenCode Ollama providers (no-op for every other provider)+ // so `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.+ env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...withOpencodeConfigEnv(provider, model) }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()});registerSpawnedAgent(claudeProcess.pid, {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 9917aa42f8..bcddfa3ce2 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -18,7 +18,7 @@ import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { shellQuote } from '../lib/shellQuote.js';-import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';+import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, withOpencodeConfigEnv } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { isAntigravityCommand } from '../lib/antigravity.js';@@ -124,7 +124,7 @@ const DONE_POLL_INTERVAL_MS = 2000;* to create the session, `sessionId` is null and the caller is expected* to bail out via its `finish` path.*/-export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit, onInitialCommandSent }) {+export function createAgentTuiSession({ agentId, provider, model = null, tuiConfig, cwd, onData, onExit, onInitialCommandSent }) {const sessionId = shellService.createShellSession(null, {cwd,kind: 'agent-tui',@@ -144,7 +144,10 @@ export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onDat// agentGuardEnv() prepends the pm2 shim to the agent session's PATH (and// points it at the real pm2). Spread LAST so it wins over any provider PATH.// Only AI agent sessions get this — the user's own Shell page does not.- env: { ...(provider.envVars || {}), ...agentGuardEnv() },+ // withOpencodeConfigEnv rebuilds OPENCODE_CONFIG_CONTENT with a declared+ // models map for OpenCode Ollama providers (no-op otherwise) so the+ // `--model ollama/<id>` the TUI launches with isn't rejected — see issue-2190.+ env: { ...withOpencodeConfigEnv(provider, model), ...agentGuardEnv() },onData,onExit,});@@ -725,6 +728,7 @@ export async function spawnTuiAgent({const session = createAgentTuiSession({agentId,provider,+ model,tuiConfig,cwd,onData: handleData,diff --git a/server/services/runner.js b/server/services/runner.jsindex 496d1af242..e559fe139a 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -6,7 +6,7 @@ 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 } from '../lib/providerModels.js';+import { hasModelFlag, extractBakedModel, withOpencodeConfigEnv } from '../lib/providerModels.js';import { buildCliArgs } from '../lib/cliProviderArgs.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';@@ -204,7 +204,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.- const childEnv = { ...process.env, ...provider.envVars };+ // 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.+ const childEnv = { ...process.env, ...withOpencodeConfigEnv(provider, provider.defaultModel) };delete childEnv.CLAUDECODE;Object.assign(childEnv, agentGuardEnv(childEnv));