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 OpenCode Ollama --model rejection: build models map at spawn
[._.]/ Adam Eivy7bf1f44257a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex faa647bce2..40535d2476 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +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.- **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/server/lib/README.md b/server/lib/README.mdindex 6b357194bf..39208c6df5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -93,6 +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. || `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/index.js b/server/lib/index.jsindex 6921b16aff..68352f2201 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -96,6 +96,7 @@ export * from './promptPartials.js';export * from './promptRunner.js';export * from './promptTemplate.js';export * from './providerModels.js';+export * from './opencodeConfig.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in// mediaModels.js — namespace it so the barrel surface is unambiguous.export * as runners from './runners.js';diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.jsnew file mode 100644index 0000000000..9bd5c53897--- /dev/null+++ b/server/lib/opencodeConfig.js@@ -0,0 +1,74 @@+/**+ * 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.+ */++import { isOpencodeCommand, prefixOpencodeModel } from './providerModels.js';++/**+ * Base OpenCode config structure for Ollama-backed providers (permission ++ * provider block). The models map is added dynamically per-run.+ */+const OPENCODE_OLLAMA_BASE_CONFIG = {+ permission: 'allow',+ provider: {+ ollama: {+ npm: '@ai-sdk/openai-compatible',+ name: 'Ollama (local)',+ options: { baseURL: 'http://localhost:11434/v1' },+ },+ },+};++/**+ * 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.+ *+ * @param {string|null|undefined} prefixedModel - Model id with ollama/ prefix+ * @returns {object} OpenCode config object+ */+export function buildOpencodeConfig(prefixedModel) {+ if (!prefixedModel) {+ return { ...OPENCODE_OLLAMA_BASE_CONFIG };+ }+ return {+ ...OPENCODE_OLLAMA_BASE_CONFIG,+ models: {+ [prefixedModel]: { name: prefixedModel, tool_call: true },+ },+ };+}++/**+ * Build OPENCODE_CONFIG_CONTENT env var value for an Ollama-backed OpenCode+ * provider. Returns the JSON string ready to set as an env var.+ *+ * @param {string|null|undefined} prefixedModel - Model id with ollama/ prefix+ * @returns {string} JSON string for OPENCODE_CONFIG_CONTENT env var+ */+export function buildOpencodeConfigContent(prefixedModel) {+ return JSON.stringify(buildOpencodeConfig(prefixedModel));+}++/**+ * 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.+ *+ * @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+ */+export function buildOpencodeEnvVars(provider, model) {+ if (!isOpencodeCommand(provider?.command) || provider?.ollamaBacked !== true) {+ return {};+ }+ const prefixedModel = prefixOpencodeModel(provider, model);+ return {+ OPENCODE_CONFIG_CONTENT: buildOpencodeConfigContent(prefixedModel),+ };+}diff --git a/server/lib/opencodeConfig.test.js b/server/lib/opencodeConfig.test.jsnew file mode 100644index 0000000000..a7cb5f8d22--- /dev/null+++ b/server/lib/opencodeConfig.test.js@@ -0,0 +1,97 @@+import { describe, it, expect } from 'vitest';+import {+ buildOpencodeConfig,+ buildOpencodeConfigContent,+ buildOpencodeEnvVars,+} from './opencodeConfig.js';++describe('buildOpencodeConfig', () => {+ it('returns base config without 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)',+ });+ expect(cfg.models).toBeUndefined();+ });++ it('includes the prefixed model in the models map', () => {+ const cfg = buildOpencodeConfig('ollama/qwen2.5:7b');+ expect(cfg.models).toEqual({+ 'ollama/qwen2.5:7b': { name: 'ollama/qwen2.5:7b', tool_call: true },+ });+ });++ it('preserves the model id exactly as passed', () => {+ const cfg = buildOpencodeConfig('ollama/hf.co/user/model:tag');+ expect(cfg.models['ollama/hf.co/user/model:tag']).toBeDefined();+ });+});++describe('buildOpencodeConfigContent', () => {+ it('returns valid JSON', () => {+ 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',+ tool_call: true,+ });+ });++ it('serializes the base config for null model', () => {+ const json = buildOpencodeConfigContent(null);+ const parsed = JSON.parse(json);+ expect(parsed.permission).toBe('allow');+ expect(parsed.models).toBeUndefined();+ });+});++describe('buildOpencodeEnvVars', () => {+ it('returns empty object for non-OpenCode providers', () => {+ const result = buildOpencodeEnvVars({ command: 'claude' }, 'claude-opus-4');+ expect(result).toEqual({});+ });++ it('returns empty object for OpenCode providers without ollamaBacked', () => {+ const result = buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: false },+ 'anthropic/claude-sonnet'+ );+ expect(result).toEqual({});+ });++ it('returns dynamic OPENCODE_CONFIG_CONTENT for Ollama-backed OpenCode', () => {+ const result = buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: true },+ '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,+ });+ });++ it('handles absolute path to opencode binary', () => {+ const result = buildOpencodeEnvVars(+ { command: '/opt/homebrew/bin/opencode', ollamaBacked: true },+ 'qwen2.5:7b'+ );+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);+ expect(cfg.models['ollama/qwen2.5:7b']).toBeDefined();+ });++ it('handles null model gracefully', () => {+ const result = buildOpencodeEnvVars(+ { command: 'opencode', ollamaBacked: true },+ null+ );+ expect(result.OPENCODE_CONFIG_CONTENT).toBeDefined();+ const cfg = JSON.parse(result.OPENCODE_CONFIG_CONTENT);+ expect(cfg.models).toBeUndefined();+ });+});diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 54b8405497..5fc34b0fe8 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -57,6 +57,7 @@ import {buildTuiInvocation,detectMissingTuiBinary,} from './tuiHandshake.js';+import { buildOpencodeEnvVars } from './opencodeConfig.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' };+ // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with+ // the models map so --model is accepted (the static env var lacked this).+ const opencodeEnv = buildOpencodeEnvVars(provider, provider.defaultModel);+ const childEnv = { ...process.env, ...(provider.envVars || {}), ...opencodeEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' };delete childEnv.CLAUDECODE;let ptyProcess;diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 8c6d951eaa..ca2a72a005 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -28,6 +28,7 @@ import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetimport { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';+import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';const AGENTS_DIR = PATHS.cosAgents;@@ -416,6 +417,10 @@ export async function spawnDirectly({? await getClaudeSettingsEnv(): {};+ // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with+ // the models map so --model is accepted (the static env var lacked this).+ const opencodeEnv = buildOpencodeEnvVars(provider, model);+const claudeProcess = spawn(cliConfig.command, cliConfig.args, {cwd,shell: false,@@ -423,8 +428,9 @@ export async function spawnDirectly({windowsHide: true,// 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; })()+ // can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override+ // the static OPENCODE_CONFIG_CONTENT in provider.envVars.+ env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; 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..602320ee45 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -48,6 +48,7 @@ import {applyCommandDefaults,} from '../lib/tuiHandshake.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';+import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { execFile } from 'child_process';// Agent-specific timing/lifecycle constants (not shared with the one-shot@@ -124,7 +125,10 @@ 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, tuiConfig, cwd, onData, onExit, onInitialCommandSent }) {+ // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with+ // the models map so --model is accepted (the static env var lacked this).+ const opencodeEnv = buildOpencodeEnvVars(provider, model);const sessionId = shellService.createShellSession(null, {cwd,kind: 'agent-tui',@@ -144,7 +148,8 @@ 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() },+ // opencodeEnv comes after provider.envVars to override the static config.+ env: { ...(provider.envVars || {}), ...opencodeEnv, ...agentGuardEnv() },onData,onExit,});@@ -725,6 +730,7 @@ export async function spawnTuiAgent({const session = createAgentTuiSession({agentId,provider,+ model,tuiConfig,cwd,onData: handleData,