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(agent): local models up to 35B get a short tool list and tool_search (C59 A2)
purplee7e389e03a68
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex 957d84f9..9acf5394 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -2407,6 +2407,15 @@ export function SettingsPage() {<div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">Stops an agent run that keeps repeating the same steps ("Loop guard halted the run"). Off: the run goes on until its step limit or until you press Stop.</div>+ {/* C59 A2: the compact profile for local models, on by default. */}+ <InlineToggle+ label="Short tool list for local models"+ enabled={settings.agentCompactAuto !== false}+ onChange={() => updateSettings({ agentCompactAuto: settings.agentCompactAuto === false })}+ />+ <div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">+ A local model up to about 35B sees the core tools with short descriptions and finds every other tool with tool_search. Small model mode still wins.+ </div><buttononClick={() => useAgentModeStore.getState().resetTutorial()}className="text-[0.6rem] text-gray-500 hover:text-gray-300 transition-colors"diff --git a/src/hooks/__tests__/chat-tools-allowlist-at-execution.test.ts b/src/hooks/__tests__/chat-tools-allowlist-at-execution.test.tsindex 7835bace..b28eee0c 100644--- a/src/hooks/__tests__/chat-tools-allowlist-at-execution.test.ts+++ b/src/hooks/__tests__/chat-tools-allowlist-at-execution.test.ts@@ -73,9 +73,11 @@ describe('useAgentChat installs that gate on the executor', () => {const agent = read('../useAgentChat.ts')it('the allow-list is checked at the execution site, not only at catalog build', () => {+ // C59 A2 put tool_search in front of it; the curated gate is unchanged.expect(agent).toContain(- 'getTool: (name) => (toolMatchesCurated(name) ? toolRegistry.resolveExecutable(name) : undefined)',+ ': toolMatchesCurated(name) ? toolRegistry.resolveExecutable(name) : undefined),',)+ expect(agent).toMatch(/getTool: \(name\) => \(compactRun && name === TOOL_SEARCH && stepOfferedNames\.has\(TOOL_SEARCH\)\s*\? TOOL_SEARCH_DEF\s*: toolMatchesCurated\(name\)/)})it('the same predicate still filters the offered catalog, so the two cannot drift', () => {diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.tsindex a1eac43c..40cebfe3 100644--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts@@ -178,7 +178,7 @@ describe('the prompt and the tool list answer the same question', () => {describe('the wiring in useCodex', () => {it('the gate runs on the routed list, so it covers all three branches', () => {- expect(src).toMatch(/const relevantDefs = gatePlanTool\(\s*gateCreateTools\(routedDefs, lastUserMsg, createGateOpened\),/)+ expect(src).toMatch(/const gatedDefs = gatePlanTool\(\s*gateCreateTools\(routedDefs, lastUserMsg, createGateOpened\),/)})it('the hermes fallback is gated too, it carries the weakest models', () => {diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex a0e61f4d..6744b8dc 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -171,6 +171,8 @@ import { asString, errorText, isRecord, prop } from '../types/json-guards'import type { ToolArgs } from '../api/mcp/types'import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'import { buildChatSystemPrompt } from '../lib/system-prompt'+import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS } from '../lib/agent-profile'+import { TOOL_SEARCH, TOOL_SEARCH_DEF, briefFor, clearUnlockedTools, runToolSearch, withToolSearch } from '../lib/tool-search'import { withChatPersona, samplingPresetFor, speakerCustomParams, speakerPersonaFor } from '../lib/chat-persona'import { injectPersonaNote, noteTokens, personaNoteOf } from '../lib/persona-note'@@ -1227,6 +1229,21 @@ export function useAgentChat() {userText: userContent,todos: convId ? useTodoStore.getState().getTodos(convId) : [],})+ // C59 A2: a local model up to ~35B gets the compact profile (short tool+ // list, one-line descriptions, tool_search), decided once per run.+ const agentProfile = agentProfileFor({+ smallModelMode: settings.smallModelMode,+ compactAuto: settings.agentCompactAuto,+ local: isLocalModelByName(activeModel),+ modelName: activeModel,+ parameterSize: (useModelStore.getState().models.find((m) => m.name === activeModel) as { details?: { parameter_size?: string } } | undefined)?.details?.parameter_size,+ })+ const compactRun = agentProfile === 'compact'+ clearUnlockedTools(convId)+ /** The tools offered in the step that is running, for tool_search. */+ let stepOfferedNames = new Set<string>()+ const briefDefs = <T extends { name: string; description: string }>(defs: T[]): T[] =>+ compactRun ? defs.map((t) => ({ ...t, description: briefFor(t) })) : defs// Round 9, N15: a phone with a small window gets the short tool list// (lib/phone-context-fit.ts). 0 everywhere else, and then nothing changes.const phoneToolCtx: number = singleModelSlot()@@ -1238,7 +1255,7 @@ export function useAgentChat() {.find((c) => c.id === convId)?.messages ?? []).filter((m) => m.role === 'user').map((m) => m.content))const hermesToolDefs = strategy === 'hermes_xml'- ? withCreateTools(gatePlanTool(await selectRelevantToolsAsync(+ ? briefDefs(withCreateTools(gatePlanTool(await selectRelevantToolsAsync(toolRoutingText(userContent, attachedFiles),toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),permissions,@@ -1249,7 +1266,7 @@ export function useAgentChat() {),reaText,},- ), planAllowed), toolRegistry.getAll())+ ), planAllowed), toolRegistry.getAll())): []// Small-Model Mode (Knob 2): swap the ~3000-char agent prompt for a lean// ~750-char one on the native path. Der Hermes-Zweig behaelt seine eigene@@ -1292,6 +1309,9 @@ export function useAgentChat() {// Computer control: the rules for the screen travel with the tool. The// section is only there when the user switched the tool on.agentSystemPrompt = withComputerUsePrompt(agentSystemPrompt, offeredTools.map((t) => t.name))+ if (compactRun && strategy !== 'hermes_xml' && !opts?.chatToolsMode) {+ agentSystemPrompt += '\n\nYour tool list is kept short on purpose. When you need a tool that is not in it, call tool_search with a few words first; the tools it finds are in your list from the next step on.'+ }if (opts?.settingsTools) agentSystemPrompt += `\n\n${SETTINGS_PROMPT_LINE}`// Create in chat: on = the paragraph; outside Cloud mode and without the// account's release not a word. Off = not a word, unless the customer@@ -1966,7 +1986,7 @@ export function useAgentChat() {// Als sie hier standen, gab es sie nur an DIESER Stelle — der// hermes_xml-Zweig oben nahm stattdessen den ganzen Katalog, und// niemandem fiel es auf, weil nichts brach.- const relevantDefs = withCreateTools(gatePlanTool(await selectRelevantToolsAsync(+ const selectedDefs = withCreateTools(gatePlanTool(await selectRelevantToolsAsync(lastUserMsg,toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),permissions,@@ -1975,9 +1995,16 @@ export function useAgentChat() {toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts, undefined, { purpose: 'tool-selection' })),phoneToolCtx, SMALL_MODEL_MAX_TOOLS,),+ ...(compactRun ? { maxTools: COMPACT_MAX_TOOLS } : {}),reaText,},), planAllowed), toolRegistry.getAll())+ // C59 A2: on the compact profile the cut tools stay reachable+ // through tool_search, and whatever a search unlocked rides along.+ const relevantDefs = compactRun+ ? briefDefs(withToolSearch(selectedDefs, offeredTools, convId, TOOL_SEARCH_DEF))+ : selectedDefs+ stepOfferedNames = new Set(relevantDefs.map((t) => t.name))const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,function: { name: t.name, description: t.description, parameters: t.inputSchema },@@ -3045,11 +3072,16 @@ export function useAgentChat() {// naming a terminal tool. A tool the run never offered does not// exist for this run, and the model gets told so and can retry with// one that does.- getTool: (name) => (toolMatchesCurated(name) ? toolRegistry.resolveExecutable(name) : undefined),+ getTool: (name) => (compactRun && name === TOOL_SEARCH && stepOfferedNames.has(TOOL_SEARCH)+ ? TOOL_SEARCH_DEF+ : toolMatchesCurated(name) ? toolRegistry.resolveExecutable(name) : undefined),// Timeout backstop shared with Codex (audit B9): before this the// Agent loop had NO ceiling around a tool call, so one hung tool// wedged the whole run with no way out but a restart.execute: (name: string, args: ToolArgs, callRun?: AgentRunContext, signal?: AbortSignal) => {+ if (compactRun && name === TOOL_SEARCH) {+ return Promise.resolve(runToolSearch(convId, args, offeredTools, stepOfferedNames))+ }const timed = (base: AbortSignal) => raceWithToolTimeout(name,toolCallCapMs(name, args, settings),@@ -3241,7 +3273,7 @@ export function useAgentChat() {// Die Notiz haengt NACH dem Kuerzen dran, sonst schneidet ein// langes Fehlerprotokoll sie gerade dann weg, wenn sie gebraucht wird.return (- truncateToolResult(text, phoneResultChars(agentCtx, settings.smallModelMode ? 1500 : 60000)) ++ truncateToolResult(text, phoneResultChars(agentCtx, resultCharsFor(agentProfile))) +toolFailureNote(r.status))}diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 7433f604..1b8da8a6 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -83,7 +83,10 @@ import type { ToolArgs } from '../api/mcp/types'import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'import { repairToolCall } from '../lib/loose-tool-parse'-import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, isGatedTool } from '../lib/tool-selection'+import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, isGatedTool, applyMaxTools } from '../lib/tool-selection'+import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS } from '../lib/agent-profile'+import type { MCPToolDefinition } from '../api/mcp/types'+import { TOOL_SEARCH, TOOL_SEARCH_DEF, briefFor, clearUnlockedTools, runToolSearch, withToolSearch } from '../lib/tool-search'import { reaRoutingText } from '../lib/plugins/rea-tools'import { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'@@ -746,6 +749,21 @@ export function useCodex() {if (strategy === 'native' && (providerId === 'openai' || isCompatProviderId(providerId)) && provider.serverToolSupport) {if ((await provider.serverToolSupport(modelToUse)) === false) strategy = 'hermes_xml'}+ // C59 A2: a local model up to ~35B gets the compact profile (short tool+ // list, one-line descriptions, tool_search). Native transport only: the+ // Hermes prompt is built once and cannot grow mid-run.+ const codexProfile = agentProfileFor({+ smallModelMode: settings.smallModelMode,+ compactAuto: settings.agentCompactAuto,+ local: isLocalModelByName(activeModel),+ modelName: activeModel,+ parameterSize: (useModelStore.getState().models.find((m) => m.name === activeModel) as { details?: { parameter_size?: string } } | undefined)?.details?.parameter_size,+ })+ const compactRun = codexProfile === 'compact' && strategy === 'native'+ clearUnlockedTools(convId)+ /** The tools offered in the step that is running, and the run's catalog, for tool_search. */+ let stepOfferedNames = new Set<string>()+ let searchCatalog: MCPToolDefinition[] = []// Pin the text model driving this Codex run — parity with useAgentChat.// The VRAM hand-off orchestrator (image/video generation in Code mode,@@ -840,7 +858,10 @@ export function useCodex() {// Die Verhaltenszeile haengt an JEDER Oberflaeche (lib/system-prompt.ts).// Der Coding-Agent bringt seine eigene Rolle mit, deshalb nur die Zeile// und nicht der ganze Grundtext.- let systemPrompt = withHouseConduct(`${baseCodexPrompt}${assetLine}\n\n${platformPromptLine()}\n${workDirLine}`)+ const toolSearchLine = compactRun && !reviewMode+ ? '\n\nYour tool list is kept short on purpose. When you need a tool that is not in it, call tool_search with a few words first; the tools it finds are in your list from the next step on.'+ : ''+ let systemPrompt = withHouseConduct(`${baseCodexPrompt}${assetLine}${toolSearchLine}\n\n${platformPromptLine()}\n${workDirLine}`)// Standing goal (/goal) — ahead of the rules and the repo map so it frames// everything that follows instead of reading as an afterthought.systemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))@@ -1572,10 +1593,12 @@ export function useCodex() {}): !isLocalModelByName(activeModel)? codexTools- : selectRelevantTools(lastUserMsg, codexTools, permissions, undefined, reaText)+ : compactRun+ ? applyMaxTools(selectRelevantTools(lastUserMsg, codexTools, permissions, undefined, reaText), COMPACT_MAX_TOOLS)+ : selectRelevantTools(lastUserMsg, codexTools, permissions, undefined, reaText)// Planning is opt-in (lib/plan-gate.ts): without Plan mode, a plan// request or an open plan, todo_write is not offered at all.- const relevantDefs = gatePlanTool(+ const gatedDefs = gatePlanTool(gateCreateTools(routedDefs, lastUserMsg, createGateOpened),planToolAllowed({mode: codexMode,@@ -1583,6 +1606,14 @@ export function useCodex() {todos: convId ? useTodoStore.getState().getTodos(convId) : [],}),)+ // C59 A2: on the compact profile the cut tools stay reachable+ // through tool_search, and whatever a search unlocked rides along.+ searchCatalog = codexTools+ const relevantDefs = compactRun+ ? withToolSearch(gatedDefs, codexTools, convId, TOOL_SEARCH_DEF)+ .map((t) => ({ ...t, description: briefFor(t) }))+ : gatedDefs+ stepOfferedNames = new Set(relevantDefs.map((t) => t.name))const tools: ToolDefinition[] = relevantDefs.map(t => ({type: 'function' as const,function: { name: t.name, description: t.description, parameters: t.inputSchema },@@ -2372,8 +2403,13 @@ export function useCodex() {}const results = await executeParallel(requests, {- getTool: (name) => toolRegistry.resolveExecutable(name),+ getTool: (name) => (compactRun && name === TOOL_SEARCH && stepOfferedNames.has(TOOL_SEARCH)+ ? TOOL_SEARCH_DEF+ : toolRegistry.resolveExecutable(name)),execute: (name: string, args: ToolArgs, _run, signal) => {+ if (compactRun && name === TOOL_SEARCH) {+ return Promise.resolve(runToolSearch(convId, args, searchCatalog, stepOfferedNames))+ }// A create tool the gate had closed still reaches the registry, so// the run self-heals: this call runs, and the next step offers the// schemas instead of pretending the capability is gone.@@ -2543,7 +2579,7 @@ export function useCodex() {// file_read rode along VERBATIM in every following request via// compaction's KEEP_RECENT window — live 225k-token prompts per// iteration, slow turns and a drained wallet (Morgan, 2026-07-26).- return truncateToolResult(text, settings.smallModelMode ? 1500 : 60000)+ return truncateToolResult(text, resultCharsFor(codexProfile))}// lu-cloud is OpenAI-compatible and STRICTLY validates thediff --git a/src/lib/__tests__/agent-compact-profile.test.ts b/src/lib/__tests__/agent-compact-profile.test.tsnew file mode 100644index 00000000..0761c67e--- /dev/null+++ b/src/lib/__tests__/agent-compact-profile.test.ts@@ -0,0 +1,128 @@+/**+ * C59 A2: local models up to ~35B get a short tool list with one-line+ * descriptions and reach every other tool through tool_search.+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { agentProfileFor, paramsBillions, resultCharsFor, COMPACT_MAX_TOOLS } from '../agent-profile'+import {+ CORE_BRIEFS, TOOL_SEARCH, TOOL_SEARCH_DEF, briefDescription, briefFor, clearUnlockedTools,+ runToolSearch, searchTools, unlockedTools, withToolSearch,+} from '../tool-search'+import { resolveApprovalLevel } from '../agent-approval-policy'+import { ALWAYS_INCLUDE } from '../tool-selection'+import type { MCPToolDefinition } from '../../api/mcp/types'++const tool = (name: string, description: string): MCPToolDefinition => ({+ name, description, inputSchema: { type: 'object', properties: {}, required: [] }, category: 'system', source: 'builtin',+})++const CATALOG = [+ tool('file_read', 'Read a file.'),+ tool('file_write', 'Write a whole file.'),+ tool('shell_execute', 'THE terminal. Run a shell command.'),+ tool('video_generate', 'Make one short clip on this computer.'),+ tool('image_generate', 'Make one picture on this computer.'),+ tool('delegate_task', 'Spawn a focused sub-agent to work on a sub-goal autonomously.'),+ tool('get_settings', 'Read LU app settings: key, current value, allowed values.'),+]++describe('which profile a model gets', () => {+ it('reads the size from the name or the metadata', () => {+ expect(paramsBillions('hf.co/DavidAU/Qwen3.5-9B-The-Defiant-Fable-Uncensored-Heretic-NEO-IMATRIX-MAX-MTP-GGUF:Q4_K_M')).toBe(9)+ expect(paramsBillions('hf.co/HauhauCS/Qwen3.8-27B-Uncensored-HauhauCS-Aggressive-MTP-GGUF:Qwen3.8-27B-Uncensored-HauhauCS-Aggressive-Q4_K_P.gguf')).toBe(27)+ expect(paramsBillions('qwen3-coder:30b-a3b')).toBe(30)+ expect(paramsBillions('gpt-oss:20b')).toBe(20)+ expect(paramsBillions('llama3.3:70b')).toBe(70)+ expect(paramsBillions('mystery-model', '8.0B')).toBe(8)+ // "Qwen3.5" is a version, not 3.5 billion.+ expect(paramsBillions('Qwen3.5-instruct')).toBeNull()+ })++ it('local up to 35B is compact, bigger or cloud is full, Small-Model Mode wins', () => {+ expect(agentProfileFor({ local: true, modelName: 'qwen3.5:9b' })).toBe('compact')+ expect(agentProfileFor({ local: true, modelName: 'qwen3-coder:30b-a3b' })).toBe('compact')+ expect(agentProfileFor({ local: true, modelName: 'llama3.3:70b' })).toBe('full')+ expect(agentProfileFor({ local: false, modelName: 'glm-5.3-flash-9b' })).toBe('full')+ expect(agentProfileFor({ local: true, modelName: 'unknown-local' })).toBe('compact')+ expect(agentProfileFor({ local: true, modelName: 'qwen3.5:9b', compactAuto: false })).toBe('full')+ expect(agentProfileFor({ local: true, modelName: 'llama3.3:70b', smallModelMode: true })).toBe('tiny')+ })++ it('a compact result is capped between the tiny and the full one', () => {+ expect(resultCharsFor('tiny')).toBe(1500)+ expect(resultCharsFor('compact')).toBe(16000)+ expect(resultCharsFor('full')).toBe(60000)+ })+})++describe('tool_search', () => {+ beforeEach(() => clearUnlockedTools('c1'))++ it('finds a tool by what it does, name words first', () => {+ expect(searchTools('make a video', CATALOG).map((t) => t.name)[0]).toBe('video_generate')+ expect(searchTools('settings', CATALOG).map((t) => t.name)).toEqual(['get_settings'])+ expect(searchTools('sub agent', CATALOG).map((t) => t.name)).toContain('delegate_task')+ expect(searchTools('the a of', CATALOG)).toEqual([])+ })++ it('a search unlocks its hits for the next step of the same conversation', () => {+ const offered = new Set(['file_read', 'file_write', TOOL_SEARCH])+ const text = runToolSearch('c1', { query: 'generate a video clip' }, CATALOG, offered)+ expect(text).toMatch(/video_generate/)+ expect(unlockedTools('c1').has('video_generate')).toBe(true)+ expect(unlockedTools('c2').size).toBe(0)+ const next = withToolSearch([CATALOG[0], CATALOG[1]], CATALOG, 'c1', TOOL_SEARCH_DEF)+ expect(next.map((t) => t.name)).toEqual(['file_read', 'file_write', 'video_generate', TOOL_SEARCH])+ })++ it('names a tool that is already there instead of unlocking nothing', () => {+ const text = runToolSearch('c1', { query: 'read a file' }, CATALOG, new Set(['file_read', TOOL_SEARCH]))+ expect(text).toMatch(/Already in your list: file_read/)+ expect(runToolSearch('c1', {}, CATALOG, new Set())).toMatch(/needs a `query`/)+ })++ it('is only offered when the list left something out', () => {+ expect(withToolSearch(CATALOG, CATALOG, 'c1', TOOL_SEARCH_DEF).map((t) => t.name)).not.toContain(TOOL_SEARCH)+ })++ it('runs without asking: it only reads the catalog', () => {+ expect(resolveApprovalLevel(TOOL_SEARCH, { categoryLevel: 'confirm', codexMode: null, readOnlyRun: false })).toBe('auto')+ expect(resolveApprovalLevel(TOOL_SEARCH, { categoryLevel: 'confirm', codexMode: 'plan', readOnlyRun: true })).toBe('auto')+ })+})++describe('one-line descriptions', () => {+ it('every core tool has its own line, short and with the rule that matters', () => {+ for (const name of [...ALWAYS_INCLUDE, 'shell_execute', 'file_list', 'file_search', 'web_search', 'web_fetch']) {+ expect(CORE_BRIEFS[name], name).toBeTruthy()+ expect(CORE_BRIEFS[name].length, name).toBeLessThanOrEqual(160)+ }+ expect(CORE_BRIEFS.todo_write).toMatch(/COMPLETE list.*never on its own/)+ expect(CORE_BRIEFS.file_edit).toMatch(/old_string/)+ })++ it('other tools keep their first sentence', () => {+ expect(briefFor(tool('pr_resume', 'Pick up where a GitHub PR left off. Long text follows.'))).toBe('Pick up where a GitHub PR left off.')+ expect(briefDescription('x'.repeat(300)).length).toBe(160)+ })++ it('the compact list stays within the planned size', () => {+ expect(COMPACT_MAX_TOOLS).toBeGreaterThanOrEqual(ALWAYS_INCLUDE.length + 2)+ })+})++describe('the loops use it', () => {+ const src = (p: string) => readFileSync(resolve(__dirname, '..', '..', p), 'utf8')+ it('Agent and Code decide the profile and cap results from it', () => {+ for (const p of ['hooks/useAgentChat.ts', 'hooks/useCodex.ts']) {+ const s = src(p)+ expect(s, p).toMatch(/agentProfileFor\(/)+ expect(s, p).toMatch(/resultCharsFor\(/)+ expect(s, p).toMatch(/withToolSearch\(/)+ expect(s, p).toMatch(/runToolSearch\(/)+ expect(s, p).not.toMatch(/settings\.smallModelMode \? 1500 : 60000/)+ }+ })+})diff --git a/src/lib/__tests__/phone-context-fit.test.ts b/src/lib/__tests__/phone-context-fit.test.tsindex a6021c65..1989739b 100644--- a/src/lib/__tests__/phone-context-fit.test.ts+++ b/src/lib/__tests__/phone-context-fit.test.ts@@ -243,6 +243,6 @@ describe('the agent loop asks', () => {})it('caps a result where it enters the run, with the numbers of the desktop as the fallback', () => {- expect(hook).toContain('truncateToolResult(text, phoneResultChars(agentCtx, settings.smallModelMode ? 1500 : 60000))')+ expect(hook).toContain('truncateToolResult(text, phoneResultChars(agentCtx, resultCharsFor(agentProfile)))')})})diff --git a/src/lib/agent-approval-policy.ts b/src/lib/agent-approval-policy.tsindex a8134384..ea71b475 100644--- a/src/lib/agent-approval-policy.ts+++ b/src/lib/agent-approval-policy.ts@@ -165,6 +165,10 @@ export function resolveApprovalLevel(toolName: string, d: FrontDecision): Permis// 3. Ein Werkzeug mit eigenem Riegel fragt selbst (siehe SELF_GATED_TOOLS).if (SELF_GATED_TOOLS.has(toolName)) return 'auto'+ // tool_search reads the tool catalog of this run and touches nothing+ // (lib/tool-search.ts, C59). It is not in the registry, so its category+ // would read as the unknown tool's 'confirm'.+ if (toolName === 'tool_search') return 'auto'if (d.codexMode !== null) {// Code-Oberflaeche: das Preset IST die Entscheidung von vorne. Derdiff --git a/src/lib/agent-profile.ts b/src/lib/agent-profile.tsnew file mode 100644index 00000000..05f227f9--- /dev/null+++ b/src/lib/agent-profile.ts@@ -0,0 +1,70 @@+/**+ * Which agent profile a run gets (C59 A2).+ *+ * - 'tiny' Small-Model Mode, switched on by the user: the lean prompt, six+ * tools, results cut to 1 500 characters. Built for 3–8B models.+ * - 'compact' a local model of up to ~35B, automatically: the normal prompt,+ * a short tool list with one-line descriptions plus tool_search,+ * results capped at 16 000 characters.+ * - 'full' everything else, cloud and big local models: unchanged.+ *+ * Why automatic: Small-Model Mode is off by default (lib/constants.ts) and a+ * user with a 9B model never finds it, so a 9B saw the same ~5k tokens of+ * tool schemas as a cloud model (useAgentChat measured 17 tools ≈ 4.9k+ * tokens). The harness study of Fan et al. 2026 (arXiv 2609.20804) and+ * RAG-MCP both find that weaker models pick tools better from a short list.+ * 'tiny' stays as it was: it is the user's explicit choice.+ */++export type AgentProfile = 'tiny' | 'compact' | 'full'++/** Above this many billion parameters a local model gets the full profile. */+export const COMPACT_MAX_PARAMS_B = 35++/** The tool list of a compact run, before tool_search and unlocked tools. */+export const COMPACT_MAX_TOOLS = 8++/** A tool result in a compact run: about 4k tokens, an eighth of a 32k window. */+export const COMPACT_RESULT_CHARS = 16_000++/**+ * Billions of parameters as the model's name or its metadata says, or null.+ * A mixture of experts counts with its total (30B-A3B → 30): memory and+ * knowledge follow the total, and the profile is about the model's skill,+ * not its speed.+ */+export function paramsBillions(name: string, parameterSize?: string | null): number | null {+ const fromMeta = parameterSize?.match(/(\d+(?:\.\d+)?)\s*B/i)+ if (fromMeta) return Number(fromMeta[1])+ // The last path segment carries the size; a repo owner like "Qwen3.5" must+ // not be read as 3.5B, so a size needs a B right after the number.+ const tail = name.split(/[/:]/).slice(-2).join(' ')+ const all = [...tail.matchAll(/(?:^|[^a-z0-9.])(\d+(?:\.\d+)?)\s?[bB](?![a-z0-9])/gi)].map((m) => Number(m[1]))+ const sizes = all.filter((n) => n > 0 && n < 2000)+ return sizes.length ? Math.max(...sizes) : null+}++export interface ProfileInput {+ /** settings.smallModelMode */+ smallModelMode?: boolean+ /** settings.agentCompactAuto; undefined counts as on. */+ compactAuto?: boolean+ /** The model runs on this machine (agents/model-locality). */+ local: boolean+ modelName: string+ parameterSize?: string | null+}++export function agentProfileFor(input: ProfileInput): AgentProfile {+ if (input.smallModelMode) return 'tiny'+ if (input.compactAuto === false || !input.local) return 'full'+ const b = paramsBillions(input.modelName, input.parameterSize)+ // Unknown size on this machine: compact. Most local models are small, and a+ // big one with a short list still reaches everything through tool_search.+ return b === null || b <= COMPACT_MAX_PARAMS_B ? 'compact' : 'full'+}++/** How many characters of one tool result go back to the model. */+export function resultCharsFor(profile: AgentProfile): number {+ return profile === 'tiny' ? 1500 : profile === 'compact' ? COMPACT_RESULT_CHARS : 60000+}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 2d07d845..5960e112 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -62,6 +62,7 @@ export const DEFAULT_SETTINGS: Settings = {agentMaxToolCalls: 400,agentMaxIterations: 200,agentLoopGuard: true,+ agentCompactAuto: true,// Die heutigen festen Werte aus sub-agent.ts, unveraendert uebernommen:// wer nichts einstellt, bekommt exakt das Verhalten von 2.6.7.subAgentMaxToolCalls: 10,diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.tsindex 83140b08..cfd520a5 100644--- a/src/lib/settings-catalog.ts+++ b/src/lib/settings-catalog.ts@@ -208,6 +208,7 @@ export const CATALOG: readonly CatalogEntry[] = [// Agent limits: read at the start of a run, so a run cannot raise its own.e('agentMaxToolCalls', 'Agent tool call limit', 'agent', 'Most tool calls per message. Applies from the next message.', int(0, 10_000, '', 'unlimited')),e('agentMaxIterations', 'Agent step limit', 'agent', 'Most steps per message. Applies from the next message.', int(0, 10_000, '', 'unlimited')),+ e('agentCompactAuto', 'Short tool list for local models', 'agent', 'Local models up to about 35B see the core tools and find the rest with tool_search.', bool()),e('agentLoopGuard', 'Loop guard', 'agent', 'Stops an agent run that repeats the same steps. Off: the run goes on until its step limit or Stop.', bool()),e('subAgentMaxToolCalls', 'Sub-agent tool call limit', 'agent', 'Most tool calls of one sub-agent.', int(0, SUB_AGENT_LIMIT_MAX, '', 'default')),e('subAgentMaxIterations', 'Sub-agent step limit', 'agent', 'Most steps of one sub-agent.', int(0, SUB_AGENT_LIMIT_MAX, '', 'default')),diff --git a/src/lib/settings-reset.ts b/src/lib/settings-reset.tsindex 5e7a91c5..0014d88e 100644--- a/src/lib/settings-reset.ts+++ b/src/lib/settings-reset.ts@@ -30,7 +30,7 @@ export const SETTINGS_TAB_RESET_KEYS: Record<SettingsTab, (keyof Settings)[]> =backends: ['apiEndpoint', 'hfDownloadPathOverride', 'downloadLimitMBps', 'exclusiveVramMode', 'builtinEngine', 'engineIdleUnloadMinutes'],agent: ['personasEnabled', 'defaultWorkspace',- 'agentMaxToolCalls', 'agentMaxIterations', 'agentLoopGuard',+ 'agentMaxToolCalls', 'agentMaxIterations', 'agentLoopGuard', 'agentCompactAuto','subAgentMaxToolCalls', 'subAgentMaxIterations', 'loopMaxPasses','searchProvider', 'braveApiKey', 'tavilyApiKey', 'exaApiKey', 'searchUserAgent','codexArchitectMode', 'codexArchitectModel', 'codexArchitectAllowCloud',diff --git a/src/lib/tool-search.ts b/src/lib/tool-search.tsnew file mode 100644index 00000000..39545d58--- /dev/null+++ b/src/lib/tool-search.ts@@ -0,0 +1,187 @@+/**+ * Tool search: a small local model sees a short tool list and can still reach+ * every other tool (C59 A2).+ *+ * The selection in tool-selection.ts decides once per step, from the user's+ * words, which tools ride along. On a big catalog a cap has to cut, and a cut+ * tool used to be gone for the run: a model that found out mid-task that it+ * needed `video_generate` or an MCP tool could only say so. OpenClaw's answer+ * (docs.openclaw.ai/tools/tool-search) is a meta tool: the model asks for a+ * capability in its own words, gets the few matching tools back by name, and+ * from the next step on those tools are in its list. RAG-MCP measured what the+ * short list buys: selection accuracy 13.6 % → 43.1 % (arXiv 2505.03275).+ *+ * The search itself is plain word matching over name and description. No+ * embedding call: it has to work on a machine whose embedding model is not+ * there, and the catalog is a few dozen entries.+ *+ * Unlocked tools are kept per conversation for the rest of the run, so the+ * step after the search carries them. `clearUnlockedTools` at the start of a+ * user turn drops them again.+ */+import type { MCPToolDefinition } from '../api/mcp/types'++export const TOOL_SEARCH = 'tool_search'++/** At most this many tools come back from one search (OpenClaw: 5 for local models). */+export const TOOL_SEARCH_LIMIT = 5++export const TOOL_SEARCH_DEF: MCPToolDefinition = {+ name: TOOL_SEARCH,+ description:+ 'Find a tool that is not in your list yet. Describe what you need in a few words '+ + '(e.g. "make a video", "list running processes"). The matching tools are added to your list for the next step.',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'What the tool should do, a few words' },+ },+ required: ['query'],+ },+ category: 'system',+ source: 'builtin',+}++const unlocked = new Map<string, Set<string>>()++export function unlockedTools(convId: string | null | undefined): ReadonlySet<string> {+ return (convId && unlocked.get(convId)) || new Set()+}++export function unlockTools(convId: string | null | undefined, names: string[]): void {+ if (!convId || !names.length) return+ const set = unlocked.get(convId) ?? new Set<string>()+ for (const n of names) set.add(n)+ unlocked.set(convId, set)+}++export function clearUnlockedTools(convId: string | null | undefined): void {+ if (convId) unlocked.delete(convId)+}++const STOP = new Set(['a', 'an', 'the', 'to', 'of', 'and', 'or', 'for', 'in', 'on', 'with', 'from', 'tool', 'tools', 'my', 'me', 'i', 'it', 'is', 'that', 'this'])++function words(text: string): string[] {+ return text+ .toLowerCase()+ .replace(/[_\-./]/g, ' ')+ .split(/[^a-z0-9äöüß]+/)+ .filter((w) => w.length > 1 && !STOP.has(w))+}++/** Two words match when one starts with the other (generate ~ generation, list ~ listing). */+function close(a: string, b: string): boolean {+ if (a === b) return true+ const n = Math.min(a.length, b.length)+ return n >= 4 && (a.startsWith(b.slice(0, Math.max(4, n - 2))) || b.startsWith(a.slice(0, Math.max(4, n - 2))))+}++interface Scored { t: MCPToolDefinition; score: number }++function scoreTools(query: string, catalog: readonly MCPToolDefinition[]): Scored[] {+ const q = words(query)+ if (!q.length) return []+ return catalog+ .filter((t) => t.name !== TOOL_SEARCH)+ .map((t) => {+ const name = words(t.name)+ const desc = words(t.description)+ let score = 0+ for (const w of q) {+ if (name.some((n) => close(n, w))) score += 3+ else if (desc.some((d) => close(d, w))) score += 1+ }+ return { t, score }+ })+ .filter((s) => s.score > 0)+ .sort((a, b) => b.score - a.score || a.t.name.localeCompare(b.t.name))+}++/**+ * The tools of `catalog` that fit `query`, best first. A word in the name+ * counts three times as much as one in the description, and a hit has to+ * score more than half of the best one, so "make a video" does not bring+ * image_generate along on the word "make".+ */+export function searchTools(query: string, catalog: readonly MCPToolDefinition[], limit = TOOL_SEARCH_LIMIT): MCPToolDefinition[] {+ const scored = scoreTools(query, catalog)+ if (!scored.length) return []+ const floor = scored[0].score / 2+ return scored.filter((s) => s.score > floor).slice(0, limit).map((s) => s.t)+}++/**+ * One line per core tool for the compact profile. The first sentence of the+ * full description is not enough for these: shell_execute's is "THE+ * terminal.", file_read's drops the paging, todo_write's drops the rule that+ * makes it cheap. Every other tool gets its first sentence (`briefDescription`).+ */+export const CORE_BRIEFS: Readonly<Record<string, string>> = {+ todo_write: 'The task plan the user sees. Send the COMPLETE list each time, together with your next real tool call, never on its own.',+ web_search: 'Search the web: titles, URLs and short snippets. Read the best page with web_fetch before you answer.',+ web_fetch: 'Read one web page (full URL) as text.',+ file_read: 'Read a text file (path relative to the workspace). For a big file pass offset and limit.',+ file_write: 'Create a file or replace a WHOLE file. To change part of a file use file_edit.',+ file_edit: 'Change part of a file: replace old_string (copied exactly from file_read, unique) with new_string.',+ file_list: 'List a folder ("." is the workspace). recursive and pattern ("*.md") are optional.',+ file_search: 'Search file contents with a regex across a folder: file, line number and text of each match.',+ shell_execute: 'Run one shell command in the workspace (git, tests, scripts, mv, mkdir). Returns stdout, stderr and exit code.',+}++/** The line a compact run shows for a tool. */+export function briefFor(tool: { name: string; description: string }): string {+ return CORE_BRIEFS[tool.name] ?? briefDescription(tool.description)+}++/** The first sentence of a description, at most `max` characters. */+export function briefDescription(description: string, max = 160): string {+ const flat = description.replace(/\s+/g, ' ').trim()+ const first = flat.match(/^.+?[.!?](?=\s|$)/)?.[0] ?? flat+ return first.length <= max ? first : `${first.slice(0, max - 1).trimEnd()}…`+}++/**+ * Runs one search for a conversation and returns what the model reads.+ * `catalog` is everything this run may use (permissions applied), `offered`+ * the names already in the model's list.+ */+export function runToolSearch(+ convId: string | null | undefined,+ args: Record<string, unknown>,+ catalog: readonly MCPToolDefinition[],+ offered: ReadonlySet<string>,+): string {+ const query = typeof args.query === 'string' ? args.query : ''+ if (!query.trim()) return 'tool_search needs a `query`: describe in a few words what the tool should do.'+ const scored = scoreTools(query, catalog)+ if (!scored.length) return `No tool fits "${query}". Carry on with the tools you have, or tell the user what is missing.`+ // The best fit is already offered: say so instead of unlocking a weaker one.+ if (offered.has(scored[0].t.name)) {+ const there = scored.filter((s) => offered.has(s.t.name) && s.score === scored[0].score).map((s) => s.t.name)+ return `No other tool fits "${query}" better. Already in your list: ${there.join(', ')}. Use it.`+ }+ const floor = scored[0].score / 2+ const hits = scored.filter((s) => !offered.has(s.t.name) && s.score > floor).slice(0, TOOL_SEARCH_LIMIT).map((s) => s.t)+ unlockTools(convId, hits.map((t) => t.name))+ return `Added to your tool list for the next step:\n${hits.map((t) => `- ${t.name}: ${briefFor(t)}`).join('\n')}\nCall the one you need in your next step.`+}++/**+ * The tool list for one step of a run with a short list: the selection, plus+ * what this run unlocked, plus `tool_search` itself when the catalog holds+ * anything the list does not.+ */+export function withToolSearch<T extends { name: string }>(+ selected: T[],+ catalog: readonly T[],+ convId: string | null | undefined,+ searchDef: T,+): T[] {+ const have = new Set(selected.map((t) => t.name))+ const open = unlockedTools(convId)+ const extra = catalog.filter((t) => open.has(t.name) && !have.has(t.name))+ const list = [...selected, ...extra]+ const names = new Set(list.map((t) => t.name))+ const somethingLeft = catalog.some((t) => !names.has(t.name) && t.name !== TOOL_SEARCH)+ return somethingLeft && !names.has(TOOL_SEARCH) ? [...list, searchDef] : list+}diff --git a/src/types/settings.ts b/src/types/settings.tsindex 5db9878f..03932c79 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -185,6 +185,10 @@ export interface Settings {/** The agent loop guard (lib/agent-loop-guard.ts): steers and halts a run* that repeats itself. On unless switched off (C44, Discord 05.11.2026). */agentLoopGuard?: boolean+ /** Local models up to ~35B get a short tool list with one-line+ * descriptions plus tool_search (lib/agent-profile.ts, C59). On unless+ * switched off; Small-Model Mode still wins. */+ agentCompactAuto?: boolean/*** Dieselben zwei Schranken, aber fuer einen delegierten Sub-Agenten.*