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: let Ollama-backed agent harnesses run on a real context window
Adam Eivy5662b7e5a2cd
diff --git a/.changelog/next/fixed-agent-d0298607.md b/.changelog/next/fixed-agent-d0298607.mdnew file mode 100644index 0000000000..ae34cdfc20--- /dev/null+++ b/.changelog/next/fixed-agent-d0298607.md@@ -0,0 +1 @@+- Ollama-backed agent harnesses (Claude Ollama / OpenCode Ollama) no longer die mid-task on a 32K context window: "Local num_ctx" is now settable on Ollama-backed CLI/TUI providers (it was API-only), PortOS reloads the Ollama daemon at that window before the run since a CLI harness talks to Ollama directly, the Local LLM card shows the window loaded models are actually running at, and the `exceed_context_size_error` 400 is classified as its own actionable failure instead of a generic bad-request.diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 8985c5d75e..7a88abf570 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -133,6 +133,13 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAcconst statusColor = data?.available ? 'bg-port-success' : data?.installed ? 'bg-port-warning' : 'bg-gray-600';const startupService = backend.id === 'ollama' ? data?.service : null;const runsAtStartup = Boolean(startupService?.runAtStartup);+ // The window resident models were ACTUALLY loaded at — Ollama picks it from+ // VRAM (4K/32K/256K), and an agent harness that overruns it dies mid-task with+ // a 400. Null while nothing is resident, since Ollama hasn't committed yet.+ const runtimeContext = backend.id === 'ollama' ? data?.contextLength?.runtime ?? null : null;+ const runtimeContextLabel = formatContextLength(runtimeContext);+ const contextBelowAgentFloor = runtimeContext != null+ && runtimeContext < (data?.contextLength?.agentMinimum ?? 0);return (<div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">@@ -164,6 +171,16 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc</span>)}{startupService?.supported && <> · {runsAtStartup ? 'runs at login' : 'startup off'}</>}+ {runtimeContextLabel && (+ <span+ className={contextBelowAgentFloor ? 'text-port-warning' : undefined}+ title={contextBelowAgentFloor+ ? `Loaded models are running at ${runtimeContextLabel} — below what an agent harness (Claude Ollama / OpenCode Ollama) usually needs. Set "Local num_ctx" on that provider in AI Providers to reload Ollama at a larger window.`+ : `Loaded models are running at ${runtimeContextLabel}`}+ >+ {' · '}{runtimeContextLabel}+ </span>+ )}</div>{!data?.installed && (diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 391083e1df..cc98bc4c69 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -117,3 +117,36 @@ describe('LocalLlmTab recommendations', () => {await waitFor(() => expect(screen.getByText('Qwen3.8 27B')).toBeTruthy());});});++describe('LocalLlmTab runtime context window', () => {+ // Ollama picks the runtime window from VRAM; a harness that overruns it dies+ // mid-task, so the card has to make the loaded window visible.+ const withContext = (contextLength) => {+ getLocalLlmStatus.mockResolvedValue({+ backend: 'ollama',+ ollama: { installed: true, available: true, modelCount: 0, models: [], contextLength },+ lmstudio: { installed: false, available: false, modelCount: 0, models: [] },+ });+ };++ it('flags a runtime window below the agent floor', async () => {+ withContext({ runtime: 32768, applied: null, agentMinimum: 65536 });+ await renderTab();+ const badge = screen.getByTitle(/below what an agent harness/);+ expect(badge.textContent).toContain('32K ctx');+ expect(badge.className).toMatch(/text-port-warning/);+ });++ it('shows a generous window without the warning styling', async () => {+ withContext({ runtime: 131072, applied: 131072, agentMinimum: 65536 });+ await renderTab();+ const badge = screen.getByTitle('Loaded models are running at 128K ctx');+ expect(badge.className || '').not.toMatch(/text-port-warning/);+ });++ it('shows nothing while no model is resident — Ollama has not picked a window yet', async () => {+ withContext({ runtime: null, applied: null, agentMinimum: 65536 });+ await renderTab();+ expect(screen.queryByTitle(/Loaded models are running at/)).toBeNull();+ });+});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 83a664a463..939f8b40b1 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -3,7 +3,7 @@ import { AlertTriangle } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, supportsModelRefresh, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider } from '../utils/providers';+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, supportsModelRefresh, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider } from '../utils/providers';import useLocalModels from '../hooks/useLocalModels';import BrailleSpinner from '../components/BrailleSpinner';import EmptyState from '../components/EmptyState';@@ -869,6 +869,17 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloconst plannedContextLabel = formatContextLength(effectiveModelContextWindow(formData, formData.defaultModel));+ // `num_ctx` is meaningful for any provider whose tokens come from Ollama, not+ // just `api` ones: an `api` provider sends it on every request, while an+ // Ollama-backed CLI/TUI (claude-ollama, opencode-ollama) talks to the daemon+ // itself, so PortOS applies it by reloading Ollama at that window before the+ // run (server/services/ollamaAgentContext.js). Gating the field to `api` left+ // those providers stuck on Ollama's VRAM-based 32K auto-pick, which an agent+ // harness overruns mid-task. Merged over the stored record rather than reading+ // formData alone — the `ollamaBacked` marker (what identifies opencode-ollama,+ // whose envVars carry no ANTHROPIC_BASE_URL) is not a form field, while+ // endpoint/envVars edits must still count immediately.+ const showsNumCtx = formData.type === 'api' || isOllamaBackedProvider({ ...provider, ...formData });const parseOptionalIntField = (value) => {const input = String(value ?? '').trim();if (!input) return null;@@ -896,7 +907,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloargs: formData.args ? formData.args.split(' ').filter(Boolean) : [],headlessArgs: formData.headlessArgs ? formData.headlessArgs.split(' ').filter(Boolean) : [],contextWindow: parseOptionalIntField(formData.contextWindow),- numCtx: formData.type === 'api' ? parseOptionalIntField(formData.numCtx) : null,+ numCtx: showsNumCtx ? parseOptionalIntField(formData.numCtx) : null,};// The generation/fallback pickers filter out embedding-only models, so a// stored embedding (from an older config) would be hidden in the UI yet@@ -1294,7 +1305,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAllo</p></FormField>- {formData.type === 'api' && (+ {showsNumCtx && (<FormField label="Local num_ctx"><inputtype="number"@@ -1307,7 +1318,9 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [], runnerAlloclassName="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"/><p className="text-xs text-gray-500 mt-1">- Sent to compatible local backends; used for planning when no model window is known.+ {formData.type === 'api'+ ? 'Sent to compatible local backends; used for planning when no model window is known.'+ : 'PortOS reloads the Ollama daemon at this window before the run — the CLI/TUI talks to Ollama directly, so nothing else can raise it. Leave blank to keep Ollama\'s VRAM-based auto-pick; make sure the model still fits at the larger size.'}</p></FormField>)}diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex a765015cab..8c782a21b2 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -293,3 +293,57 @@ describe('CoS Agent Runner allowlist warning', () => {));});});++describe('Local num_ctx field', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getApps.mockResolvedValue([]);+ api.getRuns.mockResolvedValue({ runs: [] });+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ });++ const openEditorFor = async (provider) => {+ api.getProviders.mockResolvedValue({ providers: [provider], activeProvider: provider.id });+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));+ };++ // An Ollama-backed TUI reaches the daemon itself, so num_ctx is the ONLY way+ // to lift it off Ollama's VRAM-based auto-pick. It used to be `api`-only.+ it('offers num_ctx on an Ollama-backed TUI provider and saves it', async () => {+ await openEditorFor({+ id: 'claude-ollama-tui',+ name: 'Claude Ollama TUI',+ type: 'tui',+ command: 'claude',+ enabled: true,+ ollamaBacked: true,+ models: [],+ envVars: {},+ });++ const numCtx = await screen.findByLabelText('Local num_ctx');+ fireEvent.change(numCtx, { target: { value: '131072' } });++ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(api.updateProvider).toHaveBeenCalledWith(+ 'claude-ollama-tui',+ expect.objectContaining({ numCtx: 131072 }),+ ));+ });++ it('hides num_ctx on a cloud CLI provider, which has no Ollama daemon to reload', async () => {+ await openEditorFor({+ id: 'codex',+ name: 'Codex',+ type: 'cli',+ command: 'codex',+ enabled: true,+ models: ['gpt-5'],+ defaultModel: 'gpt-5',+ });++ await screen.findByLabelText('Planning Window');+ expect(screen.queryByLabelText('Local num_ctx')).toBeNull();+ });+});diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 75d41aadbb..26cd25e916 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -106,6 +106,42 @@ claude --version- OpenAI: `gpt-5`, `gpt-5-mini`- Ollama: Model must be pulled first (`ollama pull llama3`)+### Ollama-backed agent dies with "exceeds the available context size"++**Symptom**: a Claude Ollama / OpenCode Ollama session works for a while, then+stops with++```+API Error: 400 {"error":{"code":400,"message":"request (32768 tokens) exceeds the+available context size (32768 tokens), try increasing it",+"type":"exceed_context_size_error","n_prompt_tokens":32768,"n_ctx":32768}}+```++**Cause**: Ollama picks a model's runtime window from available VRAM+(`OLLAMA_CONTEXT_LENGTH` documents the default as "4k/32k/256k based on VRAM"),+so a 256K-capable model is commonly *loaded* at 32K. An agent harness ships a+system prompt, tool schemas, and a growing transcript, and sizes its own+compaction against the window it thinks it has — so it overruns the real one+without warning. The task isn't too big; the window is too small.++**Solution**: set **Local num_ctx** on the provider (AI Providers → the provider+→ Context Window). PortOS reloads the Ollama daemon at that window before the+next run, because a CLI/TUI harness talks to Ollama directly and nothing else+can raise it. `OLLAMA_CONTEXT_LENGTH` in the environment works as a machine-wide+fallback.++Two caveats:++- **Check the model still fits.** A larger window means a larger KV cache. Past+ what VRAM allows, Ollama silently offloads layers to CPU and the model becomes+ unusably slow rather than failing loudly. Raise it a step at a time.+- **A background service can't inherit the setting.** A launchd/systemd-managed+ `ollama serve` runs from its own unit file, so when a window is configured+ PortOS starts (or restarts) Ollama itself.++The Local LLM settings card shows the window loaded models are actually running+at, and flags it when it's below what an agent harness needs.+## Chief of Staff Issues### CoS Not Runningdiff --git a/server/lib/README.md b/server/lib/README.mdindex df6e077e9e..22683f8d26 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -286,6 +286,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. || `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. || `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |+| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. || `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. || `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. || `issueLength.js` | Per-issue size targets fed into text stages. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 44e05b9128..eefb4a66ab 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -266,6 +266,7 @@ export * from './huggingfaceModel.js';export * from './localLlmCatalog.js';export * from './localLlmDisk.js';export * from './localModelHeuristics.js';+export * from './ollamaContext.js';export * from './loraDataset.js';export * from './issueLength.js';export * from './investigationTasks.js';diff --git a/server/lib/ollamaContext.js b/server/lib/ollamaContext.jsnew file mode 100644index 0000000000..01368b32fc--- /dev/null+++ b/server/lib/ollamaContext.js@@ -0,0 +1,139 @@+/**+ * Ollama runtime context-window helpers.+ *+ * Ollama picks a model's runtime window (`n_ctx`) from available VRAM —+ * `OLLAMA_CONTEXT_LENGTH` documents the default as "4k/32k/256k based on VRAM".+ * That auto-pick is fine for a chat turn and far too small for an agent harness:+ * Claude Code / OpenCode ship a system prompt plus tool schemas plus a growing+ * transcript, and they size their own compaction against the window they *think*+ * they have (an Anthropic-sized one), not the window Ollama actually loaded. The+ * result is a run that works for an hour and then dies mid-task with+ * `exceed_context_size_error` at 100% prompt utilisation.+ *+ * The only lever that reaches those harnesses is the daemon default: they speak+ * Ollama's Anthropic/OpenAI-compatible endpoints directly, so PortOS cannot+ * attach a per-request `num_ctx` the way the toolkit runner does for `api`+ * providers. Hence `OLLAMA_CONTEXT_LENGTH` on the daemon PortOS starts.+ *+ * Pure — no I/O, no daemon calls. `server/services/ollamaManager.js` owns the+ * daemon side (starting/restarting with the resolved window) and+ * `server/services/ollamaAgentContext.js` owns the pre-spawn enforcement.+ */++/**+ * Smallest runtime window an Ollama-backed *agent harness* can realistically+ * finish a task in. Not a hard requirement — it is the threshold below which+ * PortOS warns before spawning, because 32K (the common VRAM auto-pick) is+ * routinely consumed by scaffold + tools + a few file reads.+ */+export const OLLAMA_AGENT_MIN_CONTEXT = 65536++/** Ollama's own env knob for the daemon-wide default window. */+export const OLLAMA_CONTEXT_ENV_VAR = 'OLLAMA_CONTEXT_LENGTH'++const positiveInt = (value) => {+ const n = Number(value)+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null+}++/**+ * The context window PortOS should hold the Ollama daemon at for `provider`.+ *+ * Explicit provider config wins (`numCtx` — the same field the toolkit runner+ * sends as a per-request `num_ctx` for `api` providers, reused here as "the+ * window this provider needs"), then the ambient `OLLAMA_CONTEXT_LENGTH`, then+ * `null`.+ *+ * `null` means **leave Ollama's VRAM-based auto-pick alone**. That is the+ * deliberate default: forcing a window larger than VRAM allows does not fail+ * loudly, it silently offloads layers to CPU and turns a fast local model into+ * an unusable one. Only the user knows their machine's headroom.+ *+ * @param {{numCtx?: number|null}|null|undefined} provider+ * @param {Record<string, string|undefined>} [env]+ * @returns {number|null}+ */+export function resolveOllamaContextLength(provider, env = process.env) {+ return positiveInt(provider?.numCtx) ?? positiveInt(env?.[OLLAMA_CONTEXT_ENV_VAR])+}++/**+ * Child env for `ollama serve`, carrying the resolved window. Returns `env`+ * untouched when `contextLength` is null so a PortOS-started daemon keeps+ * Ollama's own auto-pick unless someone asked for a specific window.+ *+ * @param {Record<string, string|undefined>} env+ * @param {number|null} contextLength+ * @returns {Record<string, string|undefined>}+ */+export function withOllamaContextEnv(env, contextLength) {+ const n = positiveInt(contextLength)+ if (!n) return env+ return { ...env, [OLLAMA_CONTEXT_ENV_VAR]: String(n) }+}++// Ollama's overflow rejection, in both the shapes it reaches us in: the JSON+// error body (`n_prompt_tokens` / `n_ctx`) and the human message the harness+// prints ("request (N tokens) exceeds the available context size (M tokens)").+// Matched independently so a truncated/re-wrapped copy of either still parses.+const OVERFLOW_TYPE_RE = /exceed_context_size_error/+const OVERFLOW_MESSAGE_RE = /request \((\d+) tokens?\) exceeds the available context size \((\d+) tokens?\)/i+const N_PROMPT_TOKENS_RE = /"n_prompt_tokens"\s*:\s*(\d+)/+const N_CTX_RE = /"n_ctx"\s*:\s*(\d+)/++/**+ * Recognize an Ollama context-overflow rejection in a chunk of agent output.+ *+ * Returns `null` for anything else — including a generic 400 — so callers can+ * use it as the guard for "is this the too-small-window failure?" rather than+ * pattern-matching the raw JSON at every call site.+ *+ * @param {string|null|undefined} text+ * @returns {{ promptTokens: number|null, contextLength: number|null }|null}+ */+export function parseOllamaContextOverflow(text) {+ const s = String(text || '')+ const message = s.match(OVERFLOW_MESSAGE_RE)+ if (!message && !OVERFLOW_TYPE_RE.test(s)) return null+ return {+ promptTokens: positiveInt(message?.[1]) ?? positiveInt(s.match(N_PROMPT_TOKENS_RE)?.[1]),+ contextLength: positiveInt(message?.[2]) ?? positiveInt(s.match(N_CTX_RE)?.[1])+ }+}++const tokenLabel = (n) => (n ? `${Math.round(n / 1024)}K` : 'unknown')++/**+ * One actionable line explaining an overflow. The raw Ollama body is a JSON+ * blob whose "try increasing it" says nothing about *where* — this names the+ * knob (the provider's `num_ctx`) and the fact that the daemon reloads to apply+ * it, so the run's output is enough to fix the run.+ *+ * @param {{ promptTokens: number|null, contextLength: number|null }} overflow+ * @param {{ model?: string|null, providerName?: string|null }} [options]+ * @returns {string}+ */+export function describeOllamaContextOverflow(overflow, { model = null, providerName = null } = {}) {+ const who = providerName ? `${providerName}'s` : "the provider's"+ const what = model ? ` for ${model}` : ''+ return `🪟 Ollama ran out of context${what}: the request needed ${tokenLabel(overflow?.promptTokens)} tokens ` ++ `but the model was loaded with a ${tokenLabel(overflow?.contextLength)} window. ` ++ `Raise ${who} "Local num_ctx" in AI Providers (or set ${OLLAMA_CONTEXT_ENV_VAR}) and PortOS will reload ` ++ `the Ollama daemon at that window — check the model still fits in VRAM at the larger size.`+}++/**+ * One actionable line warning that the daemon's current window is below+ * {@link OLLAMA_AGENT_MIN_CONTEXT}, emitted before a spawn rather than an hour+ * into a doomed run.+ *+ * @param {number} runtimeContext - the window the daemon actually loaded+ * @param {{ providerName?: string|null }} [options]+ * @returns {string}+ */+export function describeOllamaContextTooSmall(runtimeContext, { providerName = null } = {}) {+ const who = providerName ? `${providerName}` : 'This provider'+ return `⚠️ ${who} is running on an Ollama window of ${tokenLabel(runtimeContext)} — below the ` ++ `${tokenLabel(OLLAMA_AGENT_MIN_CONTEXT)} an agent harness usually needs. Set "Local num_ctx" in AI Providers ` ++ `to reload Ollama at a larger window (VRAM permitting), or the run will fail partway through.`+}diff --git a/server/lib/ollamaContext.test.js b/server/lib/ollamaContext.test.jsnew file mode 100644index 0000000000..c1461065ba--- /dev/null+++ b/server/lib/ollamaContext.test.js@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest'+import {+ OLLAMA_AGENT_MIN_CONTEXT,+ OLLAMA_CONTEXT_ENV_VAR,+ describeOllamaContextOverflow,+ describeOllamaContextTooSmall,+ parseOllamaContextOverflow,+ resolveOllamaContextLength,+ withOllamaContextEnv+} from './ollamaContext.js'++describe('resolveOllamaContextLength', () => {+ it('prefers the provider numCtx over the ambient env', () => {+ expect(resolveOllamaContextLength({ numCtx: 131072 }, { [OLLAMA_CONTEXT_ENV_VAR]: '32768' })).toBe(131072)+ })++ it('falls back to OLLAMA_CONTEXT_LENGTH', () => {+ expect(resolveOllamaContextLength({}, { [OLLAMA_CONTEXT_ENV_VAR]: '65536' })).toBe(65536)+ })++ it('returns null when neither is set, so Ollama keeps its VRAM auto-pick', () => {+ expect(resolveOllamaContextLength({}, {})).toBeNull()+ expect(resolveOllamaContextLength(null, {})).toBeNull()+ })++ it('ignores zero, negative, and non-numeric values', () => {+ expect(resolveOllamaContextLength({ numCtx: 0 }, {})).toBeNull()+ expect(resolveOllamaContextLength({ numCtx: -1 }, {})).toBeNull()+ expect(resolveOllamaContextLength({ numCtx: 'wide' }, {})).toBeNull()+ expect(resolveOllamaContextLength({}, { [OLLAMA_CONTEXT_ENV_VAR]: 'wide' })).toBeNull()+ })++ it('falls through a non-numeric provider value to the env', () => {+ expect(resolveOllamaContextLength({ numCtx: null }, { [OLLAMA_CONTEXT_ENV_VAR]: '65536' })).toBe(65536)+ })+})++describe('withOllamaContextEnv', () => {+ it('injects the window as a string', () => {+ expect(withOllamaContextEnv({ PATH: '/bin' }, 131072)).toEqual({+ PATH: '/bin',+ [OLLAMA_CONTEXT_ENV_VAR]: '131072'+ })+ })++ it('leaves the env untouched when no window is configured', () => {+ const env = { PATH: '/bin' }+ expect(withOllamaContextEnv(env, null)).toBe(env)+ expect(withOllamaContextEnv(env, 0)).toBe(env)+ })++ it('does not mutate the source env', () => {+ const env = { PATH: '/bin' }+ withOllamaContextEnv(env, 65536)+ expect(env[OLLAMA_CONTEXT_ENV_VAR]).toBeUndefined()+ })+})++describe('parseOllamaContextOverflow', () => {+ const body = '{"error":{"code":400,"message":"request (32768 tokens) exceeds the available context size ' ++ '(32768 tokens), try increasing it","type":"exceed_context_size_error","n_prompt_tokens":32768,"n_ctx":32768}}'++ it('reads both token counts out of the full error body', () => {+ expect(parseOllamaContextOverflow(body)).toEqual({ promptTokens: 32768, contextLength: 32768 })+ })++ it('reads them from the human message alone', () => {+ expect(parseOllamaContextOverflow('request (40000 tokens) exceeds the available context size (32768 tokens)'))+ .toEqual({ promptTokens: 40000, contextLength: 32768 })+ })++ it('recognizes the error type even when the message was reflowed away', () => {+ expect(parseOllamaContextOverflow('"type":"exceed_context_size_error","n_prompt_tokens":9000,"n_ctx":8192}}'))+ .toEqual({ promptTokens: 9000, contextLength: 8192 })+ })++ it('reports nulls rather than failing when only the type survives', () => {+ expect(parseOllamaContextOverflow('exceed_context_size_error')).toEqual({ promptTokens: null, contextLength: null })+ })++ it('returns null for unrelated output', () => {+ expect(parseOllamaContextOverflow('API Error: 400 bad request')).toBeNull()+ expect(parseOllamaContextOverflow('')).toBeNull()+ expect(parseOllamaContextOverflow(null)).toBeNull()+ })+})++describe('overflow descriptions', () => {+ it('names the knob that actually fixes the overflow', () => {+ const text = describeOllamaContextOverflow({ promptTokens: 32768, contextLength: 32768 }, { model: 'qwen3.8:27b' })+ expect(text).toContain('qwen3.8:27b')+ expect(text).toContain('32K')+ expect(text).toContain('num_ctx')+ })++ it('degrades to "unknown" instead of NaN when the counts did not parse', () => {+ const text = describeOllamaContextOverflow({ promptTokens: null, contextLength: null })+ expect(text).toContain('unknown')+ expect(text).not.toContain('NaN')+ })++ it('warns with the agent floor when the daemon window is too small', () => {+ const text = describeOllamaContextTooSmall(32768, { providerName: 'Claude Ollama TUI' })+ expect(text).toContain('Claude Ollama TUI')+ expect(text).toContain('32K')+ expect(text).toContain(`${OLLAMA_AGENT_MIN_CONTEXT / 1024}K`)+ })+})diff --git a/server/lib/providerCooldown.js b/server/lib/providerCooldown.jsindex 2b1be61ad1..041e8ebb09 100644--- a/server/lib/providerCooldown.js+++ b/server/lib/providerCooldown.js@@ -46,7 +46,8 @@ export const DEFAULT_COOLDOWN_MS = 60 * 1000;// its synthetic response-schema failure 'parse-error' so it lands in this tier// when it re-enters the cascade.const SCHEMA_TYPE_CATEGORIES = new Set([- 'parse-error', 'bad-request', 'context-length', 'output-length', 'build-error', 'lint-error',+ 'parse-error', 'bad-request', 'context-length', 'ollama-context-window', 'output-length',+ 'build-error', 'lint-error',]);export const isSchemaTypeCategory = (category) => SCHEMA_TYPE_CATEGORIES.has(category);diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex c14ae3d9a1..98ec99ec8e 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -11,6 +11,7 @@ import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { redactOutput } from '../lib/commandSecurity.js';import { stripAnsi } from '../lib/ansiStrip.js';+import { describeOllamaContextOverflow, parseOllamaContextOverflow } from '../lib/ollamaContext.js';import { retryHoldMetadata } from '../lib/taskRetryHold.js';import {INVESTIGATION_CIRCUIT_MAX_CREATIONS,@@ -226,6 +227,32 @@ export const ERROR_PATTERNS = [};}},+ {+ // Ollama's own overflow rejection. Must sit AHEAD of `bad-request` (it+ // arrives as `API Error: 400`) and of the generic `context-length` rule+ // below, which misses it entirely — Ollama says "context size", not+ // "context length". Worth its own category because the fix is the opposite+ // of both: the task isn't too big and the request isn't malformed — a+ // 256K-capable model was LOADED at 32K, because Ollama picks the runtime+ // window from VRAM and an agent harness talking to it directly can't ask+ // for more. Splitting the task (the generic rule's advice) just loses the+ // work again next run; raising the provider's num_ctx is what fixes it.+ // See server/lib/ollamaContext.js.+ pattern: /exceed_context_size_error|exceeds the available context size/i,+ category: 'ollama-context-window',+ actionable: true,+ origin: 'provider',+ escalation: 'Approve raising the Ollama-backed provider\'s "Local num_ctx" (AI Providers → the provider → Context Window) so PortOS reloads the daemon at a larger window, then retry.',+ extract: (match, output, task, model) => {+ const overflow = parseOllamaContextOverflow(output) || {};+ return {+ message: `Ollama context window exhausted (${overflow.contextLength ?? 'unknown'} tokens)`,+ suggestedFix: describeOllamaContextOverflow(overflow, { model }),+ affectedContextLength: overflow.contextLength ?? null,+ requestedTokens: overflow.promptTokens ?? null+ };+ }+ },{pattern: /API Error: 400|invalid_request_error|bad.?request/i,category: 'bad-request',diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 59b31488e9..73a4d0d4f3 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -172,6 +172,20 @@ describe('analyzeAgentFailure — ERROR_PATTERNS classification', () => {expect(analysis.compaction?.needed).toBe(true);});+ it('classifies an Ollama context overflow separately from a generic context-length error', () => {+ const body = 'API Error: 400 {"error":{"code":400,"message":"request (32768 tokens) exceeds the available ' ++ 'context size (32768 tokens), try increasing it","type":"exceed_context_size_error",' ++ '"n_prompt_tokens":32768,"n_ctx":32768}}';+ const analysis = analyzeAgentFailure(withLead(body), { id: 't' }, 'qwen3.8:27b');+ // NOT `context-length`: the task isn't too big, the daemon loaded the model+ // at 32K. Splitting the task (that rule's advice) would lose the work again.+ expect(analysis.category).toBe('ollama-context-window');+ expect(analysis.actionable).toBe(true);+ expect(analysis.affectedContextLength).toBe(32768);+ expect(analysis.requestedTokens).toBe(32768);+ expect(analysis.suggestedFix).toContain('num_ctx');+ });+it('falls back to an unknown, non-actionable category for unrecognized output', () => {const analysis = analyzeAgentFailure(withLead('The agent halted after an unrecognized condition with no diagnostic.'), { id: 't' }, 'x');expect(analysis.category).toBe('unknown');diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 8ca7fbeeb9..4ecb3d8091 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -77,6 +77,8 @@ import {import { injectTuiModelAndEffort } from '../lib/providerVendors.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';+import { ensureOllamaAgentContext } from './ollamaAgentContext.js';+import { isOllamaBackedProvider } from './providers.js';import { execFile } from '../lib/childProcess.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot@@ -1418,6 +1420,17 @@ export async function spawnTuiAgent({? {}: await git.resolveForgeTokenEnv(cwd);+ // Ollama-backed harnesses talk to the daemon directly, so their context+ // window is whatever Ollama loaded the model at — no per-request `num_ctx`+ // reaches them. Hold the daemon at the provider's configured window (or warn+ // when it's below what an agent harness needs) BEFORE the TUI starts: the+ // failure mode otherwise is an hour of work lost to a 400 at 100% context.+ // Gated on the predicate here (not just inside the helper) so a cloud-provider+ // spawn — the overwhelmingly common case — takes no async hop at all.+ const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ if (ollamaContext?.warning) appendLine(ollamaContext.warning);+ if (ollamaContext?.applied) appendLine(`🪟 Reloaded Ollama at a ${ollamaContext.contextLength}-token context window`);+// A spawn failure here (a runner 400 for a command missing from its allowlist,// an unreachable runner, a PTY that won't open) used to propagate raw out of// spawnTuiAgent. The caller in subAgentSpawner only logs it, so the agentdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 655c52e0d0..33d92cf910 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -61,6 +61,13 @@ vi.mock('./agentCompletion.js', () => ({processAgentCompletion: vi.fn().mockResolvedValue(undefined)}));+// The Ollama-backed spawn path prepares the daemon's context window first, which+// otherwise reaches a real localhost:11434 in this suite. Stub it to a no-op —+// its own behavior is covered by services/ollamaAgentContext.test.js.+vi.mock('./ollamaAgentContext.js', () => ({+ ensureOllamaAgentContext: vi.fn().mockResolvedValue({ skipped: false, contextLength: null, applied: false, warning: null })+}));+vi.mock('./agentFinalization.js', () => ({persistSimplifySummaries: vi.fn().mockResolvedValue(undefined),finalizeAgent: vi.fn().mockResolvedValue(undefined),@@ -221,6 +228,7 @@ import { releaseRetryHold } from './agentWorktreeCleanup.js';import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentFinalization.js';+import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';@@ -728,6 +736,23 @@ describe('spawnTuiAgent runtime', () => {}));});+ it('prepares the Ollama context window only for Ollama-backed providers', async () => {+ const spawnPromise = runSpawn({+ provider: { id: 'claude-ollama-tui', name: 'Lean Claude TUI', type: 'tui', command: 'claude', ollamaBacked: true, envVars: {} },+ });+ await flushMicrotasks();+ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;+ expect(ensureOllamaAgentContext).toHaveBeenCalledTimes(1);++ vi.mocked(ensureOllamaAgentContext).mockClear();+ const cloudSpawn = runSpawn();+ await flushMicrotasks();+ await capturedOnExit({ exitCode: 0, killed: false });+ await cloudSpawn;+ expect(ensureOllamaAgentContext).not.toHaveBeenCalled();+ });+it('does not double-fire a PR owned by a slashdo-capable Claude TUI', async () => {const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);// finalize asked the forge and got an answer for a real branch — the onlydiff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 23e4e16416..142b894800 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -129,6 +129,7 @@ const CATEGORY_TO_TIER = {'parse-error': FIX_TIERS.SCHEMA_TYPE,'bad-request': FIX_TIERS.SCHEMA_TYPE,'context-length': FIX_TIERS.SCHEMA_TYPE,+ 'ollama-context-window': FIX_TIERS.SCHEMA_TYPE,'output-length': FIX_TIERS.SCHEMA_TYPE,'build-error': FIX_TIERS.SCHEMA_TYPE,'lint-error': FIX_TIERS.SCHEMA_TYPE,diff --git a/server/services/layeredIntelligenceExecutionFailures.js b/server/services/layeredIntelligenceExecutionFailures.jsindex 0ccd0d9516..68b2bdda11 100644--- a/server/services/layeredIntelligenceExecutionFailures.js+++ b/server/services/layeredIntelligenceExecutionFailures.js@@ -149,6 +149,7 @@ const RAW_CATEGORY_TAXONOMY = new Map(Object.entries({// context — the agent lacked repo knowledge, or overran the context/turn budget.'context-length': 'context',+ 'ollama-context-window': 'context','output-length': 'context','turn-limit': 'context','file-not-found': 'context',diff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.jsnew file mode 100644index 0000000000..18e6c51310--- /dev/null+++ b/server/services/ollamaAgentContext.js@@ -0,0 +1,64 @@+/**+ * Pre-spawn context-window preparation for Ollama-backed *agent harnesses*+ * (`claude-ollama`, `claude-ollama-tui`, `opencode-ollama`, …).+ *+ * These providers launch a real CLI/TUI that speaks to Ollama directly, so —+ * unlike `api`-type providers, where the toolkit runner attaches a per-request+ * `num_ctx` — PortOS has no way to influence the window from inside the+ * request. The only lever is the daemon's `OLLAMA_CONTEXT_LENGTH`, which is why+ * a provider's `numCtx` is enforced here by (re)loading the daemon at that+ * window before the harness starts.+ *+ * When the provider carries no `numCtx`, nothing is restarted — Ollama's+ * VRAM-based auto-pick stands — but a too-small window is warned about up+ * front, because the alternative is a run that dies an hour in with+ * `exceed_context_size_error`.+ */++import { isOllamaBackedProvider } from './providers.js'+import {+ OLLAMA_AGENT_MIN_CONTEXT,+ describeOllamaContextTooSmall,+ resolveOllamaContextLength+} from '../lib/ollamaContext.js'+import { ensureContextWindow, getRuntimeContextLength } from './ollamaManager.js'++/**+ * Prepare the Ollama daemon for an agent harness run.+ *+ * Never throws and never blocks a spawn: a daemon that refuses to restart is+ * reported through `warning` (and the run proceeds on whatever window it has)+ * rather than failing the agent before it starts.+ *+ * Non-Ollama providers return `{ skipped: true }`. Call sites gate on+ * `isOllamaBackedProvider` too, so a cloud run takes no async hop at all; this+ * guard is the module's own contract, not the hot path.+ *+ * @param {{id?:string, name?:string, numCtx?:number|null, envVars?:object, endpoint?:string, ollamaBacked?:boolean}|null} provider+ * @param {{ env?: Record<string, string|undefined> }} [options]+ * @returns {Promise<{ skipped: boolean, contextLength?: number|null, applied?: boolean, warning?: string|null }>}+ */+export async function ensureOllamaAgentContext(provider, { env = process.env } = {}) {+ if (!provider || !isOllamaBackedProvider(provider)) return { skipped: true }++ const contextLength = resolveOllamaContextLength(provider, env)+ const providerName = provider.name || provider.id || null++ if (!contextLength) {+ const runtime = await getRuntimeContextLength().catch(() => null)+ const warning = runtime != null && runtime < OLLAMA_AGENT_MIN_CONTEXT+ ? describeOllamaContextTooSmall(runtime, { providerName })+ : null+ if (warning) console.warn(warning)+ return { skipped: false, contextLength: null, applied: false, warning }+ }++ const result = await ensureContextWindow(contextLength).catch((err) => ({+ applied: false, reason: 'error', error: err.message+ }))+ const warning = result.error+ ? `⚠️ Could not reload Ollama at a ${contextLength}-token window (${result.error}) — ${providerName || 'the run'} continues on the current window.`+ : null+ if (warning) console.warn(warning)+ return { skipped: false, contextLength, applied: !!result.applied, warning }+}diff --git a/server/services/ollamaAgentContext.test.js b/server/services/ollamaAgentContext.test.jsnew file mode 100644index 0000000000..8ef1630b7f--- /dev/null+++ b/server/services/ollamaAgentContext.test.js@@ -0,0 +1,74 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('./ollamaManager.js', () => ({+ ensureContextWindow: vi.fn(),+ getRuntimeContextLength: vi.fn()+}))++import { ensureContextWindow, getRuntimeContextLength } from './ollamaManager.js'+import { ensureOllamaAgentContext } from './ollamaAgentContext.js'++const claudeOllamaTui = {+ id: 'claude-ollama-tui',+ name: 'Claude Ollama TUI (local model)',+ type: 'tui',+ ollamaBacked: true,+ envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11434' }+}++describe('ensureOllamaAgentContext', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ })++ it('skips providers that are not Ollama-backed', async () => {+ const result = await ensureOllamaAgentContext({ id: 'claude-code-tui', type: 'tui' }, { env: {} })+ expect(result).toEqual({ skipped: true })+ expect(ensureContextWindow).not.toHaveBeenCalled()+ expect(getRuntimeContextLength).not.toHaveBeenCalled()+ })++ it('skips a null provider', async () => {+ expect(await ensureOllamaAgentContext(null, { env: {} })).toEqual({ skipped: true })+ })++ it('holds the daemon at the provider window', async () => {+ ensureContextWindow.mockResolvedValue({ applied: true, reason: 'restarted' })+ const result = await ensureOllamaAgentContext({ ...claudeOllamaTui, numCtx: 131072 }, { env: {} })+ expect(ensureContextWindow).toHaveBeenCalledWith(131072)+ expect(result).toMatchObject({ skipped: false, contextLength: 131072, applied: true, warning: null })+ })++ it('warns but does not block the spawn when the reload fails', async () => {+ ensureContextWindow.mockResolvedValue({ applied: false, reason: 'stop-failed', error: 'still reachable' })+ const result = await ensureOllamaAgentContext({ ...claudeOllamaTui, numCtx: 131072 }, { env: {} })+ expect(result.applied).toBe(false)+ expect(result.warning).toContain('131072')+ expect(result.warning).toContain('still reachable')+ })++ it('warns when no window is configured and the daemon is running below the agent floor', async () => {+ getRuntimeContextLength.mockResolvedValue(32768)+ const result = await ensureOllamaAgentContext(claudeOllamaTui, { env: {} })+ expect(ensureContextWindow).not.toHaveBeenCalled()+ expect(result.warning).toContain('32K')+ expect(result.warning).toContain('num_ctx')+ })++ it('stays quiet when the running window is already generous', async () => {+ getRuntimeContextLength.mockResolvedValue(262144)+ expect((await ensureOllamaAgentContext(claudeOllamaTui, { env: {} })).warning).toBeNull()+ })++ it('stays quiet when no model is resident — an unknown window is not evidence of a small one', async () => {+ getRuntimeContextLength.mockResolvedValue(null)+ expect((await ensureOllamaAgentContext(claudeOllamaTui, { env: {} })).warning).toBeNull()+ })++ it('falls back to OLLAMA_CONTEXT_LENGTH when the provider carries no numCtx', async () => {+ ensureContextWindow.mockResolvedValue({ applied: false, reason: 'already-large-enough' })+ await ensureOllamaAgentContext(claudeOllamaTui, { env: { OLLAMA_CONTEXT_LENGTH: '65536' } })+ expect(ensureContextWindow).toHaveBeenCalledWith(65536)+ })+})diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex fd3bd41878..718135f791 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -30,6 +30,7 @@ import {import { buildHfAuthHeaders } from '../lib/huggingfaceLora.js'import { isEmbeddingModel } from '../lib/localModelHeuristics.js'import { commandExists } from '../lib/commandExists.js'+import { OLLAMA_AGENT_MIN_CONTEXT, OLLAMA_CONTEXT_ENV_VAR, withOllamaContextEnv } from '../lib/ollamaContext.js'const execFileAsync = promisify(execFile)const AVAILABILITY_CACHE_TTL_MS = 30_000@@ -84,6 +85,16 @@ let installedModels = nulllet lastCheckAt = nulllet managedProcess = nulllet managedProcessPid = null+// The OLLAMA_CONTEXT_LENGTH PortOS handed the daemon that is up right now —+// whether by spawning it or by restarting its launch-at-login service. Cleared+// when the daemon goes away, so it always describes the live process.+//+// It is what stops `ensureContextWindow` from restarting in a loop: Ollama is+// free to load a model at less than the requested window (it fits the KV cache+// to VRAM), and re-reading a smaller `/api/ps` value as "not applied yet" would+// bounce the daemon before every single agent spawn. Once a window has been+// handed over, that request is done.+let appliedContextLength = nullconst status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }@@ -94,6 +105,7 @@ async function getServiceController() {manager: 'homebrew',start: ['brew', ['services', 'start', 'ollama']],stop: ['brew', ['services', 'stop', 'ollama']],+ restart: ['brew', ['services', 'restart', 'ollama']],list: ['brew', ['services', 'list']]}}@@ -186,6 +198,9 @@ async function checkOllamaAvailable(forceRefresh = false) {return true} catch (err) {isAvailable = false+ // The daemon we handed a window to is gone; whatever comes up next has to+ // be re-checked rather than credited with that window.+ appliedContextLength = nullstatus.lastError = err.messagestatus.consecutiveErrors++lastCheckAt = now@@ -232,9 +247,15 @@ async function terminateManagedProcess() {/*** Start the Ollama HTTP server via the local CLI.+ *+ * `contextLength` (when set) becomes the daemon-wide `OLLAMA_CONTEXT_LENGTH`.+ * This is the only lever that reaches Ollama-backed *agent harnesses* — Claude+ * Code and OpenCode talk to Ollama directly, so PortOS can't attach a+ * per-request `num_ctx` the way the toolkit runner does for `api` providers.+ * @param {{ contextLength?: number|null }} [options]* @returns {Promise<{ success: boolean, running?: boolean, alreadyRunning?: boolean, pid?: number, error?: string }>}*/-async function startServer() {+async function startServer({ contextLength = null } = {}) {if (await checkOllamaAvailable(true)) {return { success: true, running: true, alreadyRunning: true }}@@ -244,7 +265,7 @@ async function startServer() {const child = spawn('ollama', ['serve'], {detached: true,stdio: ['ignore', 'ignore', 'pipe'],- env: process.env+ env: withOllamaContextEnv(process.env, contextLength)})rememberManagedProcess(child)child.stderr?.on('data', (chunk) => {@@ -256,7 +277,9 @@ async function startServer() {const running = await waitForAvailability(true, START_TIMEOUT_MS)if (running) {- console.log(`▶️ Started Ollama server (pid ${child.pid})`)+ appliedContextLength = contextLength || null+ const window = contextLength ? ` (context ${contextLength})` : ''+ console.log(`▶️ Started Ollama server (pid ${child.pid})${window}`)return { success: true, running: true, pid: child.pid }}@@ -402,6 +425,123 @@ async function ensureRunning({ preferPersistent = false } = {}) {return startServer()}+/**+ * The context window the daemon actually loaded models at, read from `/api/ps`.+ * Ollama reports it per resident model; we take the largest, since that is the+ * window a request routed to an already-resident model will get.+ *+ * `null` means unknowable right now — no model is resident, so Ollama has not+ * yet committed to a window. Callers must treat that as "no evidence", never as+ * "too small": the daemon's own default may well be generous.+ * @returns {Promise<number|null>}+ */+async function getRuntimeContextLength() {+ if (!(await checkOllamaAvailable())) return null+ const data = await ollamaRequest('/api/ps').catch(() => null)+ const windows = (Array.isArray(data?.models) ? data.models : [])+ .map((m) => Number(m?.context_length))+ .filter((n) => Number.isFinite(n) && n > 0)+ return windows.length ? Math.max(...windows) : null+}++/**+ * Hold the Ollama daemon at (at least) `contextLength` tokens, reloading it with+ * that window when it is running at a smaller one.+ *+ * Reloading a daemon is disruptive, so it happens only on positive evidence:+ * `/api/ps` reports a resident model below the target and this daemon has not+ * already been handed that window. An unmanaged daemon with nothing resident is+ * left alone — see {@link getRuntimeContextLength}, an unknown window is not a+ * small one — and the pre-spawn warning covers that case instead.+ *+ * @param {number|null} contextLength+ * @returns {Promise<{ applied: boolean, reason: string, contextLength: number|null, runtimeContextLength?: number|null, error?: string }>}+ */+async function ensureContextWindow(contextLength) {+ const target = Number(contextLength) > 0 ? Math.floor(Number(contextLength)) : null+ if (!target) return { applied: false, reason: 'not-configured', contextLength: null }+ if (!(await checkOllamaAvailable(true))) {+ const started = await startServer({ contextLength: target })+ return started.success+ ? { applied: true, reason: 'started', contextLength: target }+ : { applied: false, reason: 'start-failed', contextLength: target, error: started.error }+ }++ if (Number(appliedContextLength) >= target) {+ return { applied: false, reason: 'already-applied', contextLength: target, runtimeContextLength: appliedContextLength }+ }++ const runtime = await getRuntimeContextLength()+ if (runtime == null) return { applied: false, reason: 'unknown-window', contextLength: target, runtimeContextLength: null }+ if (runtime >= target) {+ return { applied: false, reason: 'already-large-enough', contextLength: target, runtimeContextLength: runtime }+ }++ console.log(`🪟 Reloading Ollama at a ${target}-token context window (was ${runtime})`)++ // A daemon the user registered to launch at login must keep that registration:+ // `stopServer` would route through `brew services stop` / `systemctl disable`,+ // which un-registers it. Restart it in place instead (see restartServiceWithContext).+ const service = await getServiceStatus().catch(() => null)+ if (service?.runAtStartup) {+ const viaService = await restartServiceWithContext(service, target)+ return { ...viaService, contextLength: target, runtimeContextLength: runtime }+ }++ const stopped = await stopServer()+ if (!stopped.success) {+ return { applied: false, reason: 'stop-failed', contextLength: target, runtimeContextLength: runtime, error: stopped.error }+ }+ const started = await startServer({ contextLength: target })+ return started.success+ ? { applied: true, reason: 'restarted', contextLength: target, runtimeContextLength: runtime }+ : { applied: false, reason: 'start-failed', contextLength: target, runtimeContextLength: runtime, error: started.error }+}++/**+ * Restart a launch-at-login-registered Ollama at `contextLength`, WITHOUT+ * un-registering it.+ *+ * macOS: `launchctl setenv` writes into the user's launchd domain, which every+ * job launched afterwards inherits — so setting it and then+ * `brew services restart ollama` carries the window into a plist PortOS cannot+ * edit (Homebrew regenerates it from the formula on every start). The variable+ * is scoped to Ollama's behavior, so exporting it session-wide is harmless.+ *+ * Linux: the equivalent is a `systemctl edit ollama` drop-in, which needs root.+ * PortOS reports what to do rather than tearing the unit down to work around it.+ */+async function restartServiceWithContext(service, contextLength) {+ if (service.manager !== 'homebrew') {+ return {+ applied: false,+ reason: 'service-managed',+ error: `Ollama runs as a ${service.manager} service, which PortOS can't hand a context window. ` ++ `Add one with: sudo systemctl edit ollama → [Service] Environment="${OLLAMA_CONTEXT_ENV_VAR}=${contextLength}", then restart it.`+ }+ }++ const controller = await getServiceController()+ const setenv = await execFileAsync('launchctl', ['setenv', OLLAMA_CONTEXT_ENV_VAR, String(contextLength)], { timeout: SERVICE_COMMAND_TIMEOUT_MS })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.message }))+ if (!setenv.success) return { applied: false, reason: 'setenv-failed', error: setenv.error }++ resetAvailabilityCache()+ const [cmd, args] = controller.restart+ const restarted = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.stderr?.trim() || err.stdout?.trim() || err.message }))+ if (!restarted.success) return { applied: false, reason: 'restart-failed', error: restarted.error }++ if (!(await waitForAvailability(true, START_TIMEOUT_MS))) {+ return { applied: false, reason: 'restart-unreachable', error: 'Ollama restarted, but the API did not become reachable.' }+ }+ appliedContextLength = contextLength+ console.log(`▶️ Restarted the Ollama ${service.manager} service at a ${contextLength}-token context window`)+ return { applied: true, reason: 'service-restarted' }+}+function isOllamaProvider(provider) {const endpoint = String(provider?.endpoint || '')return provider?.id === 'ollama' ||@@ -1105,6 +1245,15 @@ async function getStatus(forceRefresh = false) {modelCount: models.length,models,service,+ // The window resident models were actually loaded at (null when nothing is+ // resident — Ollama has not committed to one yet), plus the window PortOS+ // handed this daemon. Surfaced so the Local LLM page can show why an agent+ // harness overflowed at 32K on a 256K-capable model.+ contextLength: {+ runtime: available ? await getRuntimeContextLength().catch(() => null) : null,+ applied: available ? appliedContextLength : null,+ agentMinimum: OLLAMA_AGENT_MIN_CONTEXT+ },lastError: status.lastError,consecutiveErrors: status.consecutiveErrors}@@ -1123,6 +1272,8 @@ export {importModelFromGguf,startServer,stopServer,+ ensureContextWindow,+ getRuntimeContextLength,startPersistentService,stopPersistentService,ensureRunning,diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex 3a3c10cf76..92d6d36eb0 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -628,3 +628,136 @@ describe('ollamaManager.startPersistentService bootstrap recovery (homebrew)', (expect(result.error).toContain('still wedged') // retry's error, not the first})})++describe('ollamaManager context window', () => {+ afterEach(() => { vi.unstubAllGlobals() })++ // Answers /api/version (reachable) and /api/ps with the given resident models.+ function stubPs(models) {+ const bodyFor = (url) => (String(url).endsWith('/api/ps') ? { models } : { version: '0.32.13' })+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const body = bodyFor(url)+ return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }+ }))+ }++ it('reports the largest window across resident models', async () => {+ stubPs([{ name: 'a', context_length: 32768 }, { name: 'b', context_length: 131072 }])+ const { getRuntimeContextLength } = await loadManager()+ expect(await getRuntimeContextLength()).toBe(131072)+ })++ it('reports null when nothing is resident — Ollama has not committed to a window yet', async () => {+ stubPs([])+ const { getRuntimeContextLength } = await loadManager()+ expect(await getRuntimeContextLength()).toBeNull()+ })++ it('ignores models whose window Ollama did not report', async () => {+ stubPs([{ name: 'a' }, { name: 'b', context_length: 0 }])+ const { getRuntimeContextLength } = await loadManager()+ expect(await getRuntimeContextLength()).toBeNull()+ })++ it('does nothing when no window is configured', async () => {+ stubPs([{ name: 'a', context_length: 4096 }])+ const { ensureContextWindow } = await loadManager()+ expect(await ensureContextWindow(null)).toEqual({ applied: false, reason: 'not-configured', contextLength: null })+ })++ it('leaves a daemon alone when it already loaded a large enough window', async () => {+ stubPs([{ name: 'a', context_length: 131072 }])+ const { ensureContextWindow } = await loadManager()+ expect(await ensureContextWindow(65536)).toMatchObject({ applied: false, reason: 'already-large-enough' })+ })++ it('leaves an unmanaged daemon with nothing resident alone — an unknown window is not evidence', async () => {+ stubPs([])+ const { ensureContextWindow } = await loadManager()+ expect(await ensureContextWindow(65536)).toMatchObject({ applied: false, reason: 'unknown-window' })+ })+})++describe('ollamaManager context window — launch-at-login daemons', () => {+ let restorePlatform = null+ afterEach(() => { vi.unstubAllGlobals(); restorePlatform?.(); restorePlatform = null })++ function stubPs(models) {+ const bodyFor = (url) => (String(url).endsWith('/api/ps') ? { models } : { version: '0.32.13' })+ vi.stubGlobal('fetch', vi.fn(async (url) => {+ const body = bodyFor(url)+ return { ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body) }+ }))+ }++ // Reloading a registered service must NEVER route through `brew services stop`+ // / `systemctl disable` — that silently drops the user's launch-at-login+ // registration as a side effect of raising a context window.+ it('restarts a homebrew service in place, carrying the window via launchctl setenv', async () => {+ restorePlatform = pinPlatform('darwin')+ stubPs([{ name: 'a', context_length: 32768 }])+ const calls = []+ execMock.impl = (cmd, args, opts, cb) => {+ const a = (args || []).join(' ')+ calls.push(`${cmd} ${a}`)+ if (cmd === 'brew' && a === '--version') return cb(null, { stdout: 'Homebrew 4.0.0', stderr: '' })+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started antic plist\n', stderr: '' })+ if (cmd === 'launchctl' && a.startsWith('setenv OLLAMA_CONTEXT_LENGTH')) return cb(null, { stdout: '', stderr: '' })+ if (cmd === 'brew' && a === 'services restart ollama') return cb(null, { stdout: '', stderr: '' })+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { ensureContextWindow } = await loadManager()+ const result = await ensureContextWindow(131072)++ expect(result).toMatchObject({ applied: true, reason: 'service-restarted', contextLength: 131072 })+ expect(calls).toContain('launchctl setenv OLLAMA_CONTEXT_LENGTH 131072')+ expect(calls).toContain('brew services restart ollama')+ expect(calls.some((c) => c.includes('services stop'))).toBe(false)+ })++ it('does not reload twice for the same window once it has been handed over', async () => {+ restorePlatform = pinPlatform('darwin')+ stubPs([{ name: 'a', context_length: 32768 }])+ let restarts = 0+ execMock.impl = (cmd, args, opts, cb) => {+ const a = (args || []).join(' ')+ if (cmd === 'brew' && a === '--version') return cb(null, { stdout: 'Homebrew 4.0.0', stderr: '' })+ if (cmd === 'brew' && a === 'services list') return cb(null, { stdout: 'ollama started antic plist\n', stderr: '' })+ if (cmd === 'launchctl') return cb(null, { stdout: '', stderr: '' })+ if (cmd === 'brew' && a === 'services restart ollama') { restarts++; return cb(null, { stdout: '', stderr: '' }) }+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { ensureContextWindow } = await loadManager()+ await ensureContextWindow(131072)+ // Ollama may still load a model at less than the requested window (it fits+ // the KV cache to VRAM). That must not read as "not applied" and bounce the+ // daemon before every agent spawn.+ const second = await ensureContextWindow(131072)++ expect(restarts).toBe(1)+ expect(second).toMatchObject({ applied: false, reason: 'already-applied' })+ })++ it('reports the systemd drop-in instead of tearing the unit down', async () => {+ restorePlatform = pinPlatform('linux')+ stubPs([{ name: 'a', context_length: 32768 }])+ const calls = []+ execMock.impl = (cmd, args, opts, cb) => {+ const a = (args || []).join(' ')+ calls.push(`${cmd} ${a}`)+ if (cmd === 'systemctl' && a === '--version') return cb(null, { stdout: 'systemd 250', stderr: '' })+ if (cmd === 'systemctl' && a === 'is-active ollama') return cb(null, { stdout: 'active\n', stderr: '' })+ if (cmd === 'systemctl' && a === 'is-enabled ollama') return cb(null, { stdout: 'enabled\n', stderr: '' })+ return cb(new Error(`unexpected exec: ${cmd} ${a}`))+ }++ const { ensureContextWindow } = await loadManager()+ const result = await ensureContextWindow(131072)++ expect(result).toMatchObject({ applied: false, reason: 'service-managed' })+ expect(result.error).toContain('systemctl edit ollama')+ expect(calls.some((c) => c.includes('disable'))).toBe(false)+ })+})diff --git a/server/services/runner.js b/server/services/runner.jsindex 70e8b79d69..1b87280fc7 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -13,6 +13,8 @@ import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { createImmediateFallbackSignalDetector, ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';import { isHostShuttingDown } from '../lib/hostShutdown.js';+import { ensureOllamaAgentContext } from './ollamaAgentContext.js';+import { isOllamaBackedProvider } from './providers.js';import {setAIToolkitInstance,getAIToolkitInstance,@@ -285,6 +287,15 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onconst { args, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, builtArgs, prompt);console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'argv'})`);+ // Ollama-backed CLIs (claude-ollama, opencode-ollama) reach the daemon+ // themselves, so the toolkit's per-request `num_ctx` never applies to them —+ // hold the daemon at the provider's configured window (or warn) first. See+ // services/ollamaAgentContext.js.+ // Gated on the predicate here (not just inside the helper) so a cloud-provider+ // run — the overwhelmingly common case — takes no async hop at all.+ const ollamaContext = isOllamaBackedProvider(provider) ? await ensureOllamaAgentContext(provider) : null;+ if (ollamaContext?.warning) onData?.(`${ollamaContext.warning}\n`);+// Shared composition (provider.envVars + OpenCode models map + PWD pin +// CLAUDECODE strip) — see buildCliChildEnv. `guard: true` prepends the pm2// shim onto the final PATH so an unrestricted agent can't `pm2 kill` thediff --git a/server/services/taskLearning/promptRecommendations.js b/server/services/taskLearning/promptRecommendations.jsindex 5e7387b254..8413c99f74 100644--- a/server/services/taskLearning/promptRecommendations.js+++ b/server/services/taskLearning/promptRecommendations.js@@ -170,6 +170,10 @@ function generateErrorInsight(category, percentage) {message: `${percentage}% of failures due to context length exceeded`,implication: 'Prompt or codebase references are too large; be more specific about which files to analyze'},+ 'ollama-context-window': {+ message: `${percentage}% of failures due to the Ollama context window`,+ implication: 'The local model was loaded with too small a window; raise the provider\'s num_ctx rather than shrinking the task'+ },'tool-error': {message: `${percentage}% of failures due to tool execution errors`,implication: 'Add explicit error handling instructions for tool usage'