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-1776]): Clawed Ollama provider + coding-only task form + tool-use model filtering
Adam Eivyb2c0a4931d62
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 50750f3388..4c81e89193 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased+## AI Providers++- **[issue-1776] Run CoS agent tasks on a local model with the new "Clawed Ollama" provider.** If your only LLM is Ollama or LM Studio, you couldn't run file-writing agent tasks — those providers return plain text with no Read/Write/Edit harness. The new **Clawed Ollama** sample provider (AI Providers → Add Sample) runs the full Claude Code harness on top of your local model: it's a `claude` CLI pre-wired to your Ollama daemon, and its **Refresh Models** pulls the installed Ollama models filtered to the **tool-use-capable** ones the agent loop depends on. The task form now offers **only coding providers** — raw Ollama / LM Studio / kimi are excluded (with an inline advisory pointing you to Clawed Ollama when they're all you have), and a server-side guard rejects an API provider that slips into the spawn path instead of silently writing nothing. Includes a copy-ready global `~/.claude/settings.json` example and a setup guide with the tool-use model caveat. (`docs/features/clawed-ollama.md`, `docs/examples/`)+## Dashboard- **A new "Daily POST" dashboard widget surfaces your cognitive self-test streak and whether you've trained today.** POST (the daily 5-minute math/wordplay/memory/verbal/imagination self-test) had no dashboard presence — you had to navigate to `/post` to even remember it existed, which is exactly the wrong friction for a habit you want to do *daily*. The new widget shows today's status (✓ Done · score%, or a "Start →" nudge), your current practice streak with a fire/zap/sparkle glyph, and your personal-best run — one click into `/post/launcher`. To back it, `getPostStats` now also returns `completedToday`, `currentStreak`, `longestStreak`, `lastDate`, and `todayScore`, computed by a new pure `computePostStreaks(sessions, today)` helper that mirrors the activity-streak grace-window semantics (a not-yet-done today doesn't break the streak if yesterday is logged) using UTC day math so month/DST boundaries don't cause off-by-ones. The widget ships in the built-in **Health** layout — a migration (`145-seed-daily-post-widget.js`) seeds it into existing installs' persisted Health layout, so current users get it too, not just fresh installs — and is addable to any layout. (`server/services/meatspacePost.js`, `client/src/components/DailyPostWidget.jsx`, `client/src/components/dashboard/widgetRegistry.jsx`, `server/services/dashboardLayouts.js`, `scripts/migrations/145-seed-daily-post-widget.js`)diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex 83b4bc3cd9..a07be8cd34 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -5,7 +5,7 @@ import AppContextPicker from '../AppContextPicker';import * as api from '../../services/api';import { processScreenshotUploads, processAttachmentUploads } from '../../utils/fileUpload';import { formatBytes } from '../../utils/formatters';-import { filterSelectableModels, isTuiProvider, isCliProvider } from '../../utils/providers';+import { filterSelectableModels, isTuiProvider, isCliProvider, isProcessProvider } from '../../utils/providers';import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from './constants';import ReviewerPicker from './ReviewerPicker';@@ -68,12 +68,25 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fareturn () => { cancelled = true; };}, []);- // Memoize enabled providers for dropdown+ // Memoize enabled providers for the dropdown — restricted to CODING providers+ // (CLI/TUI agents with a file-writing harness). HTTP `api` providers (raw+ // Ollama / LM Studio / nvidia-kimi) return plain text and can't write files, so+ // they're not valid task runners; a user who only has those should use the+ // "Clawed Ollama" sample (a `claude` CLI pointed at Ollama) instead.const enabledProviders = useMemo(() =>- providers?.filter(p => p.enabled) || [],+ providers?.filter(p => p.enabled && isProcessProvider(p)) || [],[providers]);+ // True when the user has enabled providers but ALL of them are HTTP `api`+ // providers (Ollama / LM Studio / kimi) — none can run file-writing tasks.+ // Surface the harness-boundary advisory so they aren't left with an empty+ // dropdown and no explanation.+ const apiOnlyProviders = useMemo(() => {+ const enabled = providers?.filter(p => p.enabled) || [];+ return enabled.length > 0 && enabledProviders.length === 0;+ }, [providers, enabledProviders]);+// Check if selected app has JIRA configuredconst selectedApp = useMemo(() =>apps?.find(a => a.id === newTask.app),@@ -539,6 +552,11 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa</div>) : null}</div>+ {apiOnlyProviders && (+ <div className="px-3 py-2 bg-port-warning/10 border border-port-warning/40 rounded-lg text-xs text-port-warning">+ Your enabled providers (Ollama / LM Studio) are HTTP API providers with no file-writing harness, so they can't run agent tasks. Add the <span className="font-semibold">Clawed Ollama</span> sample provider (a <code>claude</code> CLI pointed at your local model) from AI Providers → Add Sample to run file-writing tasks on a local model.+ </div>+ )}{/* Screenshot and Attachment Upload */}<div className="flex items-center gap-3 flex-wrap"><buttondiff --git a/client/src/utils/providers.js b/client/src/utils/providers.jsindex 3fd5f8b0c8..5273bfd9b8 100644--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@ -91,6 +91,36 @@ export const isVisionModel = (id) =>// Mirror of VISION_RE in server/lib/localModelHeuristics.js — keep in lockstep./(?:^|[-_/:])vision(?:[-_/:.]|$)|(?:^|[-_/:])vl(?:\d|[-_/:.]|$)|qwen[\d.]*-?vl|llava|bakllava|moondream|minicpm-?v|pixtral|gemma-?3|smolvlm|internvl|cogvlm|glm-?4v|phi-?3\.5?-vision|phi-?4-multimodal|got-ocr|idefics|fuyu|paligemma|kosmos|nanollava/i.test(id);+/**+ * Tool-use (function-calling) capable model detector — mirror of `isToolUseModel`+ * in server/lib/localModelHeuristics.js (and the TOOL_USE_RE inlined in+ * server/lib/aiToolkit/providers.js). Keep all three in lockstep (the server libs+ * can't be imported here). Ollama's /api/show `tools` capability is authoritative+ * when known; this id regex is the fallback for bare model-id strings. The CoS+ * agent harness depends on reliable tool-calling, so only these families should+ * be selectable for a local-model-backed coding provider.+ * @param {string} id+ * @returns {boolean}+ */+export const isToolUseModel = (id) =>+ typeof id === 'string' && id.length > 0 &&+ // Mirror of TOOL_USE_RE in server/lib/localModelHeuristics.js — keep in lockstep.+ /qwen|llama-?3\.[1-9]|llama-?4|mistral|mixtral|ministral|codestral|devstral|magistral|command-?r|command-?a|firefunction|functionary|watt-tool|hermes|glm-?4|granite-?3|gpt-oss|nemotron|smollm2|deepseek-v3|deepseek-r1/i.test(id);++/**+ * Per-model filter for a CODING / tool-use picker: restrict LOCAL backends+ * (Ollama / LM Studio) to tool-use-capable models by id, but leave cloud/API+ * providers' lists untouched — `isToolUseModel` is a local-name heuristic and+ * would wrongly hide capable cloud models whose ids don't encode their family.+ * Mirrors `visionLocalModelFilter`. Pass as+ * `useProviderModels({ modelFilter: toolUseLocalModelFilter })`.+ * @param {string} id+ * @param {{endpoint?:string,name?:string}} [provider]+ * @returns {boolean}+ */+export const toolUseLocalModelFilter = (id, provider) =>+ localBackendForProvider(provider) ? isToolUseModel(id) : true;+/*** Selectable models for a generation/chat picker: drops internal sentinels AND* embedding-only models. Use anywhere the user picks a model that will run adiff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.jsindex e709a49ff5..d8e0d70b57 100644--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@ -8,6 +8,8 @@ import {isEmbeddingModel,isVisionModel,visionLocalModelFilter,+ isToolUseModel,+ toolUseLocalModelFilter,localBackendForProvider,effectiveModelContextWindow,mergeModelLists,@@ -219,6 +221,38 @@ describe('isVisionModel (mirror of server localModelHeuristics)', () => {});});+describe('isToolUseModel (mirror of server localModelHeuristics)', () => {+ it('flags known tool-use-capable model ids', () => {+ for (const id of [+ 'qwen2.5:7b', 'qwen3:32b', 'llama3.1:8b', 'llama3.3:70b',+ 'mistral-small:24b', 'mixtral:8x7b', 'command-r:35b', 'hermes3:8b', 'glm-4:9b', 'gpt-oss:20b',+ ]) {+ expect(isToolUseModel(id), id).toBe(true);+ }+ });++ it('does not flag non-tool families or non-strings', () => {+ for (const id of ['llama3:8b', 'gemma2:9b', 'phi3:mini', 'nomic-embed-text', '']) {+ expect(isToolUseModel(id), id).toBe(false);+ }+ expect(isToolUseModel(null)).toBe(false);+ });+});++describe('toolUseLocalModelFilter', () => {+ it('restricts local backends to tool-use models', () => {+ const ollama = { name: 'Ollama', endpoint: 'http://localhost:11434/v1' };+ expect(toolUseLocalModelFilter('qwen2.5:7b', ollama)).toBe(true);+ expect(toolUseLocalModelFilter('gemma2:9b', ollama)).toBe(false);+ });++ it('leaves cloud/CLI providers untouched', () => {+ const cloud = { name: 'OpenAI', endpoint: 'https://api.openai.com/v1' };+ expect(toolUseLocalModelFilter('gpt-4o', cloud)).toBe(true);+ expect(toolUseLocalModelFilter('anything', undefined)).toBe(true);+ });+});+describe('localBackendForProvider', () => {it('detects Ollama by endpoint or name', () => {expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');diff --git a/docs/examples/README.md b/docs/examples/README.mdnew file mode 100644index 0000000000..5e498bcda3--- /dev/null+++ b/docs/examples/README.md@@ -0,0 +1,32 @@+# Example config files++## `claude-code-ollama-settings.json`++A copy-ready `~/.claude/settings.json` that points the **stock `claude` CLI** at a+local Ollama daemon, so every Claude Code session (interactive *and* the agent+harness PortOS spawns for CoS tasks) generates tokens from a local model while+keeping the full Read/Write/Edit/Bash tool harness.++| Field | Why |+| --- | --- |+| `ANTHROPIC_BASE_URL` | Your Ollama host. **No `/v1` suffix** — Claude Code appends the Anthropic path itself. Use `http://<remote-host>:11434` for a remote box. Requires **Ollama ≥ 0.14**, which natively serves the Anthropic Messages API; for LM Studio / vLLM / older Ollama, put **LiteLLM** in front to translate (avoid LiteLLM `1.82.7`/`1.82.8` — shipped malware). |+| `ANTHROPIC_AUTH_TOKEN` | Any non-empty value (`ollama`) — local backends don't check it. |+| `ANTHROPIC_DEFAULT_*_MODEL` | Map each Claude tier to a local model id. |+| `ANTHROPIC_SMALL_FAST_MODEL` | **Must** map to a local model — Claude Code uses a small/fast model for background work and will otherwise try to reach an unreachable Haiku. |++### Two ways to use it++- **Global (`~/.claude/settings.json`)** — copy this file's `env` block in. The stock+ `claude-code` provider in PortOS then works as-is, with no custom provider. Downside:+ it routes *all* local `claude` usage (interactive too) through Ollama.+- **Scoped (recommended)** — add the **Clawed Ollama** sample provider in PortOS+ (AI Providers → Add Sample). It carries the same env *per provider*, so you keep+ cloud Claude and a local-model option side by side and pick per task. See+ [docs/features/clawed-ollama.md](../features/clawed-ollama.md).++> ⚠️ **Tool-use caveat.** The agent harness depends on reliable tool-calling. Small+> generic models (Mistral 7B, base Llama, etc.) "run" but fail ~35–85% of tool calls+> and silently stop writing files. Use a tool-capable model — **Qwen 2.5/3, Llama+> 3.1+, Mistral Small 24B, GLM-4, Granite 3, gpt-oss**. Q4_K_M is the practical quant+> floor. The Clawed Ollama provider's model refresh filters its list to tool-capable+> models for you.diff --git a/docs/examples/claude-code-ollama-settings.json b/docs/examples/claude-code-ollama-settings.jsonnew file mode 100644index 0000000000..009a244b43--- /dev/null+++ b/docs/examples/claude-code-ollama-settings.json@@ -0,0 +1,10 @@+{+ "env": {+ "ANTHROPIC_BASE_URL": "http://127.0.0.1:11434",+ "ANTHROPIC_AUTH_TOKEN": "ollama",+ "ANTHROPIC_DEFAULT_OPUS_MODEL": "qwen3:32b",+ "ANTHROPIC_DEFAULT_SONNET_MODEL": "qwen3:32b",+ "ANTHROPIC_DEFAULT_HAIKU_MODEL": "qwen2.5:7b",+ "ANTHROPIC_SMALL_FAST_MODEL": "qwen2.5:7b"+ }+}diff --git a/docs/features/clawed-ollama.md b/docs/features/clawed-ollama.mdnew file mode 100644index 0000000000..6da4c5625c--- /dev/null+++ b/docs/features/clawed-ollama.md@@ -0,0 +1,63 @@+# Clawed Ollama — run CoS agent tasks on a local model++**Clawed Ollama** lets a user whose only LLM is **Ollama / LM Studio** run+file-writing **CoS agent tasks** — create/edit files, run tests, ship a PR — by+running the **Claude Code harness on top of a local model**.++## Why a special provider?++PortOS has two provider classes:++- **`cli` / `tui`** (claude, codex, agy) — spawned as a child process in the agent+ worktree. The CLI owns the Read/Write/Edit/Bash **tool harness**, so it can write+ files. CoS agent tasks run only on these.+- **`api`** (Ollama, LM Studio, nvidia-kimi) — an HTTP request that returns **plain+ text**. No harness, no file writes. Great for planning/vision/ask, but a task that+ needs to edit files produces a transcript and writes nothing.++Claude Code's harness is **independent of which model serves tokens**. Point the+`claude` CLI at a local model via `ANTHROPIC_BASE_URL` and you keep the *entire*+file-editing harness while Ollama does the generation. **Clawed Ollama** is exactly+that: a `cli` provider (`command: claude`) whose `envVars` route Claude Code to your+Ollama daemon, with its model list pulled live from Ollama.++## Setup++1. **Install the `claude` CLI on the PortOS host** — `npm i -g @anthropic-ai/claude-code`+ (the harness runs locally; only token generation is remote).+2. **Run Ollama ≥ 0.14** (locally or on a remote box) — it natively serves the+ Anthropic Messages API, so no proxy is needed. (LM Studio / vLLM / older Ollama:+ put **LiteLLM** in front to translate Anthropic ↔ OpenAI.)+3. **Add the sample provider** — in PortOS, **AI Providers → Add Sample → "Clawed+ Ollama (local model)"**. Edit `ANTHROPIC_BASE_URL` if your Ollama isn't on+ `localhost:11434` (e.g. `http://<remote-host>:11434`).+4. **Refresh models** — hit the provider's **Refresh Models** button. PortOS pulls the+ installed Ollama models and **keeps only the tool-use-capable ones** (the harness+ depends on reliable tool-calling), then pick a default.+5. **Run a task** — set Clawed Ollama as the active provider (or pin it per task) and+ create a CoS agent task. It now writes files and ships a PR backed by your local model.++The provider is `enabled: false` by default — adopting the sample doesn't change your+active provider until you choose it.++## Coding-task restrictions++- The **task form only offers coding providers** (CLI/TUI). Raw Ollama / LM Studio /+ kimi (`api`) providers are not file-writing runners and are excluded. If your only+ enabled providers are `api`-type, the form shows an advisory pointing you here.+- A server-side guard in `agentProviderResolution` rejects an `api` provider that+ reaches the spawn path (via a task pin or the fallback chain) with a clear error,+ rather than spawning a child process that can't write files.+- Clawed Ollama's model list is filtered to **tool-use-capable** models (Qwen 2.5/3,+ Llama 3.1+, Mistral/Mixtral, Cohere Command, GLM-4, Granite 3, gpt-oss, Hermes, …).++## ⚠️ Tool-use caveat++Small generic models (Mistral 7B, base Llama, Phi) **"run" but fail ~35–85% of tool+calls** and silently stop editing files mid-task. Use a tool-capable model and treat+**Q4_K_M** as the practical quant floor. The model-list filter steers you toward+reliable families, but a model that *reports* the `tools` capability can still be weak+in practice — prefer ≥7B instruction-tuned models from the families above.++See [docs/examples/claude-code-ollama-settings.json](../examples/claude-code-ollama-settings.json)+for the equivalent global `~/.claude/settings.json` approach.diff --git a/docs/features/cos-agent-runner.md b/docs/features/cos-agent-runner.mdindex b1afac944a..5c7ed4a144 100644--- a/docs/features/cos-agent-runner.md+++ b/docs/features/cos-agent-runner.md@@ -43,3 +43,4 @@ A separate `portos-cos` PM2 process that:- [Chief of Staff](./chief-of-staff.md) - Main orchestration system- [Error Handling](./error-handling.md) - Agent error recovery+- [Clawed Ollama](./clawed-ollama.md) - Run agent tasks on a local Ollama/LM Studio modeldiff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 571ddcd3d2..80b33fbe37 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -38,6 +38,25 @@"secretEnvVars": ["AWS_BEARER_TOKEN_BEDROCK"],"headlessArgs": ["--no-session-persistence", "--disable-slash-commands", "--tools", ""]},+ "clawed-ollama": {+ "id": "clawed-ollama",+ "name": "Clawed Ollama (local model)",+ "type": "cli",+ "command": "claude",+ "args": ["--print"],+ "models": [],+ "defaultModel": null,+ "ollamaBacked": true,+ "timeout": 600000,+ "enabled": false,+ "envVars": {+ "ANTHROPIC_BASE_URL": "http://localhost:11434",+ "ANTHROPIC_AUTH_TOKEN": "ollama",+ "ANTHROPIC_SMALL_FAST_MODEL": "qwen2.5:7b"+ },+ "secretEnvVars": [],+ "headlessArgs": ["--no-session-persistence", "--disable-slash-commands", "--tools", ""]+ },"codex": {"id": "codex","name": "Codex CLI",diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 98c9a55ec1..7ed53efa7e 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -20,6 +20,56 @@ const DEFAULT_SAMPLE_PATH = join(__dirname, 'defaults/providers.sample.json');const execFileAsync = promisify(execFile);+// Tool-use (function-calling) capable model families. Inlined here because the+// aiToolkit is self-contained (no imports out to server/lib). MIRROR of+// TOOL_USE_RE in server/lib/localModelHeuristics.js and isToolUseModel in+// client/src/utils/providers.js — keep all three in lockstep.+const TOOL_USE_RE = new RegExp([+ 'qwen',+ 'llama-?3\\.[1-9]', 'llama-?4',+ 'mistral', 'mixtral', 'ministral', 'codestral', 'devstral', 'magistral',+ 'command-?r', 'command-?a',+ 'firefunction', 'functionary', 'watt-tool', 'hermes',+ 'glm-?4',+ 'granite-?3',+ 'gpt-oss',+ 'nemotron',+ 'smollm2',+ 'deepseek-v3', 'deepseek-r1',+].join('|'), 'i');++/**+ * A CLI provider (command `claude`) is "Ollama-backed" — the Clawed Ollama+ * pattern — when it carries the `ollamaBacked` marker or its ANTHROPIC_BASE_URL+ * points at an Ollama daemon. Such a provider runs the full Claude Code harness+ * but generates tokens from a local model, so its model list must come from+ * Ollama (filtered to tool-use-capable models) rather than the static Anthropic list.+ */+function isOllamaBackedProvider(provider) {+ if (provider?.ollamaBacked === true) return true;+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || '');+ return /:11434\b/.test(base) || /ollama/i.test(base);+}++/** Normalize an Ollama base URL (strip trailing slash + an OpenAI-compat `/v1`). */+function ollamaBaseFromProvider(provider) {+ const base = String(provider?.envVars?.ANTHROPIC_BASE_URL || provider?.endpoint || 'http://localhost:11434');+ return base.replace(/\/+$/, '').replace(/\/v1$/, '');+}++/**+ * Whether an Ollama model supports tool use. Prefers the authoritative `tools`+ * capability from /api/show (a non-empty capabilities array without `tools` is+ * an explicit negative); falls back to the id heuristic when capabilities are+ * unavailable (daemon hiccup / older Ollama).+ */+function ollamaModelSupportsTools(id, capabilities) {+ if (Array.isArray(capabilities) && capabilities.length > 0) {+ return capabilities.some((c) => String(c).toLowerCase() === 'tools');+ }+ return TOOL_USE_RE.test(String(id || ''));+}+const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';const CODEX_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];const ANTIGRAVITY_MODEL_KEYS = ['defaultModel', 'lightModel', 'mediumModel', 'heavyModel'];@@ -324,6 +374,9 @@ export function createProviderService(config = {}) {contextWindow: providerData.contextWindow || null,timeout: providerData.timeout || 300000,enabled: providerData.enabled !== false,+ // Clawed Ollama marker — preserve so adopting the sample via POST drives+ // ollama-backed model refresh (see isOllamaBackedProvider).+ ...(providerData.ollamaBacked === true ? { ollamaBacked: true } : {}),envVars: providerData.envVars || {},secretEnvVars: providerData.secretEnvVars || [],headlessArgs: providerData.headlessArgs || [],@@ -507,6 +560,14 @@ export function createProviderService(config = {}) {async _refreshCLIProviderModels(provider) {const providerName = provider.name.toLowerCase();+ // Clawed Ollama: a `claude` CLI pointed at a local Ollama daemon. Pull the+ // installed Ollama models (filtered to tool-use-capable ones — the agent+ // harness depends on reliable tool-calling) instead of the static Anthropic+ // list. Checked BEFORE the generic claude branch below.+ if (isOllamaBackedProvider(provider)) {+ return await this._fetchOllamaToolCapableModels(provider);+ }+if (providerName.includes('claude') || provider.command === 'claude') {return await this._fetchAnthropicModels(provider);}@@ -522,6 +583,33 @@ export function createProviderService(config = {}) {throw new Error('Model refresh not supported for this CLI provider');},+ async _fetchOllamaToolCapableModels(provider) {+ const base = ollamaBaseFromProvider(provider);+ const res = await fetch(`${base}/api/tags`, { signal: AbortSignal.timeout(8000) }).catch(() => null);+ if (!res?.ok) {+ throw new Error(`Ollama unreachable at ${base} (HTTP ${res?.status || 'error'})`);+ }+ const data = await res.json().catch(() => null);+ const names = (data?.models || []).map(m => m.name || m.model).filter(Boolean);++ // Query /api/show per model for the authoritative `tools` capability; fall+ // back to the id heuristic when the daemon doesn't answer. Filter to+ // tool-use-capable models only — a Claude harness on a non-tool model+ // "runs" but silently fails to edit files.+ const checked = await Promise.all(names.map(async (name) => {+ const showRes = await fetch(`${base}/api/show`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: name, name }),+ signal: AbortSignal.timeout(8000)+ }).catch(() => null);+ const showData = showRes?.ok ? await showRes.json().catch(() => null) : null;+ const capabilities = Array.isArray(showData?.capabilities) ? showData.capabilities : null;+ return ollamaModelSupportsTools(name, capabilities) ? name : null;+ }));+ return checked.filter(Boolean);+ },+async _fetchAnthropicModels(_provider) {return ['claude-opus-4-8',diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex f5bfd893cb..a1530ef7f0 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -593,6 +593,63 @@ describe('Provider Service', () => {});});+ describe('Clawed Ollama (ollama-backed CLI) model refresh', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ // Mock fetch for an Ollama daemon: /api/tags lists models, /api/show reports+ // per-model capabilities. `caps[name]` controls which models report `tools`.+ const stubOllama = (names, caps) => {+ vi.stubGlobal('fetch', vi.fn(async (url, opts) => {+ if (String(url).endsWith('/api/tags')) {+ return { ok: true, json: async () => ({ models: names.map((n) => ({ name: n })) }) };+ }+ if (String(url).endsWith('/api/show')) {+ const body = JSON.parse(opts?.body || '{}');+ const capabilities = caps[body.model];+ return { ok: true, json: async () => (capabilities ? { capabilities } : {}) };+ }+ return { ok: false, status: 404 };+ }));+ };++ it('pulls Ollama models filtered to tool-use-capable ones (by capabilities)', async () => {+ stubOllama(['qwen2.5:7b', 'gemma2:9b', 'llama3.1:8b'], {+ 'qwen2.5:7b': ['completion', 'tools'],+ 'gemma2:9b': ['completion', 'vision'], // no tools → excluded+ 'llama3.1:8b': ['completion', 'tools'],+ });++ const p = await providerService.createProvider({+ name: 'Clawed Ollama (local model)',+ type: 'cli',+ command: 'claude',+ ollamaBacked: true,+ envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11434', ANTHROPIC_AUTH_TOKEN: 'ollama' },+ });++ const updated = await providerService.refreshProviderModels(p.id);+ expect(updated).not.toBeNull();+ expect(updated.models).toEqual(['qwen2.5:7b', 'llama3.1:8b']);+ });++ it('falls back to the id heuristic when /api/show reports no capabilities', async () => {+ stubOllama(['qwen2.5:7b', 'gemma2:9b'], {}); // no capabilities reported for any++ const p = await providerService.createProvider({+ name: 'Clawed Ollama',+ type: 'cli',+ command: 'claude',+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434' },+ });++ const updated = await providerService.refreshProviderModels(p.id);+ // qwen matches the tool-use heuristic; gemma2 does not.+ expect(updated.models).toEqual(['qwen2.5:7b']);+ });+ });+describe('_refreshAPIProviderModels — network layer', () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/server/lib/aiToolkit/validation.js b/server/lib/aiToolkit/validation.jsindex 337d9e98a2..ec068fd1fc 100644--- a/server/lib/aiToolkit/validation.js+++ b/server/lib/aiToolkit/validation.js@@ -34,6 +34,10 @@ export const providerSchema = z.object({contextWindow: z.number().int().min(512).max(2097152).nullable().optional(),timeout: z.number().int().min(1000).max(1800000).optional(),enabled: z.boolean().optional(),+ // Marks a CLI provider (command `claude`) whose ANTHROPIC_BASE_URL points at a+ // local Ollama daemon — the "Clawed Ollama" pattern. Drives model refresh to+ // pull tool-use-capable Ollama models instead of the static Anthropic list.+ ollamaBacked: z.boolean().optional(),envVars: z.record(z.string()).optional(),secretEnvVars: z.array(z.string()).optional(),headlessArgs: z.array(z.string()).optional(),diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.jsindex 3c740a0b11..7fb04e91ed 100644--- a/server/lib/localModelHeuristics.js+++ b/server/lib/localModelHeuristics.js@@ -108,6 +108,55 @@ export function isVisionModel(model) {return typeof id === 'string' && VISION_RE.test(id);}+// Tool-use (function-calling) capable model families. The CoS agent harness+// (Read/Write/Edit/Bash + the agent loop) depends entirely on reliable+// tool-calling, so a Claude-on-Ollama ("Clawed Ollama") provider must only+// surface models that can actually drive tools. Ollama's /api/show reports a+// `tools` capability that is authoritative when present — this id regex is the+// fallback for bare model-id strings (e.g. LM Studio, or a stored provider+// `models` list). Matches the families with dependable function-calling support+// (Qwen 2.5/3, Llama 3.1+, Mistral/Mixtral, Cohere Command, Hermes, GLM-4,+// Granite 3, gpt-oss, Nemotron, function-calling-specialized models). Llama 3.0+// is deliberately NOT matched (tool use landed in 3.1).+//+// MIRRORED in client/src/utils/providers.js (isToolUseModel) and inlined in+// server/lib/aiToolkit/providers.js (TOOL_USE_RE) — keep all three in lockstep.+const TOOL_USE_RE = new RegExp([+ 'qwen',+ 'llama-?3\\.[1-9]', 'llama-?4',+ 'mistral', 'mixtral', 'ministral', 'codestral', 'devstral', 'magistral',+ 'command-?r', 'command-?a',+ 'firefunction', 'functionary', 'watt-tool', 'hermes',+ 'glm-?4',+ 'granite-?3',+ 'gpt-oss',+ 'nemotron',+ 'smollm2',+ 'deepseek-v3', 'deepseek-r1',+].join('|'), 'i');++/**+ * Detect a tool-use (function-calling) capable model from its id and/or backend+ * capability metadata. Prefers explicit metadata: Ollama's /api/show reports a+ * `tools` capability, which is authoritative in BOTH directions — a capabilities+ * array that lists `tools` confirms support, and a non-empty array WITHOUT it is+ * an explicit negative (don't regex-guess past it). Falls back to the id regex+ * only when no capability metadata is available (bare id strings, LM Studio).+ *+ * @param {string|{id?:string,name?:string,capabilities?:string[]}} model+ * @returns {boolean}+ */+export function isToolUseModel(model) {+ if (!model) return false;+ if (typeof model === 'string') return TOOL_USE_RE.test(model);+ if (typeof model !== 'object') return false;+ if (Array.isArray(model.capabilities) && model.capabilities.length > 0) {+ return model.capabilities.some((c) => String(c).toLowerCase() === 'tools');+ }+ const id = model.id || model.name || '';+ return typeof id === 'string' && TOOL_USE_RE.test(id);+}+// Families ranked for EDITORIAL FIX GENERATION, best-first. This task needs// tight instruction-following and clean, constrained output (rewrite a passage,// emit only the rewrite) — NOT chatty long-form generation. So instruction-tuneddiff --git a/server/lib/localModelHeuristics.test.js b/server/lib/localModelHeuristics.test.jsindex eb7adc7fec..402d971f8a 100644--- a/server/lib/localModelHeuristics.test.js+++ b/server/lib/localModelHeuristics.test.js@@ -1,7 +1,58 @@import { describe, it, expect } from 'vitest';-import { isEmbeddingModel, isGenerationModel, isVisionModel, isVisionCapableCliProvider, recommendEditorialModel } from './localModelHeuristics.js';+import { isEmbeddingModel, isGenerationModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel, recommendEditorialModel } from './localModelHeuristics.js';describe('localModelHeuristics', () => {+ describe('isToolUseModel', () => {+ it('flags known tool-use-capable families by id', () => {+ for (const id of [+ 'qwen2.5:7b',+ 'qwen3:32b',+ 'qwen2.5-coder:14b',+ 'llama3.1:8b',+ 'llama3.3:70b',+ 'mistral-small:24b',+ 'mixtral:8x7b',+ 'command-r:35b',+ 'hermes3:8b',+ 'glm-4:9b',+ 'granite3-dense:8b',+ 'gpt-oss:20b',+ ]) {+ expect(isToolUseModel(id), id).toBe(true);+ }+ });++ it('does not flag families without dependable tool use by id', () => {+ for (const id of [+ 'llama3:8b', // Llama 3.0 — tool use landed in 3.1+ 'gemma2:9b',+ 'phi3:mini',+ 'orca-mini',+ 'nomic-embed-text',+ ]) {+ expect(isToolUseModel(id), id).toBe(false);+ }+ });++ it('prefers explicit capability metadata in both directions', () => {+ // `tools` present → true even when the id wouldn't match.+ expect(isToolUseModel({ id: 'some-custom-model', capabilities: ['completion', 'tools'] })).toBe(true);+ // Non-empty capabilities WITHOUT `tools` → explicit negative, even when the+ // id family would otherwise match the heuristic.+ expect(isToolUseModel({ id: 'qwen2.5:7b', capabilities: ['completion', 'vision'] })).toBe(false);+ // No capability metadata → fall back to the id heuristic.+ expect(isToolUseModel({ id: 'qwen2.5:7b' })).toBe(true);+ expect(isToolUseModel({ id: 'gemma2:9b' })).toBe(false);+ });++ it('handles falsy / non-model inputs', () => {+ expect(isToolUseModel(null)).toBe(false);+ expect(isToolUseModel(undefined)).toBe(false);+ expect(isToolUseModel(42)).toBe(false);+ expect(isToolUseModel('')).toBe(false);+ });+ });+describe('isEmbeddingModel', () => {it('flags known embedding models', () => {for (const id of [diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.jsindex dbe8ba6f32..8dca0e6d05 100644--- a/server/services/agentProviderResolution.js+++ b/server/services/agentProviderResolution.js@@ -89,6 +89,22 @@ export async function resolveAgentProviderAndModel(task) {}}+ // Harness boundary guard. `api`-type providers (Ollama / LM Studio / kimi over+ // HTTP) return plain text with NO filesystem tool harness — they can't+ // Read/Write/Edit/Bash, so a CoS agent task resolved onto one would spawn a+ // child process that writes nothing to disk. Fail clearly instead. This catches+ // an api provider arriving via a task pin OR via the fallback chain (the default+ // fallback priority includes lmstudio/ollama). The fix for users: add a CLI+ // coding provider — e.g. the "Clawed Ollama" sample (a `claude` CLI pointed at+ // Ollama) gives the full file-writing harness on a local model.+ if (provider.type === 'api') {+ return {+ ok: false,+ error: `Provider "${provider.id}" is an HTTP API provider with no file-writing harness — CoS agent tasks need a CLI/TUI coding provider (claude, codex, or the "Clawed Ollama" Claude-on-Ollama sample).`,+ providerId: provider.id+ };+ }+// Select optimal model for this task (async to allow learning-based suggestions)const modelSelection = await selectModelForTask(task, provider);let selectedModel = modelSelection.model;diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.jsindex 384f948b31..6c9d14d005 100644--- a/server/services/agentProviderResolution.test.js+++ b/server/services/agentProviderResolution.test.js@@ -46,7 +46,7 @@ describe('resolveAgentProviderAndModel', () => {});it('resolves the active provider + selected model on the happy path', async () => {- const provider = { id: 'p1', type: 'api', models: ['m-default'] };+ const provider = { id: 'p1', type: 'cli', models: ['m-default'] };getActiveProvider.mockResolvedValue(provider);const r = await resolveAgentProviderAndModel(TASK);expect(r.ok).toBe(true);@@ -56,7 +56,7 @@ describe('resolveAgentProviderAndModel', () => {});it('fails with providerId + status when unavailable and no fallback exists', async () => {- const provider = { id: 'p1', type: 'api' };+ const provider = { id: 'p1', type: 'cli' };getActiveProvider.mockResolvedValue(provider);isProviderAvailable.mockReturnValue(false);getProviderStatus.mockReturnValue({ message: 'usage-limit', reason: 'limit' });@@ -71,8 +71,8 @@ describe('resolveAgentProviderAndModel', () => {});it('switches to the fallback provider and pins its model when one is available', async () => {- const primary = { id: 'p1', type: 'api' };- const fallback = { id: 'p2', type: 'api', models: ['fb-model'] };+ const primary = { id: 'p1', type: 'cli' };+ const fallback = { id: 'p2', type: 'cli', models: ['fb-model'] };getActiveProvider.mockResolvedValue(primary);isProviderAvailable.mockReturnValue(false);getProviderStatus.mockReturnValue({ message: 'rate-limit', reason: 'rl' });@@ -87,8 +87,8 @@ describe('resolveAgentProviderAndModel', () => {});it('honors a user-specified provider and clears any fallback pin', async () => {- const active = { id: 'p1', type: 'api' };- const chosen = { id: 'p-user', type: 'api', models: ['m-default'] };+ const active = { id: 'p1', type: 'cli' };+ const chosen = { id: 'p-user', type: 'cli', models: ['m-default'] };getActiveProvider.mockResolvedValue(active);getProviderById.mockResolvedValue(chosen);@@ -105,8 +105,8 @@ describe('resolveAgentProviderAndModel', () => {// ever blocking the task (regression: the override used to run after the// active-provider availability check, so a pinned-but-healthy provider// still failed when the active one was down).- const active = { id: 'p-active', type: 'api' };- const chosen = { id: 'p-user', type: 'api', models: ['m-default'] };+ const active = { id: 'p-active', type: 'cli' };+ const chosen = { id: 'p-user', type: 'cli', models: ['m-default'] };getActiveProvider.mockResolvedValue(active);getProviderById.mockResolvedValue(chosen);isProviderAvailable.mockImplementation((id) => id === 'p-user'); // active down, pinned up@@ -119,7 +119,7 @@ describe('resolveAgentProviderAndModel', () => {});it('honors a pinned provider even when no active provider is configured', async () => {- const chosen = { id: 'p-user', type: 'api', models: ['m-default'] };+ const chosen = { id: 'p-user', type: 'cli', models: ['m-default'] };getActiveProvider.mockResolvedValue(null); // no active provider at allgetProviderById.mockResolvedValue(chosen);@@ -128,8 +128,37 @@ describe('resolveAgentProviderAndModel', () => {expect(r.provider).toBe(chosen);});+ it('rejects an api-type provider (no file-writing harness) with a clear error', async () => {+ // Ollama / LM Studio over HTTP return plain text and can't run file-writing+ // agent tasks. Guard so they never reach the CLI spawn path.+ const provider = { id: 'ollama', type: 'api', models: ['qwen2.5:7b'] };+ getActiveProvider.mockResolvedValue(provider);++ const r = await resolveAgentProviderAndModel(TASK);+ expect(r.ok).toBe(false);+ expect(r.providerId).toBe('ollama');+ expect(r.error).toContain('no file-writing harness');+ // Guard fires before model selection — never spawns.+ expect(selectModelForTask).not.toHaveBeenCalled();+ });++ it('rejects an api-type provider even when reached via the fallback chain', async () => {+ const primary = { id: 'p1', type: 'cli' };+ const apiFallback = { id: 'lmstudio', type: 'api', models: ['m'] };+ getActiveProvider.mockResolvedValue(primary);+ isProviderAvailable.mockReturnValue(false);+ getProviderStatus.mockReturnValue({ message: 'down', reason: 'x' });+ getAllProviders.mockResolvedValue({ providers: [primary, apiFallback] });+ getFallbackProvider.mockResolvedValue({ provider: apiFallback, model: 'm', source: 'provider' });++ const r = await resolveAgentProviderAndModel(TASK);+ expect(r.ok).toBe(false);+ expect(r.providerId).toBe('lmstudio');+ expect(r.error).toContain('no file-writing harness');+ });+it('falls back to the provider tier default when the selected model is not in the provider model list', async () => {- const provider = { id: 'p1', type: 'api', models: ['only-this'], heavyModel: 'heavy-x' };+ const provider = { id: 'p1', type: 'cli', models: ['only-this'], heavyModel: 'heavy-x' };getActiveProvider.mockResolvedValue(provider);selectModelForTask.mockResolvedValue({ model: 'not-listed', tier: 'heavy', reason: 'heavy task' });