The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(small-model-mode): evidence-backed lean profile for 3B-8B local models (v2.5.0)
purple25f00ab380a9
diff --git a/src/api/discover.ts b/src/api/discover.tsindex ed172367..19d1efc1 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -449,6 +449,7 @@ export function getMainstreamTextModels(): DiscoverModel[] {// ── Gemma 4 (April 2026) ──{ name: 'Gemma 4 31B', description: 'Google Gemma 4 31B — frontier dense model, native tools + vision. 256K context.', pulls: '100K+', tags: ['31B', 'Q4_K_M', '17 GB'], updated: 'Hot', agent: true, released: '2026-04', downloadUrl: HF('unsloth/gemma-4-31B-it-GGUF', 'gemma-4-31B-it-Q4_K_M.gguf'), filename: 'gemma-4-31B-it-Q4_K_M.gguf', sizeGB: 17 },{ name: 'Gemma 4 26B MoE', description: 'Gemma 4 26B MoE — 26B brain, runs like 4B. Tools + vision. Apache 2.0.', pulls: '100K+', tags: ['26B', 'Q4_K_XL', '16 GB'], updated: 'Hot', agent: true, released: '2026-04', downloadUrl: HF('unsloth/gemma-4-26B-A4B-it-GGUF', 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf'), filename: 'gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf', sizeGB: 16 },+ { name: 'Gemma 4 12B', description: 'Google Gemma 4 12B — dense mid-size, native tools + vision + thinking. 128K context. Strong pick for Small-Model Mode on 12 GB GPUs.', pulls: '100K+', tags: ['12B', 'Q4_K_M', '7 GB'], updated: 'Hot', agent: true, released: '2026-04', downloadUrl: HF('unsloth/gemma-4-12b-it-GGUF', 'gemma-4-12b-it-Q4_K_M.gguf'), filename: 'gemma-4-12b-it-Q4_K_M.gguf', sizeGB: 7 },{ name: 'Gemma 4 E4B', description: 'Gemma 4 E4B — lightweight 4.5B, great for small GPUs.', pulls: '100K+', tags: ['4.5B', 'Q4_K_M', '5 GB'], updated: 'Hot', released: '2026-04', downloadUrl: HF('unsloth/gemma-4-E4B-it-GGUF', 'gemma-4-E4B-it-Q4_K_M.gguf'), filename: 'gemma-4-E4B-it-Q4_K_M.gguf', sizeGB: 5 },{ name: 'Gemma 4 E2B', description: 'Gemma 4 E2B — ultra-light 2.3B, runs on anything.', pulls: '100K+', tags: ['2.3B', 'Q4_K_M', '3 GB'], updated: 'New', released: '2026-04', downloadUrl: HF('unsloth/gemma-4-E2B-it-GGUF', 'gemma-4-E2B-it-Q4_K_M.gguf'), filename: 'gemma-4-E2B-it-Q4_K_M.gguf', sizeGB: 3 },// ── Qwen 3.6 27B DENSE (April 21, 2026 — new release) ──diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex 4cf6d576..c48d3cbc 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -18,6 +18,7 @@ import { FileText, Bot, ChevronDown, Download, Brain, Wrench, Radio, RefreshCw,import { PluginsDropdown } from './PluginsDropdown'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'+import { SmallModelModeToggle } from './SmallModelModeToggle'import { MemoryDebugToggle } from './MemoryDebugPanel'import { ABCompare } from './ABCompare'import { useCompareStore } from '../../stores/compareStore'@@ -196,6 +197,10 @@ export function ChatView() {{/* Context window picker (Ollama num_ctx / LM Studio loaded ctx) */}<ContextDropdown />+ {/* Small-Model Mode — only relevant when the agent loop (tools)+ is active; plain chat has no tool calls to lean out. */}+ {isAgentActive && <SmallModelModeToggle />}+{/* Memory Debug */}<MemoryDebugToggle />diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 963f6471..dd5c884e 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -7,6 +7,7 @@ import { ThinkingBlock } from './ThinkingBlock'import { MarkdownRenderer } from './MarkdownRenderer'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'+import { SmallModelModeToggle } from './SmallModelModeToggle'import { MemoryDebugToggle } from './MemoryDebugPanel'import { RealtimeCounter } from './RealtimeCounter'import { PluginsDropdown } from './PluginsDropdown'@@ -171,6 +172,7 @@ export function CodexView() {</button><TokenCounter /><ContextDropdown />+ <SmallModelModeToggle /><MemoryDebugToggle /><PluginsDropdown /></div>diff --git a/src/components/chat/SmallModelModeToggle.tsx b/src/components/chat/SmallModelModeToggle.tsxnew file mode 100644index 00000000..17eff9f3--- /dev/null+++ b/src/components/chat/SmallModelModeToggle.tsx@@ -0,0 +1,38 @@+import { Feather } from 'lucide-react'+import { useSettingsStore } from '../../stores/settingsStore'++/**+ * Small-Model Mode toggle (v2.5.0). A compact toolbar pill that flips+ * `settings.smallModelMode` — the evidence-backed lean profile that helps small+ * local models (3B-8B, e.g. gemma4:e4b, Llama-3.2-3B) reliably emit tool calls+ * and retain earlier steps. When on it: caps + embedding-ranks the tool list,+ * swaps in a lean system prompt, truncates long tool outputs, and compacts+ * history harder. It deliberately does NOT lower num_ctx (research: the+ * num_ctx-as-ceiling fear is largely a myth). Off by default — big models are+ * unaffected. Matches the ContextDropdown pill styling; lives in the Code and+ * (agent-active) Chat toolbars.+ */+export function SmallModelModeToggle() {+ const on = useSettingsStore((s) => s.settings.smallModelMode)+ const updateSettings = useSettingsStore((s) => s.updateSettings)++ return (+ <button+ onClick={() => updateSettings({ smallModelMode: !on })}+ title={+ on+ ? 'Small-Model Mode: ON — lean profile for small local models (3B-8B):\n• fewer tools (embedding-ranked + capped)\n• lean system prompt\n• truncated tool outputs\n• tighter history compaction\n(num_ctx is left untouched on purpose.)\nClick to turn off.'+ : 'Small-Model Mode — lean profile that helps small local models (3B-8B) emit valid tool calls and remember earlier steps. Click to turn on.'+ }+ className={+ 'flex items-center gap-1 px-1.5 py-0.5 rounded border transition-colors text-[0.55rem] ' ++ (on+ ? 'border-violet-500/40 bg-violet-500/[0.08] text-violet-600 dark:text-violet-300'+ : 'border-gray-200 dark:border-white/[0.06] text-gray-500 hover:border-gray-400 dark:hover:border-white/15')+ }+ >+ <Feather size={9} className="shrink-0" />+ <span>Small-Model{on ? ' · on' : ''}</span>+ </button>+ )+}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex e1d1d33c..c6c880fd 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -35,6 +35,7 @@ import { WorkflowEngine } from '../lib/workflow-engine'import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'import { generateEmbeddings } from '../api/rag'+import { truncateToolResult } from '../lib/truncate-tool-result'import { budgetFromSettings } from '../api/agents/budget'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'@@ -376,9 +377,14 @@ export function useAgentChat() {// Build agent system prompt FIRST, then append caveman style as a modifierconst hermesToolDefs = toolRegistry.toHermesToolDefs(permissions)+ // Small-Model Mode (Knob 2): swap the ~3000-char agent prompt for a lean+ // ~750-char one on the native path. The Hermes-XML branch already uses a+ // tight tool prompt (buildHermesToolPrompt), so it stays as-is.let agentSystemPrompt = strategy === 'hermes_xml'? buildHermesToolPrompt(hermesToolDefs) + (systemPrompt ? `\n\n${systemPrompt}` : '')- : buildAgentSystemPrompt(systemPrompt)+ : settings.smallModelMode+ ? buildAgentSystemPromptLean(systemPrompt)+ : buildAgentSystemPrompt(systemPrompt)// Multi-Repo (Sprint C #8): when the agent workspace has extra paths,// append a "Workspaces" section so the model can reference them by@@ -528,7 +534,11 @@ export function useAgentChat() {} catch { /* keep the 8192 floor on failure */ }}const chatOptions = {- temperature: settings.temperature,+ // Small-Model Mode (Knob 6): gently clamp temperature for tool turns.+ // FOLKLORE, not measured — research found NO temperature finding for+ // tool-calling. A low, low-entropy setting is *plausible* for valid+ // tool-call JSON, so we cap downward (never raise) rather than force.+ temperature: settings.smallModelMode ? Math.min(settings.temperature, 0.3) : settings.temperature,topP: settings.topP,topK: settings.topK,maxTokens: settings.maxTokens || undefined,@@ -543,9 +553,14 @@ export function useAgentChat() {// trim to the model's full context (e.g. 128k) while Ollama only has the// capped num_ctx allocated — that mismatch caused prompt overflow.const maxCtx = agentCtx+ // Small-Model Mode (Knob 4): keep the REAL prompt short (the true lever,+ // NOT num_ctx) — tighter ratio + an absolute cap.+ const compactBudget = settings.smallModelMode+ ? Math.floor(Math.min(maxCtx * 0.5, 6000))+ : Math.floor(maxCtx * 0.8)agentMessages = compactMessages(agentMessages as OllamaChatMessage[],- Math.floor(maxCtx * 0.8)+ compactBudget) as ChatMessage[]if (strategy === 'native') {@@ -561,11 +576,17 @@ export function useAgentChat() {// (Phase 9). The embedding call is best-effort: if Ollama is// unreachable it silently falls back to keyword-only.const lastUserMsg = agentMessages.filter(m => m.role === 'user').pop()?.content || ''+ // Small-Model Mode (Knob 1): tighten the tool cap and force the+ // embedding router even on a modest catalog (threshold 6) so a 3B-8B+ // model sees ≤6 semantically-ranked tools. Default mode keeps the+ // permissive selection unchanged for big models.const relevantDefs = await selectRelevantToolsAsync(lastUserMsg,toolRegistry.getAll(),permissions,- { embed: (texts) => generateEmbeddings(texts) }+ settings.smallModelMode+ ? { embed: (texts) => generateEmbeddings(texts), topN: 5, embeddingThreshold: 6, maxTools: 6 }+ : { embed: (texts) => generateEmbeddings(texts) })const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,@@ -1033,10 +1054,18 @@ export function useAgentChat() {// kept per-call for compatibility with how the non-native path// parses history.const resultTextFor = (r: typeof results[number]): string => {- if (r.status === 'rejected') return 'User rejected this action. Try a different approach.'- if (r.status === 'completed' || r.status === 'cached') return r.result ?? ''- // failed- return r.errorHint ? `${r.error ?? 'Tool failed'} — ${r.errorHint}` : (r.error ?? 'Tool failed')+ const text =+ r.status === 'rejected'+ ? 'User rejected this action. Try a different approach.'+ : r.status === 'completed' || r.status === 'cached'+ ? (r.result ?? '')+ : r.errorHint+ ? `${r.error ?? 'Tool failed'} — ${r.errorHint}`+ : (r.error ?? 'Tool failed')+ // Small-Model Mode (Knob 3): truncate long tool outputs (head+tail)+ // before re-injecting into history. No-op for big models. The short+ // mediaNote appended at the push sites is left intact.+ return settings.smallModelMode ? truncateToolResult(text) : text}// After a successful image/video gen, nudge a NATURAL closing comment so// the model doesn't silently loop another generation (David 2026-06-04).@@ -1302,3 +1331,22 @@ Other rules:}return agentInstructions}++// Small-Model Mode (Knob 2): a lean agent prompt (~750 chars vs ~3000 above)+// for 3B-8B models. Long prompts + big tool catalogs measurably degrade+// small-model tool-calling (LongFuncEval, arXiv 2505.10570) and small models+// have a limited instruction-following budget. Keep only what a small model+// needs to ACT — same tool names + native call format as the full prompt.+function buildAgentSystemPromptLean(basePrompt: string): string {+ const lean = `You are an autonomous agent in Locally Uncensored with tools on this computer. Do tasks by CALLING tools — do not just describe them.++Tools: file_read, file_write, file_list, file_search, web_search, web_fetch, shell_execute, code_execute, system_info, get_current_time, image_generate, video_generate.++Rules:+- To build/create/write something, CALL the tool (usually file_write) — never paste a code block and say "save this".+- After each tool result, if a step remains, immediately call the next tool. Do not narrate "I will now…" and then stop.+- Emit tool calls as valid JSON, one at a time. Never guess file contents — file_read first.+- For images/video call image_generate / video_generate as real tool calls.+- When everything is done, reply with one short sentence in the user's language.`+ return basePrompt ? `${lean}\n\n${basePrompt}` : lean+}diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex ff04585a..e98009ec 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -33,7 +33,9 @@ import { budgetFromSettings } from '../api/agents/budget'import { finalStripThinkingTags } from '../lib/thinking-stripper'import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'import { repairToolCallArgs, extractToolCallsFromContent, extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair'-import { selectRelevantTools } from '../lib/tool-selection'+import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'+import { generateEmbeddings } from '../api/rag'+import { truncateToolResult } from '../lib/truncate-tool-result'import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'import { useMemoryStore } from '../stores/memoryStore'import { extractMemoriesFromPair } from './useMemory'@@ -85,6 +87,21 @@ Rules:- Be concise in text. All the work happens in tool calls.- FINISH with a short natural-language sentence summarising what you did or found. NEVER end your turn with only a raw JSON object or a bare code block — the user needs a human-readable answer, not a data dump.`+// Small-Model Mode (Knob 2): a lean Codex prompt (~500 chars vs ~1700 above)+// for 3B-8B models. Research (LongFuncEval, arXiv 2505.10570) shows long+// prompts + big tool catalogs degrade small-model tool-calling, and small+// models have a limited instruction-following budget — the verbose autonomy /+// workflow prose costs more than it buys. Keep only the essentials and stay+// faithful to the native tool-call format. Selected at the injection point+// below when settings.smallModelMode is on (review mode still wins).+const CODEX_SYSTEM_PROMPT_LEAN = `You are a coding agent in Locally Uncensored. Use tools to do the work — never guess file contents.++Rules:+- Read a file before you edit it.+- After each tool result, if more steps remain, immediately call the next tool. Do not narrate "I will now…" and then stop.+- Emit tool calls as valid JSON, one step at a time.+- When the task is done and verified, reply with one short sentence. Never end with only raw JSON or a bare code block.`+// Local alias — the helper now lives in src/lib/ollama-stream-tools.ts// so useAgentChat can share the same wire protocol + arg-repair layer// without a code duplicate. Kept under the same name to minimise diff.@@ -261,9 +278,14 @@ export function useCodex() {// list-stripping below (REVIEW_MODE_FORBIDDEN_TOOLS) still enforces it// programmatically even if the model tries to call a write tool anyway.const reviewMode = settings.codexReviewMode === true- let systemPrompt = reviewMode- ? `${CODEX_REVIEW_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`- : `${CODEX_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`+ // Review mode always wins; otherwise Small-Model Mode swaps in the lean+ // prompt (Knob 2) for small local models.+ const baseCodexPrompt = reviewMode+ ? CODEX_REVIEW_SYSTEM_PROMPT+ : settings.smallModelMode+ ? CODEX_SYSTEM_PROMPT_LEAN+ : CODEX_SYSTEM_PROMPT+ let systemPrompt = `${baseCodexPrompt}\n\nWorking directory: ${workDir}`// Memory injection — parity with Chat + Agent. Codex was the only// surface that ignored the memory system; now it sees remembered@@ -538,9 +560,16 @@ export function useCodex() {// 8K-context local models blow past their window after a few tool// calls and Ollama starts silently truncating or errors out.try {+ // Small-Model Mode (Knob 4): keep the REAL prompt short — that is the+ // actual lever for small models, NOT num_ctx (research found the+ // num_ctx-as-ceiling fear is largely a myth). Tighter ratio + an+ // absolute cap so history stays small regardless of the allocation.+ const compactBudget = settings.smallModelMode+ ? Math.floor(Math.min(numCtx * 0.5, 6000))+ : Math.floor(numCtx * 0.8)messages = compactMessages(messages as unknown as OllamaChatMessage[],- Math.floor(numCtx * 0.8),+ compactBudget,) as unknown as ChatMessage[]} catch {// Compaction is best-effort; fall through with raw history.@@ -573,7 +602,19 @@ export function useCodex() {// tools are intentionally not surfaced by the keyword router). This// line is the single most important parity point with uselu — do NOT// replace it with the full `codexTools` set (that was the regression).- const relevantDefs = selectRelevantTools(lastUserMsg, codexTools, permissions)+ // Small-Model Mode (Knob 1): give Codex the embedding router it+ // normally lacks (it ships keyword-only) plus a hard tool cap, so a+ // 3B-8B coding model sees a short, semantically-ranked tool list.+ // Default mode keeps the proven keyword-only selection — uselu parity,+ // the single most important small-model line; do NOT widen it.+ const relevantDefs = settings.smallModelMode+ ? await selectRelevantToolsAsync(lastUserMsg, codexTools, permissions, {+ embed: (texts) => generateEmbeddings(texts),+ topN: 5,+ embeddingThreshold: 6,+ maxTools: 6,+ })+ : selectRelevantTools(lastUserMsg, codexTools, permissions)const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,function: { name: t.name, description: t.description, parameters: t.inputSchema },@@ -1135,8 +1176,16 @@ export function useCodex() {// Feed results back into LLM history (batched per-provider shape).const resultTextFor = (r: typeof results[number]): string => {- if (r.status === 'completed' || r.status === 'cached') return r.result ?? ''- return r.errorHint ? `${r.error ?? 'Tool failed'} — ${r.errorHint}` : (r.error ?? 'Tool failed')+ const text =+ r.status === 'completed' || r.status === 'cached'+ ? (r.result ?? '')+ : r.errorHint+ ? `${r.error ?? 'Tool failed'} — ${r.errorHint}`+ : (r.error ?? 'Tool failed')+ // Small-Model Mode (Knob 3): truncate long tool outputs (head+tail)+ // before they re-enter the model history. Long results cost small+ // models ~30% accuracy (LongFuncEval). No-op for big models.+ return settings.smallModelMode ? truncateToolResult(text) : text}if (providerId === 'openai' || providerId === 'anthropic') {diff --git a/src/lib/__tests__/small-model-mode.test.ts b/src/lib/__tests__/small-model-mode.test.tsnew file mode 100644index 00000000..6796f07e--- /dev/null+++ b/src/lib/__tests__/small-model-mode.test.ts@@ -0,0 +1,208 @@+/**+ * Small-Model Mode (v2.5.0) — unit tests for the deterministic knobs.+ *+ * Covers:+ * - Knob 1: applyMaxTools + the maxTools cap on the sync and async selectors+ * (ALWAYS_INCLUDE survives, fills from embedding rank, no-op unset).+ * - Knob 3: truncateToolResult (head+tail, marker, no-op under the limit).+ * - Settings: smallModelMode default false + the v6→v7 additive-merge semantics+ * the store migration relies on.+ *+ * Run: npx vitest run src/lib/__tests__/small-model-mode.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import {+ applyMaxTools,+ selectRelevantTools,+ selectRelevantToolsAsync,+ ALWAYS_INCLUDE,+} from '../tool-selection'+import { clearEmbeddingCache } from '../../api/agents/embedding-router'+import { truncateToolResult } from '../truncate-tool-result'+import { DEFAULT_SETTINGS } from '../constants'+import type { MCPToolDefinition, PermissionMap } from '../../api/mcp/types'++const fullPerms: PermissionMap = {+ filesystem: 'auto',+ terminal: 'auto',+ desktop: 'auto',+ web: 'auto',+ system: 'auto',+ image: 'auto',+ video: 'auto',+ workflow: 'auto',+}++const mkTool = (+ name: string,+ description: string,+ category: keyof PermissionMap = 'system',+): MCPToolDefinition => ({+ name,+ description,+ inputSchema: { type: 'object', properties: {}, required: [] },+ category,+ source: 'builtin',+})++// Bag-of-letters embedding (same trick as tool-selection-async.test.ts) — keeps+// the test deterministic and free of any Ollama dependency.+const fakeEmbed = async (texts: string[]): Promise<number[][]> =>+ texts.map((t) => {+ const v = new Array(26).fill(0)+ const s = t.toLowerCase()+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i)+ if (c >= 97 && c <= 122) v[c - 97] += 1+ }+ return v+ })++describe('Small-Model Mode — Knob 1: applyMaxTools', () => {+ const tools = [+ mkTool('file_read', 'read', 'filesystem'),+ mkTool('file_write', 'write', 'filesystem'),+ mkTool('get_current_time', 'time', 'system'),+ mkTool('a', 'aaaa'),+ mkTool('b', 'bbbb'),+ mkTool('c', 'cccc'),+ mkTool('d', 'dddd'),+ mkTool('e', 'eeee'),+ mkTool('f', 'ffff'),+ ]++ it('is a strict no-op when maxTools is unset (same reference back)', () => {+ expect(applyMaxTools(tools)).toBe(tools)+ })++ it('is a no-op when the list already fits', () => {+ expect(applyMaxTools(tools, 100)).toBe(tools)+ })++ it('caps the list to maxTools', () => {+ expect(applyMaxTools(tools, 4).length).toBe(4)+ })++ it('keeps every ALWAYS_INCLUDE tool even after the cap', () => {+ const out = applyMaxTools(tools, 4)+ for (const name of ALWAYS_INCLUDE) {+ expect(out.some((t) => t.name === name)).toBe(true)+ }+ })++ it('fills the non-always slots from rankOrder when provided', () => {+ // 3 ALWAYS_INCLUDE + 1 free slot; rank puts 'f' first → 'f' wins, 'a' loses.+ const out = applyMaxTools(tools, 4, ['f', 'e', 'd', 'c', 'b', 'a'])+ expect(out.length).toBe(4)+ expect(out.some((t) => t.name === 'f')).toBe(true)+ expect(out.some((t) => t.name === 'a')).toBe(false)+ })+})++describe('Small-Model Mode — Knob 1: selectRelevantTools (sync) maxTools', () => {+ const tools = [+ mkTool('file_read', 'read', 'filesystem'),+ mkTool('file_write', 'write', 'filesystem'),+ mkTool('file_list', 'list', 'filesystem'),+ mkTool('file_search', 'search', 'filesystem'),+ mkTool('shell_execute', 'run', 'terminal'),+ mkTool('web_search', 'search', 'web'),+ mkTool('get_current_time', 'time', 'system'),+ ]++ it('caps the keyword selection to maxTools', () => {+ const out = selectRelevantTools('help me with this project', tools, fullPerms, 3)+ expect(out.length).toBeLessThanOrEqual(3)+ })++ it('returns at least as many without the cap', () => {+ const capped = selectRelevantTools('help me with this project', tools, fullPerms, 3)+ const uncapped = selectRelevantTools('help me with this project', tools, fullPerms)+ expect(uncapped.length).toBeGreaterThanOrEqual(capped.length)+ })+})++describe('Small-Model Mode — Knob 1: selectRelevantToolsAsync maxTools', () => {+ beforeEach(() => clearEmbeddingCache())++ const many = Array.from({ length: 16 }, (_, i) =>+ mkTool(`tool_${i}`, `desc about topic ${i}`, 'system'),+ ).concat([+ mkTool('file_read', 'read a file on disk', 'filesystem'),+ mkTool('file_write', 'write a file on disk', 'filesystem'),+ mkTool('get_current_time', 'current local time', 'system'),+ ])++ it('caps the union to maxTools on the embedding path', async () => {+ const out = await selectRelevantToolsAsync('read the file on disk', many, fullPerms, {+ embed: fakeEmbed,+ embeddingThreshold: 5,+ topN: 8,+ maxTools: 6,+ })+ expect(out.length).toBeLessThanOrEqual(6)+ })++ it('ALWAYS_INCLUDE survives the cap', async () => {+ const out = await selectRelevantToolsAsync('read the file on disk', many, fullPerms, {+ embed: fakeEmbed,+ embeddingThreshold: 5,+ topN: 8,+ maxTools: 6,+ })+ expect(out.some((t) => t.name === 'file_read')).toBe(true)+ })++ it('is not capped when maxTools is unset', async () => {+ const out = await selectRelevantToolsAsync('read the file on disk', many, fullPerms, {+ embed: fakeEmbed,+ embeddingThreshold: 5,+ topN: 8,+ })+ // Without a cap the union can exceed 6; just assert it produced tools and+ // wasn't silently clamped to the small-model ceiling.+ expect(out.length).toBeGreaterThan(0)+ })+})++describe('Small-Model Mode — Knob 3: truncateToolResult', () => {+ it('is a no-op for output under the limit', () => {+ const s = 'short tool output'+ expect(truncateToolResult(s, 1500)).toBe(s)+ })++ it('keeps head + tail and drops the middle with a marker', () => {+ const head = 'HEAD'.repeat(500) // 2000 chars+ const mid = 'M'.repeat(2000)+ const tail = 'TAIL'.repeat(500) // 2000 chars+ const full = head + mid + tail+ const out = truncateToolResult(full, 1500)++ expect(out.length).toBeLessThan(full.length)+ expect(out.startsWith('HEAD')).toBe(true)+ expect(out.includes('TAIL')).toBe(true)+ expect(out).toMatch(/truncated \d+ chars/)+ expect(out.includes('MMMM')).toBe(false) // the middle is gone+ })++ it('defaults to a 1500-char budget', () => {+ const out = truncateToolResult('x'.repeat(5000))+ expect(out.length).toBeLessThan(5000)+ })+})++describe('Small-Model Mode — settings default + v6→v7 migration merge', () => {+ it('DEFAULT_SETTINGS.smallModelMode is false', () => {+ expect(DEFAULT_SETTINGS.smallModelMode).toBe(false)+ })++ it('the additive merge fills smallModelMode while preserving user values', () => {+ // A persisted v6 blob predates the field — exactly what the store migrate+ // hands to `{ ...DEFAULT_SETTINGS, ...persisted.settings }`.+ const oldV6 = { temperature: 0.42, thinkingEnabled: false }+ const merged = { ...DEFAULT_SETTINGS, ...oldV6 }+ expect(merged.smallModelMode).toBe(false) // default filled in+ expect(merged.temperature).toBe(0.42) // user value preserved+ expect(merged.thinkingEnabled).toBe(false) // user value preserved+ })+})diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 9e41eba6..d1cdca47 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -16,6 +16,9 @@ export const DEFAULT_SETTINGS: Settings = {onboardingDone: false,personasEnabled: true,thinkingEnabled: true,+ // Small-Model Mode (v2.5.0) — lean profile for 3B-8B local models.+ // Default OFF: big models behave exactly as before until the user flips it.+ smallModelMode: false,cavemanMode: 'off',searchProvider: 'auto',braveApiKey: '',diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.tsindex b10ac0bf..e04615d0 100644--- a/src/lib/tool-selection.ts+++ b/src/lib/tool-selection.ts@@ -87,6 +87,7 @@ export function selectRelevantTools(userMessage: string,allTools: MCPToolDefinition[],permissions: PermissionMap,+ maxTools?: number,): MCPToolDefinition[] {const msg = userMessage.toLowerCase()const selectedNames = new Set<string>(ALWAYS_INCLUDE)@@ -115,9 +116,46 @@ export function selectRelevantTools(const selected = available.filter(t => selectedNames.has(t.name))// Safety: if nothing matched at all, return all available tools- if (selected.length === 0) return available+ if (selected.length === 0) return applyMaxTools(available, maxTools)- return selected+ // Small-Model Mode (Knob 1): cap the catalog when maxTools is set. No-op+ // (returns `selected` unchanged) when unset — default behaviour preserved.+ return applyMaxTools(selected, maxTools)+}++/**+ * Hard-cap a tool list to `maxTools` entries (Small-Model Mode, Knob 1).+ * ALWAYS_INCLUDE tools are kept first (cheap + often needed mid-run); the+ * remainder fills from the incoming order, or from `rankOrder` when supplied+ * (the embedding-ranked names from the async path) so the most semantically+ * relevant tools survive the cut. Strict no-op when `maxTools` is unset or+ * the list already fits — big models keep the exact original list + order.+ *+ * Evidence: tool-catalog length is the confirmed killer for small models+ * (LongFuncEval arXiv 2505.10570 — 8B models lose 7.6-85.6% as the catalog+ * grows). Fewer tools is the single biggest fine-tuning-free win.+ */+export function applyMaxTools(+ defs: MCPToolDefinition[],+ maxTools?: number,+ rankOrder?: string[],+): MCPToolDefinition[] {+ if (!maxTools || maxTools <= 0 || defs.length <= maxTools) return defs+ const always = defs.filter((t) => ALWAYS_INCLUDE.includes(t.name))+ let rest = defs.filter((t) => !ALWAYS_INCLUDE.includes(t.name))+ if (rankOrder && rankOrder.length > 0) {+ const idx = (name: string) => {+ const i = rankOrder.indexOf(name)+ return i === -1 ? Number.MAX_SAFE_INTEGER : i+ }+ rest = [...rest].sort((a, b) => idx(a.name) - idx(b.name))+ }+ const out = [...always]+ for (const t of rest) {+ if (out.length >= maxTools) break+ out.push(t)+ }+ return out}/**@@ -132,12 +170,12 @@ export async function selectRelevantToolsAsync(userMessage: string,allTools: MCPToolDefinition[],permissions: PermissionMap,- opts?: { embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number },+ opts?: { embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number; maxTools?: number },): Promise<MCPToolDefinition[]> {const threshold = opts?.embeddingThreshold ?? EMBEDDING_ROUTING_THRESHOLDconst available = allTools.filter((t) => permissions[t.category] !== 'blocked')if (!opts?.embed || available.length <= threshold) {- return selectRelevantTools(userMessage, allTools, permissions)+ return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions), opts?.maxTools)}try {const semanticNames = await selectToolsByEmbedding(@@ -148,8 +186,13 @@ export async function selectRelevantToolsAsync()const keyword = selectRelevantTools(userMessage, allTools, permissions)const union = new Set<string>([...semanticNames, ...keyword.map((t) => t.name)])- return available.filter((t) => union.has(t.name))+ const selected = available.filter((t) => union.has(t.name))+ // Small-Model Mode (Knob 1): cap the union to maxTools, filling from+ // embedding-rank order so the most relevant tools survive. No-op when+ // maxTools is unset → `selected` (and its original order) is returned+ // byte-identical, so big-model behaviour is unchanged.+ return applyMaxTools(selected, opts.maxTools, semanticNames)} catch {- return selectRelevantTools(userMessage, allTools, permissions)+ return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions), opts?.maxTools)}}diff --git a/src/lib/truncate-tool-result.ts b/src/lib/truncate-tool-result.tsnew file mode 100644index 00000000..ab3777ba--- /dev/null+++ b/src/lib/truncate-tool-result.ts@@ -0,0 +1,26 @@+/**+ * Tool-output truncation for Small-Model Mode (Knob 3).+ *+ * Long tool responses measurably hurt small models: in IBM's LongFuncEval+ * (arXiv 2505.10570) a long tool output cost Granite-3.1-8B ~30% AST accuracy,+ * and the lost-in-the-middle effect means the MIDDLE of a long result is the+ * least-attended part anyway. So when a tool returns a wall of text (a big+ * file_read, a verbose build log), keep the HEAD and the TAIL — where the+ * signal usually lives — and drop the middle with a marker.+ *+ * Big-model behaviour is unchanged: callers only apply this when+ * settings.smallModelMode is on.+ */+export function truncateToolResult(text: string, maxChars = 1500): string {+ if (typeof text !== 'string') return text as unknown as string+ if (text.length <= maxChars) return text+ // Head-heavy split: the start of a result usually carries the most signal+ // (the top of a file, the first compiler error). Reserve ~1/3 for the tail+ // so a trailing summary / exit code / final error still survives.+ const headChars = Math.max(0, Math.floor(maxChars * 0.66))+ const tailChars = Math.max(0, maxChars - headChars)+ const head = text.slice(0, headChars)+ const tail = tailChars > 0 ? text.slice(text.length - tailChars) : ''+ const dropped = text.length - head.length - tail.length+ return `${head}\n\n…[truncated ${dropped} chars for small-model mode]…\n\n${tail}`+}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex b8b8de3a..b8009af2 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -11,7 +11,11 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'// v6 (uselu design port): added settings.personasEnabled (master persona// switch, default true). Bumped so existing users get the default ON instead// of an undefined → falsy "personas off" surprise.-const STORE_VERSION = 6+// v7 (Small-Model Mode v2.5.0): added settings.smallModelMode (lean profile+// for 3B-8B local models, default false). Same additive merge path below+// ({ ...DEFAULT_SETTINGS, ...persisted.settings }) fills the new default in+// while preserving every existing user value — existing users get it OFF.+const STORE_VERSION = 7interface SettingsState {settings: Settingsdiff --git a/src/types/settings.ts b/src/types/settings.tsindex 6cb30e05..0b782810 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -16,6 +16,18 @@ export interface Settings {* prompt (raw model). Default true. Ported from the uselu web companion. */personasEnabled: booleanthinkingEnabled: boolean+ /**+ * Small-Model Mode (v2.5.0). Evidence-backed lean profile that maximises+ * tool-call reliability + context retention on small local models (3B-8B,+ * e.g. gemma4:e4b, Llama-3.2-3B, Qwen3-8B). When on it flips: a tighter+ * tool cap + embedding-routing (Knob 1), a lean system prompt (Knob 2),+ * tool-output truncation (Knob 3), and aggressive history compaction+ * (Knob 4). It deliberately does NOT lower num_ctx — research found the+ * num_ctx-as-ceiling fear is largely a myth; the real lever is keeping the+ * actual prompt short (see finding_small_model_tool_calling_research).+ * Default false (big models are unaffected). Manual knob, not auto-forced.+ */+ smallModelMode: booleancavemanMode: CavemanModesearchProvider: SearchProviderbraveApiKey: string