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
feat([issue-1802]): add OpenCode Ollama provider (CLI + TUI) with OpenAI-format tool execution
Adam Eivy01d142d3b845
diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex 097378081f..3468cf81f6 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -156,6 +156,41 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-ollama": {+ "id": "opencode-ollama",+ "name": "OpenCode Ollama (local model)",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "models": [],+ "defaultModel": null,+ "ollamaBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-ollama-tui": {+ "id": "opencode-ollama-tui",+ "name": "OpenCode Ollama TUI (local model)",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "models": [],+ "defaultModel": null,+ "ollamaBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"antigravity-tui": {"id": "antigravity-tui","name": "Antigravity TUI",diff --git a/scripts/migrations/148-opencode-ollama-providers.js b/scripts/migrations/148-opencode-ollama-providers.jsnew file mode 100644index 0000000000..69af0f63ef--- /dev/null+++ b/scripts/migrations/148-opencode-ollama-providers.js@@ -0,0 +1,113 @@+/**+ * Ship the "OpenCode Ollama" provider pair (CLI + TUI) to existing installs.+ *+ * Background: issue-1802. Anthropic-format tool-calling (what the `claude` CLI+ * expects) is a poor fit for Ollama models trained against the OpenAI tool+ * schema — they emit JSON tool-call text that the harness never executes, so a+ * Claude-Ollama agent "runs" but silently fails to edit files. OpenCode speaks+ * the OpenAI-compatible protocol natively, so the SAME local models reliably+ * apply file changes. These providers run `opencode` against a local Ollama+ * daemon (declared inline via OPENCODE_CONFIG_CONTENT) so api-only / local-model+ * users get working tool execution.+ *+ * `setup-data.js` merges *missing* provider entries from data.reference, but only+ * when an install actually re-runs setup. This migration delivers the pair on a+ * plain server restart too, and is the canonical path for deployed installs to+ * pick them up. Purely additive: brand-new ids, so there's no rename or pinned-+ * id rewrite to do (contrast migration 146, which renamed clawed-ollama). Adds+ * each provider only when missing — idempotent; existing keys are left untouched.+ *+ * Kept in lockstep with data.reference/providers.json and+ * server/lib/aiToolkit/defaults/providers.sample.json. Frozen here as the+ * historical record this migration installs; 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';++// Inline OpenCode config: declare the local Ollama daemon as an+// openai-compatible provider and auto-approve tools (the OpenCode equivalent of+// claude's --dangerously-skip-permissions — appropriate for PortOS's single-user+// trusted box). Stored as a single env-var string; OPENCODE_CONFIG_CONTENT has+// the highest config precedence in OpenCode.+const OPENCODE_CONFIG_CONTENT = '{"permission":"allow","provider":{"ollama":{"npm":"@ai-sdk/openai-compatible","name":"Ollama (local)","options":{"baseURL":"http://localhost:11434/v1"}}}}';++const OPENCODE_OLLAMA_CLI = {+ id: 'opencode-ollama',+ name: 'OpenCode Ollama (local model)',+ type: 'cli',+ command: 'opencode',+ args: ['run'],+ models: [],+ defaultModel: null,+ ollamaBacked: true,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ headlessArgs: [],+};++const OPENCODE_OLLAMA_TUI = {+ id: 'opencode-ollama-tui',+ name: 'OpenCode Ollama TUI (local model)',+ type: 'tui',+ command: 'opencode',+ args: [],+ models: [],+ defaultModel: null,+ ollamaBacked: true,+ timeout: 600000,+ enabled: false,+ envVars: { OPENCODE_CONFIG_CONTENT },+ secretEnvVars: [],+ tuiPromptDelayMs: 2500,+ tuiIdleTimeoutMs: 180000,+};++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 seeds OpenCode Ollama from data.reference)`);+ 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;+ }++ const providers = config.providers;+ let changed = false;++ for (const def of [OPENCODE_OLLAMA_CLI, OPENCODE_OLLAMA_TUI]) {+ if (!providers[def.id]) {+ providers[def.id] = { ...def, envVars: { ...def.envVars } };+ changed = true;+ console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);+ }+ }++ if (changed) {+ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);+ } else {+ console.log(`✅ ${PROVIDERS_REL_PATH}: OpenCode Ollama providers already present — no change`);+ }+ },+};diff --git a/scripts/migrations/148-opencode-ollama-providers.test.js b/scripts/migrations/148-opencode-ollama-providers.test.jsnew file mode 100644index 0000000000..491a4fc994--- /dev/null+++ b/scripts/migrations/148-opencode-ollama-providers.test.js@@ -0,0 +1,111 @@+/**+ * Test for migration 148 — add the OpenCode Ollama CLI + TUI shipped providers+ * to existing installs. 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, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './148-opencode-ollama-providers.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 148 — OpenCode Ollama providers', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-148-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('adds both shipped OpenCode providers to an existing install', async () => {+ writeJson(providersPath, {+ activeProvider: 'claude-code',+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ const cli = out.providers['opencode-ollama'];+ const tui = out.providers['opencode-ollama-tui'];+ expect(cli.type).toBe('cli');+ expect(cli.command).toBe('opencode');+ expect(cli.args).toEqual(['run']);+ expect(cli.ollamaBacked).toBe(true);+ expect(cli.enabled).toBe(false);+ expect(tui.type).toBe('tui');+ expect(tui.command).toBe('opencode');+ expect(tui.args).toEqual([]);+ expect(tui.ollamaBacked).toBe(true);+ // unrelated providers + active provider untouched+ expect(out.providers['claude-code']).toBeDefined();+ expect(out.activeProvider).toBe('claude-code');+ });++ it('declares a valid inline OpenCode config pointing at the local Ollama daemon', async () => {+ writeJson(providersPath, { providers: {} });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ const cfg = JSON.parse(out.providers['opencode-ollama'].envVars.OPENCODE_CONFIG_CONTENT);+ expect(cfg.permission).toBe('allow');+ expect(cfg.provider.ollama.npm).toBe('@ai-sdk/openai-compatible');+ expect(cfg.provider.ollama.options.baseURL).toBe('http://localhost:11434/v1');+ });++ it('does not overwrite a user-customized opencode-ollama entry', async () => {+ writeJson(providersPath, {+ providers: {+ 'opencode-ollama': {+ id: 'opencode-ollama', type: 'cli', command: 'opencode',+ enabled: true, models: ['qwen2.5-coder:32b'], defaultModel: 'qwen2.5-coder:32b',+ },+ },+ });++ await migration.up({ rootDir });++ const out = readJson(providersPath);+ // existing CLI entry preserved untouched+ expect(out.providers['opencode-ollama'].enabled).toBe(true);+ expect(out.providers['opencode-ollama'].models).toEqual(['qwen2.5-coder:32b']);+ // but the missing TUI variant is still added+ expect(out.providers['opencode-ollama-tui']).toBeDefined();+ });++ it('is idempotent — a second run makes no changes', async () => {+ writeJson(providersPath, {+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },+ });++ await migration.up({ rootDir });+ const afterFirst = readFileSync(providersPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);+ });++ it('is a no-op when data/providers.json does not exist (fresh install)', async () => {+ await migration.up({ rootDir });+ expect(existsSync(providersPath)).toBe(false);+ });++ it('does not modify the file on invalid JSON', async () => {+ writeFileSync(providersPath, '{ not valid json');+ const before = readFileSync(providersPath, 'utf-8');++ await migration.up({ rootDir });++ expect(readFileSync(providersPath, 'utf-8')).toBe(before);+ });+});diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 415a52b1b1..e5b9ec857f 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -77,6 +77,41 @@"tuiPromptDelayMs": 2500,"tuiIdleTimeoutMs": 180000},+ "opencode-ollama": {+ "id": "opencode-ollama",+ "name": "OpenCode Ollama (local model)",+ "type": "cli",+ "command": "opencode",+ "args": ["run"],+ "models": [],+ "defaultModel": null,+ "ollamaBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"+ },+ "secretEnvVars": [],+ "headlessArgs": []+ },+ "opencode-ollama-tui": {+ "id": "opencode-ollama-tui",+ "name": "OpenCode Ollama TUI (local model)",+ "type": "tui",+ "command": "opencode",+ "args": [],+ "models": [],+ "defaultModel": null,+ "ollamaBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "OPENCODE_CONFIG_CONTENT": "{\"permission\":\"allow\",\"provider\":{\"ollama\":{\"npm\":\"@ai-sdk/openai-compatible\",\"name\":\"Ollama (local)\",\"options\":{\"baseURL\":\"http://localhost:11434/v1\"}}}}"+ },+ "secretEnvVars": [],+ "tuiPromptDelayMs": 2500,+ "tuiIdleTimeoutMs": 180000+ },"codex": {"id": "codex","name": "Codex CLI",diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.jsindex adfaad9486..6df0922589 100644--- a/server/lib/cliProviderArgs.js+++ b/server/lib/cliProviderArgs.js@@ -16,7 +16,7 @@* - Claude Code: `-p -` (+ `--model <id>`)*/-import { resolveCliModel, hasModelFlag, resolveBedrockCliModel } from './providerModels.js';+import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel } from './providerModels.js';import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from './antigravity.js';/**@@ -62,6 +62,23 @@ export function buildCliArgs(provider) {return ensureAntigravityPrintArgs(baseArgs);}+ // OpenCode CLI (`opencode run`): the headless, non-interactive subcommand. It+ // reads the prompt from stdin (the runner's shell-pipeline delivery, same as+ // every other CLI here) and selects the model with `-m provider/model`. The+ // OpenCode Ollama provider is namespaced `ollama/<model>` (see+ // prefixOpencodeModel). Ensure the `run` subcommand leads the argv even if the+ // saved provider.args dropped it. Model injection is gated on the user not+ // having hard-coded a `--model`/`-m` of their own, mirroring the claude/gemini+ // gate below.+ if (provider?.command === 'opencode') {+ const args = baseArgs.includes('run') ? [...baseArgs] : ['run', ...baseArgs];+ const model = prefixOpencodeModel(provider, effectiveDefaultModel);+ if (model && !hasModelFlag(baseArgs)) {+ args.push('-m', model);+ }+ return args;+ }+// Gemini CLI: prompt is piped via stdin directly. `-m <model>` is gemini-// cli's documented short flag for model selection (long form: `--model`).// Skip injection when the user's saved args already pin a model (eitherdiff --git a/server/lib/cliProviderArgs.test.js b/server/lib/cliProviderArgs.test.jsindex 26fd08459c..b26e2c168a 100644--- a/server/lib/cliProviderArgs.test.js+++ b/server/lib/cliProviderArgs.test.js@@ -66,6 +66,37 @@ describe('cliProviderArgs', () => {});});+ describe('buildCliArgs — OpenCode Ollama', () => {+ it('runs `opencode run -m ollama/<model>` (prompt rides stdin)', () => {+ const args = buildCliArgs({+ id: 'opencode-ollama', command: 'opencode', args: ['run'],+ ollamaBacked: true, defaultModel: 'qwen2.5:7b',+ });+ expect(args).toEqual(['run', '-m', 'ollama/qwen2.5:7b']);+ });++ it('prepends the run subcommand when the saved args dropped it', () => {+ const args = buildCliArgs({+ id: 'opencode-ollama', command: 'opencode', args: [],+ defaultModel: 'qwen2.5:7b',+ });+ expect(args).toEqual(['run', '-m', 'ollama/qwen2.5:7b']);+ });++ it('omits -m when no model is configured (opencode falls back to its own default)', () => {+ const args = buildCliArgs({ id: 'opencode-ollama', command: 'opencode', args: ['run'], defaultModel: null });+ expect(args).toEqual(['run']);+ });++ it('respects a user-baked -m pin and skips injection', () => {+ const args = buildCliArgs({+ id: 'opencode-ollama', command: 'opencode', args: ['run', '-m', 'ollama/custom'],+ defaultModel: 'qwen2.5:7b',+ });+ expect(args).toEqual(['run', '-m', 'ollama/custom']);+ });+ });+describe('stripBrokenModelFlags', () => {it('drops dangling / empty model flags but keeps pinned ones', () => {expect(stripBrokenModelFlags(['--model'])).toEqual([]);diff --git a/server/lib/providerModels.js b/server/lib/providerModels.jsindex b8b39790d5..3fad9c25cb 100644--- a/server/lib/providerModels.js+++ b/server/lib/providerModels.js@@ -17,6 +17,26 @@ export const isCodexConfiguredDefault = (model) => model === CODEX_CONFIGURED_DE*/export const resolveCliModel = (model) => isCodexConfiguredDefault(model) ? null : (model || null);+/**+ * OpenCode addresses models as `provider/model` (e.g. `ollama/qwen2.5:7b`). The+ * OpenCode Ollama provider declares its local daemon under the config-provider+ * key `ollama` (via OPENCODE_CONFIG_CONTENT), so the bare Ollama model id stored+ * in `defaultModel` must be namespaced with `ollama/` before it's passed to+ * `opencode run -m` / `opencode --model`. Idempotent — an id that already starts+ * with `ollama/` is returned untouched, and a `/`-bearing Ollama id+ * (`hf.co/user/model:tag`) is namespaced as `ollama/hf.co/...` since OpenCode+ * splits provider/model on the FIRST slash only. No-op for non-OpenCode+ * providers and empty models.+ * @param {{command?:string}} provider+ * @param {string|null|undefined} model+ * @returns {string|null|undefined}+ */+export function prefixOpencodeModel(provider, model) {+ if (provider?.command !== 'opencode' || !model) return model;+ const id = String(model);+ return id.startsWith('ollama/') ? id : `ollama/${id}`;+}+/*** 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 e47c92c8e2..425e842bac 100644--- a/server/lib/providerModels.test.js+++ b/server/lib/providerModels.test.js@@ -10,7 +10,8 @@ import {isBedrockEnabled,hasBedrockRegionPrefix,toBedrockModelId,- resolveBedrockCliModel+ resolveBedrockCliModel,+ prefixOpencodeModel} from './providerModels.js';describe('providerModels', () => {@@ -28,6 +29,33 @@ describe('providerModels', () => {});});+ describe('prefixOpencodeModel', () => {+ const oc = { command: 'opencode' };++ it('namespaces a bare Ollama id under ollama/ for opencode providers', () => {+ expect(prefixOpencodeModel(oc, 'qwen2.5:7b')).toBe('ollama/qwen2.5:7b');+ });++ it('is idempotent — an already-namespaced id is returned unchanged', () => {+ expect(prefixOpencodeModel(oc, 'ollama/qwen2.5:7b')).toBe('ollama/qwen2.5:7b');+ });++ it('namespaces a slash-bearing Ollama id (opencode splits on the first slash)', () => {+ expect(prefixOpencodeModel(oc, 'hf.co/user/model:tag')).toBe('ollama/hf.co/user/model:tag');+ });++ it('is a no-op for non-opencode providers', () => {+ expect(prefixOpencodeModel({ command: 'claude' }, 'qwen2.5:7b')).toBe('qwen2.5:7b');+ expect(prefixOpencodeModel({ command: 'codex' }, 'gpt-5')).toBe('gpt-5');+ });++ it('is a no-op for empty / nullish models', () => {+ expect(prefixOpencodeModel(oc, '')).toBe('');+ expect(prefixOpencodeModel(oc, null)).toBeNull();+ expect(prefixOpencodeModel(oc, undefined)).toBeUndefined();+ });+ });+describe('resolveCliModel', () => {it('returns null for the codex sentinel so --model is omitted', () => {expect(resolveCliModel(CODEX_CONFIGURED_DEFAULT)).toBeNull();diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex b0a90eb373..153a0508fe 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -12,7 +12,7 @@* No cycle risk: this module imports nothing from either consumer.*/-import { resolveCliModel, hasModelFlag, resolveBedrockCliModel } from './providerModels.js';+import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel } from './providerModels.js';import { ensureAntigravityTuiArgs, isAntigravityCommand } from './antigravity.js';// ─── Paste handshake constants ────────────────────────────────────────────@@ -405,15 +405,18 @@ export function buildTuiInvocation(provider, model) {const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);const effectiveModel = resolveCliModel(model);const shouldInject = !isAntigravityCommand(command) && effectiveModel && !hasModelFlag(baseArgs);- // Map a bare Claude id to its Bedrock form when the box is in Bedrock mode- // (no-op otherwise / for non-Claude ids) — mirrors buildCliArgs for the+ // OpenCode TUI: namespace the bare Ollama id (`opencode --model ollama/<id>`).+ // Otherwise map a bare Claude id to its Bedrock form when the box is in Bedrock+ // mode (no-op otherwise / for non-Claude ids) — mirrors buildCliArgs for the// claude-code-tui runner.- const injectedModel = shouldInject- ? resolveBedrockCliModel(effectiveModel, {- env: { ...process.env, ...provider?.envVars },- providerId: provider?.id,- })- : effectiveModel;+ const injectedModel = !shouldInject+ ? effectiveModel+ : command === 'opencode'+ ? prefixOpencodeModel(provider, effectiveModel)+ : resolveBedrockCliModel(effectiveModel, {+ env: { ...process.env, ...provider?.envVars },+ providerId: provider?.id,+ });const args = shouldInject ? [...baseArgs, '--model', injectedModel] : baseArgs;return { command, args };}diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex f8c95b68f2..eccf4bae06 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -374,6 +374,13 @@ describe('tuiHandshake.buildTuiInvocation', () => {expect(buildTuiInvocation(provider, '').args).toEqual(['-p', '-']);});+ it('namespaces the Ollama model under ollama/ for an OpenCode TUI', () => {+ const provider = { id: 'opencode-ollama-tui', command: 'opencode', args: [] };+ const out = buildTuiInvocation(provider, 'qwen2.5:7b');+ expect(out.command).toBe('opencode');+ expect(out.args).toEqual(['--model', 'ollama/qwen2.5:7b']);+ });+it('handles a provider with no args (treats as empty array)', () => {const out = buildTuiInvocation({ id: 'claude' }, 'opus-x');expect(out.command).toBe('claude');diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 7549a7e21e..4e959f7b63 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 } from '../lib/providerModels.js';+import { resolveBedrockCliModel, prefixOpencodeModel } from '../lib/providerModels.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';const AGENTS_DIR = PATHS.cosAgents;@@ -279,6 +279,26 @@ export function buildCliSpawnConfig(provider, model, settingsEnv = {}) {};}+ // OpenCode CLI (`opencode run`): headless agent invocation for a local Ollama+ // model. `opencode run` reads the prompt from stdin and auto-approves tools via+ // the `permission: "allow"` baked into OPENCODE_CONFIG_CONTENT (the equivalent+ // of claude's `--dangerously-skip-permissions` / codex's bypass — appropriate+ // for PortOS's single-user trusted box). The model is namespaced `ollama/<id>`+ // (prefixOpencodeModel). OpenCode emits plain text (no stream-json), so the+ // live-output handler falls through to its default text path.+ if (provider?.command === 'opencode') {+ const baseArgs = provider?.args?.includes('run') ? [...provider.args] : ['run', ...(provider?.args || [])];+ const model = prefixOpencodeModel(provider, effectiveModel);+ if (model) {+ baseArgs.push('-m', model);+ }+ return {+ command: provider.command,+ args: baseArgs,+ stdinMode: 'prompt'+ };+ }+// Default: Claude Code CLIconst args = ['--dangerously-skip-permissions', // Unrestricted modediff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 094208df55..43031293b0 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -187,6 +187,25 @@ describe('buildCliSpawnConfig', () => {expect(config.args).toEqual(['--print', '--dangerously-skip-permissions']);});+ it('runs `opencode run -m ollama/<model>` for a headless OpenCode Ollama agent', () => {+ const config = buildCliSpawnConfig(+ { id: 'opencode-ollama', command: 'opencode', args: ['run'], ollamaBacked: true },+ 'qwen2.5:7b',+ );++ expect(config.command).toBe('opencode');+ expect(config.args).toEqual(['run', '-m', 'ollama/qwen2.5:7b']);+ expect(config.stdinMode).toBe('prompt');+ // OpenCode emits plain text, so no stream-json format is requested.+ expect(config.streamFormat).toBeUndefined();+ });++ it('prepends the run subcommand for OpenCode even if saved args dropped it', () => {+ const config = buildCliSpawnConfig({ id: 'opencode-ollama', command: 'opencode', args: [] }, 'qwen2.5:7b');++ expect(config.args).toEqual(['run', '-m', 'ollama/qwen2.5:7b']);+ });+describe('Bedrock model-id mapping', () => {// buildCliSpawnConfig reads process.env for the Bedrock signal; isolate the// tests from whatever the host/CI environment happens to set.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 80056a3ba1..a5420c7dd2 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -17,7 +17,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';-import { resolveCliModel, resolveBedrockCliModel } from '../lib/providerModels.js';+import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { isAntigravityCommand } from '../lib/antigravity.js';@@ -181,6 +181,11 @@ function appendModelArgs(args, model, command, provider) {if (isAntigravityCommand(command)) return args;const effectiveModel = resolveCliModel(model);if (!effectiveModel) return args;+ // OpenCode TUI launches with `opencode --model ollama/<id>` (the top-level+ // flag preselects the model). Namespace the bare Ollama id; no Bedrock mapping.+ if (command === 'opencode') {+ return [...args, '--model', prefixOpencodeModel(provider, effectiveModel)];+ }// Bedrock box: map a bare Claude id to its region-prefixed form just-in-time// (no-op off Bedrock / for non-Claude ids).const injectedModel = resolveBedrockCliModel(effectiveModel, {diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex d58ff16100..3bf7947bab 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -103,7 +103,10 @@ vi.mock('../lib/providerModels.js', () => ({resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m),// Bedrock map is a no-op off Bedrock — mirror that pass-through here (the// mapper itself is unit-tested in providerModels.test.js).- resolveBedrockCliModel: vi.fn((m) => m)+ resolveBedrockCliModel: vi.fn((m) => m),+ // Mirror the real ollama/ namespacing for opencode providers (fully unit-+ // tested in providerModels.test.js).+ prefixOpencodeModel: vi.fn((p, m) => (p?.command === 'opencode' && m && !String(m).startsWith('ollama/')) ? `ollama/${m}` : m)}));// Shrink buffer thresholds so the truncation tests can trip them with tiny@@ -212,6 +215,14 @@ describe('agent TUI spawning', () => {expect(config.idleTimeoutMs).toBe(30000);});+ it('namespaces the Ollama model under ollama/ for an OpenCode TUI', () => {+ const config = buildTuiSpawnConfig({+ id: 'opencode-ollama-tui', type: 'tui', command: 'opencode', args: [],+ }, 'qwen2.5:7b');+ expect(config.command).toBe('opencode');+ expect(config.args).toEqual(['--model', 'ollama/qwen2.5:7b']);+ });+it('falls back to the default command via id heuristic when command is omitted', () => {const codexConfig = buildTuiSpawnConfig({ id: 'my-codex-instance', type: 'tui' }, null);expect(codexConfig.command).toBe('codex');diff --git a/server/services/askService.js b/server/services/askService.jsindex c7b38b6c90..bd61ea0f83 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -31,7 +31,7 @@ import { getCharacter } from './character.js';import { getEvents as getCalendarEvents } from './calendarSync.js';import { tokenize as bm25Tokenize, STOP_WORDS } from '../lib/bm25.js';import { VALID_MODES as STORAGE_VALID_MODES } from './askConversations.js';-import { resolveCliModel } from '../lib/providerModels.js';+import { resolveCliModel, prefixOpencodeModel } from '../lib/providerModels.js';import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';@@ -566,7 +566,8 @@ async function* streamCompletion(provider, model, prompt, signal) {if (!args.includes('--output-format') && !args.includes('-o')) args.push('--output-format', 'text');if (cliModel) args.push('--model', cliModel);} else if (cliModel) {- args.push('--model', cliModel);+ // OpenCode addresses its Ollama model as `ollama/<id>` (no-op for other CLIs).+ args.push('--model', prefixOpencodeModel(provider, cliModel));}const out = await new Promise((resolve, reject) => {let buf = '';