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
perf(agent): the coding step carries 1664 tokens of catalog instead of 2422
Davide90c930e1376
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 23587c8a..3a19cbcb 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -2211,30 +2211,30 @@ button{-webkit-appearance:none;appearance:none}// same model behaviour follows us onto mobile. Tests in// src/api/__tests__/tool-description-parity.test.ts pin this parity.var AGENT_TOOLS = [- {name:'todo_write', description:'Write the plan for a multi-step task and keep it up to date. The list is shown to the user live, so it is how they see what you are doing and how far along you are. USE FIRST on any task that needs more than about three tool calls: write the whole plan before the first step. Then call it again after each step to flip that item to completed and the next one to in_progress. Send the COMPLETE list every time. It replaces the previous one, it does not merge. Exactly one item should be in_progress at a time. DO NOT use it for a single-step request, and NEVER mark an item completed before the work actually succeeded.',+ {name:'todo_write', description:'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. USE FIRST when a task needs more than about three tool calls, then send it again after each step. Send the COMPLETE list every time: it replaces the previous one, it does not merge.',parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},- {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. For the current date/time, trust the date line in the system prompt; do NOT web_search for it.',+ {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. Snippets are teasers, not answers: PREFER web_fetch on the promising URLs for the real content. DO NOT run more than 3 similar queries per turn, refine instead of re-searching.',parameters:[{name:'query',type:'string',description:'The search query string',required:true},{name:'maxResults',type:'number',description:'Maximum results to return (default: 5, max: 20)',required:false}]},- {name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars). Strips <script>, <style>, <nav>, <header>, <footer>, <aside>, <form> — returns main content only. PREFER this over web_search when you already know the target URL. NEVER call with localhost, private IPs (10.*, 192.168.*, 172.16-31.*), or file:// — they are refused. If response is empty or 4xx, try a different URL rather than retrying the same one.',+ {name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars), scripts, styles and page furniture stripped. PREFER this over web_search when you already know the target URL. NEVER call it with localhost, a private IP or file://, those are refused. On an empty or 4xx response try a different URL, not the same one again.',parameters:[{name:'url',type:'string',description:'Full URL including protocol (http:// or https://)',required:true},{name:'maxLength',type:'number',description:'Max chars to return (default: 24000)',required:false}]},- {name:'file_read', description:'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace (~/agent-workspace). Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit (number of lines) to read a window — the response names the window and the total line count, and tells you the offset for the next page. Very long whole-file reads get their middle truncated, so page large files. DO NOT re-read a file you just wrote with file_write; the write response already confirmed the save. For directory listings use file_list; for content search across many files use file_search.',+ {name:'file_read', description:'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace. Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit (number of lines): the response names the window, the total line count and the offset of the next page. A very long whole-file read gets its middle truncated, so page large files. DO NOT re-read a file you just wrote, the write response already confirmed it.',parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},{name:'offset',type:'number',description:'1-based line to start reading from (optional)',required:false},{name:'limit',type:'number',description:'Maximum number of lines to return (optional)',required:false}]},- {name:'file_write', description:'Write a WHOLE file. Use for CREATING a new file or fully replacing one. To change part of an EXISTING file, PREFER file_edit — it is far cheaper than resending the whole file and never truncates a large one. Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. PREFER absolute paths. Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',+ {name:'file_write', description:'Write a WHOLE file: use it to CREATE a new file or fully replace one, and PREFER file_edit to change part of an existing one. Creates parent directories if missing. OVERWRITES existing content, there is no append mode. PREFER absolute paths.',parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},{name:'content',type:'string',description:'The complete new content of the file',required:true}]},- {name:'file_list', description:'List directory contents. Returns entries with name, isDir, size, full path. Supports recursive=true for full tree and glob pattern ("*.ts", "**/*.py"). PREFER a specific pattern over recursive listing of large trees — recursing home / C:\\ is slow. For content search (grep), use file_search instead.',+ {name:'file_list', description:'List directory contents. Returns name, isDir, size and full path per entry. Supports recursive=true and a glob pattern ("*.ts", "**/*.py"). PREFER a specific pattern over recursing a whole home or drive, that is slow. For content search use file_search.',parameters:[{name:'path',type:'string',description:'Directory path to list',required:true},{name:'recursive',type:'boolean',description:'Recurse into subdirectories (default: false)',required:false},{name:'pattern',type:'string',description:'Glob pattern to filter results (e.g. "*.ts", "**/*.py")',required:false}]},- {name:'file_search', description:'Grep-style regex content search across files in a directory. Returns matching lines with file + line number. PREFER over file_read + manual scan when hunting for a symbol across many files. Use file_list first if you do not know the layout. Default max 50 results — narrow the pattern or path if you flood. Pattern uses Rust regex syntax, not PCRE.',+ {name:'file_search', description:'Grep-style regex content search across files in a directory. Returns matching lines with file and line number. PREFER it over file_read plus a manual scan when hunting a symbol across many files. Default max 50 results, narrow the pattern or path if you flood. Pattern is Rust regex syntax, not PCRE.',parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},{name:'pattern',type:'string',description:'Regex pattern to search for',required:true},{name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},- {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities. This is also how you open things on the desktop: files, folders, apps (the system prompt states the OS and the exact open command). Useful forms: `git status --porcelain=2 --branch` and a recognised test run (`npm test`, `npx vitest run`, `cargo test`, `pytest`) return a parsed summary; `git log --oneline -n 20`; `git diff`; `git add -A && git commit -m "msg"`; `git push`; `gh pr create --title "t" --body "b"`. Feed a script via `stdin` instead of quoting it: set command to `python3 -` or `bash -s` and put the source in `stdin` (fresh process each call, no REPL state). Long-running work: set `background: true` to get a task id back immediately; follow it by calling again with `task: "status"` and `task_id` (or `task: "list"` / `task: "kill"`). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`. `git commit --no-verify` is refused. NEVER permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). Default timeout 120 s (recognised test runs get 300 s); set higher only for known long builds.',+ {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. A recognised test run and the common git commands come back as a parsed summary. Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. `--no-verify` is refused, and NEVER delete permanently without confirmation. Default timeout 120 s, test runs 300 s.',parameters:[{name:'command',type:'string',description:'The full command to execute. Omit only for task actions.',required:false},{name:'cwd',type:'string',description:'Working directory (optional, absolute preferred)',required:false},{name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},@@ -2245,7 +2245,7 @@ button{-webkit-appearance:none;appearance:none}{name:'task_id',type:'string',description:'Task id for task "status" or "kill".',required:false}]},{name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',parameters:[]},- {name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',+ {name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune through the optional `settings` object; a value beyond the model\'s real limit is REJECTED with the actual limit, never silently changed.',parameters:[{name:'prompt',type:'string',description:'Positive text description of the desired image',required:true},{name:'negativePrompt',type:'string',description:'Things to avoid (blurry, deformed, etc.)',required:false},{name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.tsnew file mode 100644index 00000000..9e7fc1e6--- /dev/null+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts@@ -0,0 +1,187 @@+/**+ * A6 prompt diet: what the tool catalog costs on the wire, measured.+ *+ * The 2.6.6 tool merge (e64654cf) reported 2.887 tokens for the coding-mode+ * catalog, measured on the wire against DeepSeek V4 Flash. That number lived+ * only in a commit message, so the next description edit could give it all back+ * without anything going red. This file is the guard.+ *+ * Two halves, on purpose:+ *+ * OFFLINE (always runs) pins the serialized SIZE of exactly what useCodex+ * puts into the request: the coding categories, permission-filtered, run+ * through gateCreateTools with a plain refactor instruction, serialized in+ * the OpenAI function shape. Characters, not tokens, because a byte count is+ * the only thing a machine without a model on it can reproduce.+ *+ * LIVE (LIVE_TOKENS=1) counts real tokens through a real BPE. It posts the+ * same string to a local Ollama with `raw: true` (no chat template, so+ * prompt_eval_count is the tokenizer's verdict on our bytes and nothing+ * else). Default model is qwen2.5:0.5b: the smallest thing on the box that+ * carries the 151k Qwen vocabulary the cloud coding models use.+ *+ * LIVE_TOKENS=1 npx vitest run src/api/mcp/__tests__/tool-catalog-tokens.test.ts+ * LIVE_TOKENS=1 LU_TOKENIZER_MODEL=qwen2.5-coder:7b npx vitest run ...+ *+ * The ceilings below are the measured numbers plus a small margin, so a+ * description that grows back fails here first.+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { toolRegistry, DEFAULT_PERMISSIONS } from '../index'+import { gateCreateTools } from '../../../lib/tool-selection'++/** Mirrors CODEX_CATEGORIES in useCodex.ts (same reason as the sibling tests). */+const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video', 'workflow']++/** The instruction a plain coding step carries. No creative cue, no PR, no fan-out. */+const PLAIN_CODING_ASK = 'fix the failing test in parser.ts and run the suite'++const codingCatalog = () =>+ toolRegistry+ .getAvailableTools(DEFAULT_PERMISSIONS)+ .filter((t) => CODEX_CATEGORIES.includes(t.category))++/** Exactly the object useCodex builds for the request (`tools:` on the wire). */+function wireTools(defs: { name: string; description: string; inputSchema: unknown }[]) {+ return defs.map((t) => ({+ type: 'function' as const,+ function: { name: t.name, description: t.description, parameters: t.inputSchema },+ }))+}++const codingWire = () => JSON.stringify(wireTools(gateCreateTools(codingCatalog(), PLAIN_CODING_ASK)))+const fullWire = () => JSON.stringify(wireTools(codingCatalog()))++/**+ * Measured 2026-08-21 with qwen2.5:0.5b (Qwen 151k vocabulary) through the+ * live half below, on the same tree before and after the A6 diet:+ *+ * coding step, gated before 10.585 chars / 2.422 tokens+ * after 7.418 chars / 1.664 tokens (-31,3 %)+ * whole coding catalog before 18.851 chars / 4.296 tokens+ * after 16.637 chars / 3.745 tokens (-12,8 %)+ *+ * ~4,4 chars per token on this text, stable across all four measurements, so+ * the char ceilings and the token ceilings move together.+ *+ * The 2.887 in commit e64654cf is NOT this scale: it was read off the wire+ * against DeepSeek V4 Flash, whose vocabulary is not Qwen's. Same tree, same+ * gate, this harness said 2.422 for that build, so the two scales sit about+ * 1,19 apart and the after-number is worth ~1.980 in the old units.+ *+ * The ceilings carry ~4 percent of headroom for a wording fix; a new paragraph+ * blows through them.+ */+const CODING_CHAR_CEILING = 7600+const CODING_TOKEN_CEILING = 1730+const FULL_CHAR_CEILING = 17000+const FULL_TOKEN_CEILING = 3880++describe('the coding step carries a catalog the diet actually shrank', () => {+ it('the gate really is what a plain coding turn gets', () => {+ // A guard on the guard: if the gate stopped removing the create tools the+ // ceilings below would be measuring a different catalog.+ const gated = gateCreateTools(codingCatalog(), PLAIN_CODING_ASK).map((t) => t.name)+ expect(gated).not.toContain('image_generate')+ expect(gated).not.toContain('video_generate')+ expect(gated).not.toContain('run_workflow')+ expect(gated).toContain('shell_execute')+ expect(gated).toContain('file_edit')+ expect(gated).toContain('todo_write')+ })++ it('pr_resume and delegate_task no longer ride along on a refactor', () => {+ const gated = gateCreateTools(codingCatalog(), PLAIN_CODING_ASK).map((t) => t.name)+ expect(gated).not.toContain('pr_resume')+ expect(gated).not.toContain('delegate_task')+ })++ it('the serialized coding catalog stays under its ceiling', () => {+ expect(codingWire().length).toBeLessThanOrEqual(CODING_CHAR_CEILING)+ })++ it('the ungated coding catalog stays under its ceiling too', () => {+ // The creative turn pays this one, and it is where the shared media+ // settings schema shows up.+ expect(fullWire().length).toBeLessThanOrEqual(FULL_CHAR_CEILING)+ })++ it('the mobile catalog went on the same diet, or it drifts from here', () => {+ // The relay re-declares AGENT_TOOLS inline. tool-description-parity pins+ // them word for word; this one names the cut phrases directly, so a revert+ // on either side is a red test with the reason in it.+ const relay = readFileSync(+ resolve(__dirname, '..', '..', '..', '..', 'src-tauri', 'src', 'commands', 'remote.rs'),+ 'utf8',+ )+ const start = relay.indexOf('var AGENT_TOOLS = [')+ expect(start, 'mobile AGENT_TOOLS not found').toBeGreaterThan(-1)+ const agentTools = relay.slice(start, relay.indexOf('];', start))+ expect(agentTools).not.toMatch(/git add -A && git commit/)+ expect(agentTools).not.toMatch(/gh pr create --title/)+ expect(agentTools).not.toMatch(/sideEffectKey/)+ expect(agentTools).not.toMatch(/Exactly one item should be in_progress/)+ })++ it('no tool description carries a paragraph the system prompt already states', () => {+ // The three sentences the diet moved out of the catalog and left to the+ // prompts (useCodex CODEX_SYSTEM_PROMPT, useAgentChat buildAgentSystemPrompt),+ // pinned by their most distinctive words so they cannot creep back.+ const all = toolRegistry.getAll().map((t) => t.description).join('\n')+ expect(all).not.toMatch(/Exactly one item should be in_progress/i)+ expect(all).not.toMatch(/NEVER mark an item completed/i)+ expect(all).not.toMatch(/sideEffectKey/i)+ expect(all).not.toMatch(/git add -A && git commit/i)+ expect(all).not.toMatch(/gh pr create --title/i)+ })+})++// ── the live half ────────────────────────────────────────────────++const LIVE = process.env.LIVE_TOKENS === '1'+const TOKENIZER_MODEL = process.env.LU_TOKENIZER_MODEL || 'qwen2.5:0.5b'+const OLLAMA = process.env.LU_OLLAMA_URL || 'http://127.0.0.1:11434'++/**+ * Token count of `text` from a real tokenizer. `raw: true` skips the chat+ * template, so prompt_eval_count counts our bytes and nothing else; num_predict+ * has to be 1 rather than 0 because Ollama omits the eval counters when it+ * generates nothing at all.+ */+async function countTokens(text: string): Promise<number> {+ const res = await fetch(`${OLLAMA}/api/generate`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ model: TOKENIZER_MODEL,+ prompt: text,+ raw: true,+ stream: false,+ options: { num_predict: 1, num_ctx: 32768, temperature: 0 },+ }),+ })+ if (!res.ok) throw new Error(`tokenizer ${TOKENIZER_MODEL} said ${res.status}`)+ const body = (await res.json()) as { prompt_eval_count?: number }+ if (typeof body.prompt_eval_count !== 'number') throw new Error('no prompt_eval_count in response')+ return body.prompt_eval_count+}++describe.runIf(LIVE)('the same catalog through a real tokenizer', () => {+ it('a plain coding step stays under the token ceiling', async () => {+ const wire = codingWire()+ const tokens = await countTokens(wire)+ // eslint-disable-next-line no-console+ console.log(`coding step: ${wire.length} chars, ${tokens} tokens (${TOKENIZER_MODEL})`)+ expect(tokens).toBeLessThanOrEqual(CODING_TOKEN_CEILING)+ }, 300000)++ it('the ungated coding catalog stays under its token ceiling', async () => {+ const wire = fullWire()+ const tokens = await countTokens(wire)+ // eslint-disable-next-line no-console+ console.log(`full catalog: ${wire.length} chars, ${tokens} tokens (${TOKENIZER_MODEL})`)+ expect(tokens).toBeLessThanOrEqual(FULL_TOKEN_CEILING)+ }, 300000)+})diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 6d0ac6fa..cad44ea2 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -1,6 +1,6 @@// Built-in tool definitions + executors — replaces hardcoded AGENT_TOOL_DEFS-import type { MCPToolDefinition } from './types'+import type { JSONSchemaProp, MCPToolDefinition } from './types'import type { ToolRegistry } from './tool-registry'import { backendCall, fetchExternal } from '../backend'import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'@@ -40,6 +40,41 @@ function chatCtx(): { chatId?: string; workingDirectory?: string } {// ── Tool Definitions ────────────────────────────────────────────+/**+ * The `settings` sub-schema image_generate and video_generate share (A6).+ *+ * The two carried byte-identical copies of eight properties plus the same+ * paragraph of prose about limits, and every creative turn paid for both. Two+ * copies also drift: video's sampler and width already explained themselves+ * differently from image's for no reason a model can use. One definition, one+ * wording, each tool adding only what is genuinely its own.+ */+const MEDIA_SETTINGS_HINT =+ 'Optional fine-tuning. Set ONLY what the user asked for, omit the rest. '+ + 'A value beyond the installed model\'s real limit is rejected with the actual limit. '+ + 'A flat top-level argument wins over the same key here.'++const SHARED_MEDIA_SETTINGS: Record<string, JSONSchemaProp> = {+ steps: { type: 'number', description: 'Sampling steps.' },+ cfg: { type: 'number', description: 'CFG / guidance scale.' },+ sampler: { type: 'string', description: 'Sampler name, must be one this model supports.' },+ scheduler: { type: 'string', description: 'Scheduler name, must be one this model supports.' },+ seed: { type: 'number', description: 'Seed; omit or -1 for random.' },+ width: { type: 'number', description: 'Output width in px.' },+ height: { type: 'number', description: 'Output height in px.' },+ negativePrompt: { type: 'string', description: 'Things to avoid.' },+}++/** The shared eight plus the keys only one of the two pipelines understands. */+function mediaSettingsSchema(own: Record<string, JSONSchemaProp>): JSONSchemaProp {+ return {+ type: 'object',+ description: MEDIA_SETTINGS_HINT,+ additionalProperties: true,+ properties: { ...SHARED_MEDIA_SETTINGS, ...own },+ }+}+// tool-classification.test.ts reads the names out of this array to assert that// every one of them is classified as mutating or read-only. It parses the file// rather than importing it, because importing pulls in the tool-registry cycle.@@ -48,11 +83,9 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'todo_write',description:- 'Write the plan for a multi-step task and keep it up to date. The list is shown to the user live, so it is how they see what you are doing and how far along you are. '- + 'USE FIRST on any task that needs more than about three tool calls: write the whole plan before the first step. '- + 'Then call it again after each step to flip that item to completed and the next one to in_progress. '- + 'Send the COMPLETE list every time. It replaces the previous one, it does not merge. Exactly one item should be in_progress at a time. '- + 'DO NOT use it for a single-step request, and NEVER mark an item completed before the work actually succeeded.',+ 'Write and update the plan for a multi-step task. The list is shown to the user live, so it is how they follow a long run. '+ + 'USE FIRST when a task needs more than about three tool calls, then send it again after each step. '+ + 'Send the COMPLETE list every time: it replaces the previous one, it does not merge.',inputSchema: {type: 'object',properties: {@@ -83,9 +116,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [name: 'web_search',description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. '- + 'PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. '- + 'DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. '- + 'For the current date/time, trust the date line in the system prompt; do NOT web_search for it.',+ + 'Snippets are teasers, not answers: PREFER web_fetch on the promising URLs for the real content. '+ + 'DO NOT run more than 3 similar queries per turn, refine instead of re-searching.',inputSchema: {type: 'object',properties: {@@ -100,11 +132,10 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'web_fetch',description:- 'Fetch a single URL and return its readable text (up to ~24 000 chars). '- + 'Strips <script>, <style>, <nav>, <header>, <footer>, <aside>, <form> — returns main content only. '+ 'Fetch a single URL and return its readable text (up to ~24 000 chars), scripts, styles and page furniture stripped. '+ 'PREFER this over web_search when you already know the target URL. '- + 'NEVER call with localhost, private IPs (10.*, 192.168.*, 172.16-31.*), or file:// — they are refused. '- + 'If response is empty or 4xx, try a different URL rather than retrying the same one.',+ + 'NEVER call it with localhost, a private IP or file://, those are refused. '+ + 'On an empty or 4xx response try a different URL, not the same one again.',inputSchema: {type: 'object',properties: {@@ -121,12 +152,11 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'file_read',description:- 'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace (~/agent-workspace). '+ 'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace. '+ 'Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit '- + '(number of lines) to read a window — the response names the window and the total line count, and tells you '- + 'the offset for the next page. Very long whole-file reads get their middle truncated, so page large files. '- + 'DO NOT re-read a file you just wrote with file_write; the write response already confirmed the save. '- + 'For directory listings use file_list; for content search across many files use file_search.',+ + '(number of lines): the response names the window, the total line count and the offset of the next page. '+ + 'A very long whole-file read gets its middle truncated, so page large files. '+ + 'DO NOT re-read a file you just wrote, the write response already confirmed it.',inputSchema: {type: 'object',properties: {@@ -142,11 +172,9 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'file_write',description:- 'Write a WHOLE file. Use for CREATING a new file or fully replacing one. '- + 'To change part of an EXISTING file, PREFER file_edit — it is far cheaper than resending the whole file and never truncates a large one. '- + 'Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. '- + 'PREFER absolute paths. '- + 'Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',+ 'Write a WHOLE file: use it to CREATE a new file or fully replace one, and PREFER file_edit to change part of an existing one. '+ + 'Creates parent directories if missing. OVERWRITES existing content, there is no append mode. '+ + 'PREFER absolute paths.',inputSchema: {type: 'object',properties: {@@ -161,11 +189,9 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'file_edit',description:- 'Make a SURGICAL edit to an existing file: replace old_string with new_string. '- + 'PREFER this over file_write for changing an existing file — you send only the lines that change, so it is far cheaper and never truncates a large file. '- + 'old_string must match EXACTLY ONCE: copy the exact text (including indentation) from a prior file_read and include enough surrounding lines to be unique. '- + 'It FAILS with no change if old_string is missing or matches more than one place — then read the file and retry with more context. '- + 'Use file_write instead to create a new file or fully rewrite one.',+ 'Make a SURGICAL edit to an existing file: replace old_string with new_string. PREFER it over file_write for any change to a file that exists. '+ + 'old_string must match EXACTLY ONCE: copy the exact text including indentation from a prior file_read and take enough surrounding lines to be unique. '+ + 'It FAILS with no change when old_string is missing or matches twice; then read the file and retry with more context.',inputSchema: {type: 'object',properties: {@@ -181,10 +207,10 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'file_list',description:- 'List directory contents. Returns entries with name, isDir, size, full path. '- + 'Supports recursive=true for full tree and glob pattern ("*.ts", "**/*.py"). '- + 'PREFER a specific pattern over recursive listing of large trees — recursing home / C:\\ is slow. '- + 'For content search (grep), use file_search instead.',+ 'List directory contents. Returns name, isDir, size and full path per entry. '+ + 'Supports recursive=true and a glob pattern ("*.ts", "**/*.py"). '+ + 'PREFER a specific pattern over recursing a whole home or drive, that is slow. '+ + 'For content search use file_search.',inputSchema: {type: 'object',properties: {@@ -200,11 +226,10 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [{name: 'file_search',description:- 'Grep-style regex content search across files in a directory. Returns matching lines with file + line number. '- + 'PREFER over file_read + manual scan when hunting for a symbol across many files. '- + 'Use file_list first if you do not know the layout. '- + 'Default max 50 results — narrow the pattern or path if you flood. '- + 'Pattern uses Rust regex syntax, not PCRE.',+ 'Grep-style regex content search across files in a directory. Returns matching lines with file and line number. '+ + 'PREFER it over file_read plus a manual scan when hunting a symbol across many files. '+ + 'Default max 50 results, narrow the pattern or path if you flood. '+ + 'Pattern is Rust regex syntax, not PCRE.',inputSchema: {type: 'object',properties: {@@ -223,13 +248,13 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [name: 'shell_execute',description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. '- + 'Everything runs here: git, tests, package managers, gh, python, platform utilities. This is also how you open things on the desktop: files, folders, apps (the system prompt states the OS and the exact open command). '- + 'Useful forms: `git status --porcelain=2 --branch` and a recognised test run (`npm test`, `npx vitest run`, `cargo test`, `pytest`) return a parsed summary; `git log --oneline -n 20`; `git diff`; `git add -A && git commit -m "msg"`; `git push`; `gh pr create --title "t" --body "b"`. '- + 'Feed a script via `stdin` instead of quoting it: set command to `python3 -` or `bash -s` and put the source in `stdin` (fresh process each call, no REPL state). '- + 'Long-running work: set `background: true` to get a task id back immediately; follow it by calling again with `task: "status"` and `task_id` (or `task: "list"` / `task: "kill"`). '- + 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`. '- + '`git commit --no-verify` is refused. NEVER permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). '- + 'Default timeout 120 s (recognised test runs get 300 s); set higher only for known long builds.',+ + 'Everything runs here: git, tests, package managers, gh, python, platform utilities, and opening files, folders or apps. '+ + 'A recognised test run and the common git commands come back as a parsed summary. '+ + 'Feed a script through `stdin` instead of quoting it: set command to `python3 -` or `bash -s` (fresh process each call, no REPL state). '+ + 'For long work set `background: true` to get a task id back at once, then call again with `task: "status"` and `task_id` (or "list" / "kill"). '+ + 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`, file_search over `grep`. '+ + '`--no-verify` is refused, and NEVER delete permanently without confirmation. '+ + 'Default timeout 120 s, test runs 300 s.',inputSchema: {type: 'object',properties: {@@ -300,7 +325,7 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [+ 'First installed image model is auto-selected (or pass `model`). '+ 'EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. '+ 'Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. '- + 'Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',+ + 'Fine-tune through the optional `settings` object; a value beyond the model\'s real limit is REJECTED with the actual limit, never silently changed.',inputSchema: {type: 'object',properties: {@@ -309,25 +334,12 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [model: { type: 'string', description: 'Optional image model filename to use. Omit to auto-select the first installed image model.' },inputImage: { type: 'string', description: 'Optional. Filename of a previously generated image (from an earlier image_generate result) to use as the base for image-to-image. Omit for text-to-image.' },denoise: { type: 'number', description: 'Image-to-image strength 0.05–1.0 (default 0.6). Lower keeps more of the input image, higher follows the prompt more. Only used together with inputImage.' },- settings: {- type: 'object',- description: 'Optional fine-tuning. Set ONLY what the user explicitly asked for; omit the rest (the model\'s own defaults apply). Any value beyond the installed model\'s real limit is rejected with the actual limit. Flat top-level args (above) win over the same key here.',- additionalProperties: true,- properties: {- steps: { type: 'number', description: 'Sampling steps.' },- cfg: { type: 'number', description: 'CFG / guidance scale.' },- sampler: { type: 'string', description: 'Sampler name — must be one this model supports, else rejected.' },- scheduler: { type: 'string', description: 'Scheduler name — must be one this model supports, else rejected.' },- seed: { type: 'number', description: 'Seed; omit or -1 for random.' },- width: { type: 'number', description: 'Output width in px.' },- height: { type: 'number', description: 'Output height in px.' },- negativePrompt: { type: 'string', description: 'Things to avoid.' },- denoise: { type: 'number', description: 'Image-to-image strength 0.05–1.0 (only with inputImage).' },- lora: { type: ['string', 'array'], items: { type: 'string' }, description: 'LoRA filename to apply — or an ARRAY of filenames to stack multiple LoRAs (chained in order, like stacking LoraLoader nodes). Names are matched against the installed LoRAs (extension optional); an unknown name is rejected with the installed list.' },- loraStrength: { type: ['number', 'array'], items: { type: 'number' }, description: 'LoRA strength (~0–2). Single number = applied to every LoRA; array = one strength per LoRA in the same order.' },- vae: { type: 'string', description: 'Override VAE filename.' },- },- },+ settings: mediaSettingsSchema({+ denoise: { type: 'number', description: 'Image-to-image strength 0.05 to 1.0 (only with inputImage).' },+ lora: { type: ['string', 'array'], items: { type: 'string' }, description: 'LoRA filename, or an ARRAY of filenames to stack several (chained in order). Matched against the installed LoRAs, extension optional; an unknown name is rejected with the installed list.' },+ loraStrength: { type: ['number', 'array'], items: { type: 'number' }, description: 'LoRA strength (~0 to 2). One number applies to every LoRA; an array gives one strength per LoRA in the same order.' },+ vae: { type: 'string', description: 'Override VAE filename.' },+ }),},required: ['prompt'],},@@ -343,7 +355,7 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [+ 'Pass `inputImage` (a filename from an earlier image_generate result) to animate a still image — image-to-video, which auto-selects an installed I2V model such as SVD; omit it for text-to-video. First installed video model is auto-selected (or pass `model`). '+ 'Write ONE clear prompt and call this ONCE per turn — video generation is slow and ComfyUI queues parallel calls rather than speeding up. '+ 'EXPECT A PAUSE: LU will briefly unload the chat model from VRAM to fit the (large) video model, then reload it after — typically a 30-90s swap, longer on a cold ComfyUI start. This prevents out-of-memory errors; your conversation is preserved across the swap. '- + 'Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed); set ONLY what the user asked for. A value beyond the installed model\'s real limit (e.g. more frames than the model can make) is REJECTED with the actual limit so you can retry lower — values are never silently changed.',+ + 'Fine-tune through the optional `settings` object; a value beyond the model\'s real limit is REJECTED with the actual limit, never silently changed.',inputSchema: {type: 'object',properties: {@@ -354,24 +366,11 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [frames: { type: 'number', description: 'Advanced: exact frame count (rejected if beyond the model max; e.g. ~81 for Wan, ~25 for SVD). Prefer `seconds`. Omit for the model default.' },fps: { type: 'number', description: 'Frames per second of the output clip (e.g. 16). Omit for the model default.' },inputImage: { type: 'string', description: 'Optional. Filename of a previously generated image to animate (image-to-video). Requires an installed I2V model such as SVD. Omit for text-to-video.' },- settings: {- type: 'object',- description: 'Optional fine-tuning. Set ONLY what the user explicitly asked for; omit the rest (the model\'s own defaults apply). Any value beyond the installed model\'s real limit is rejected with the actual limit. Flat top-level args (above) win over the same key here.',- additionalProperties: true,- properties: {- seconds: { type: 'number', description: 'Clip length in seconds (preferred length control).' },- frames: { type: 'number', description: 'Exact frame count — rejected if beyond the model max.' },- fps: { type: 'number', description: 'Frames per second of the output clip.' },- steps: { type: 'number', description: 'Sampling steps.' },- cfg: { type: 'number', description: 'CFG / guidance scale.' },- sampler: { type: 'string', description: 'Sampler name — must be one this model supports (ignored by FramePack, which uses a fixed sampler).' },- scheduler: { type: 'string', description: 'Scheduler name — must be one this model supports.' },- seed: { type: 'number', description: 'Seed; omit or -1 for random.' },- width: { type: 'number', description: 'Output width in px (snapped to the video grid).' },- height: { type: 'number', description: 'Output height in px (snapped to the video grid).' },- negativePrompt: { type: 'string', description: 'Things to avoid.' },- },- },+ settings: mediaSettingsSchema({+ seconds: { type: 'number', description: 'Clip length in seconds (preferred length control).' },+ frames: { type: 'number', description: 'Exact frame count, rejected if beyond the model max.' },+ fps: { type: 'number', description: 'Frames per second of the output clip.' },+ }),},// prompt intentionally NOT required: image-to-video can animate a still// without an explicit text prompt, and small models sometimes omit it —diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.tsindex 1ae15977..b013f004 100644--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts@@ -30,7 +30,7 @@ import { describe, it, expect } from 'vitest'import { readFileSync } from 'node:fs'import { fileURLToPath } from 'node:url'import { dirname, resolve } from 'node:path'-import { gateCreateTools, wantsMediaTools, CREATE_TOOLS } from '../../lib/tool-selection'+import { gateCreateTools, wantsMediaTools, CREATE_TOOLS, GATE_OPENING_TOOLS, isGatedTool } from '../../lib/tool-selection'import { toolRegistry, DEFAULT_PERMISSIONS } from '../../api/mcp'const src = readFileSync(@@ -61,20 +61,32 @@ describe('a plain coding turn does not carry the generators', () => {expect(out).toContain('todo_write')})- it('removes exactly three tools from the real coding catalog and nothing else', () => {+ it('removes exactly the gated tools from the real coding catalog and nothing else', () => {+ // A6 widened the gate from the three generators to five: pr_resume and+ // delegate_task shipped a schema on every step of every run that never+ // mentions a PR or a fan-out.const before = names(codingCatalog())const after = names(gateCreateTools(codingCatalog(), 'fix the failing test in parser.ts'))- expect(before.length - after.length).toBe(3)- expect(before.filter((n) => !after.includes(n)).sort()).toEqual([...CREATE_TOOLS].sort())+ expect(before.length - after.length).toBe(5)+ expect(before.filter((n) => !after.includes(n)).sort()).toEqual([...GATE_OPENING_TOOLS].sort())})- it('leaves delegate_task alone, which shares the workflow category', () => {+ it('still gates per tool, not by category', () => {// The naive version of this gate filters by category. delegate_task is// category 'workflow' (sub-agent.ts) and joined the Code tab in audit B11- // precisely because it was unreachable; a category filter would take the- // sub-agent fan-out out again by accident.- const out = names(gateCreateTools(codingCatalog(), 'refactor the auth guard'))+ // precisely because it was unreachable; a category filter would take+ // run_workflow out with it on a delegate ask, and vice versa.+ const out = names(gateCreateTools(codingCatalog(), 'split the work and fan out over the four files'))expect(out).toContain('delegate_task')+ expect(out).not.toContain('run_workflow')+ expect(out).not.toContain('image_generate')+ })++ it('a PR ask brings pr_resume back and nothing else', () => {+ const out = names(gateCreateTools(codingCatalog(), 'continue the pull request from yesterday'))+ expect(out).toContain('pr_resume')+ expect(out).not.toContain('delegate_task')+ expect(out).not.toContain('image_generate')})})@@ -192,11 +204,37 @@ describe('a run that discovers halfway through that it needs a picture', () => {})it('useCodex flips it on the call itself, not on the offered list', () => {- expect(src).toMatch(/if \(CREATE_TOOLS\.includes\(name\)\) createGateOpened = true/)+ // A6 leaves the callsite shape alone and only widens the predicate; the+ // patch that turns CREATE_TOOLS into isGatedTool is a one-liner, so this+ // accepts either spelling and still fails if the flip disappears.+ expect(src).toMatch(/if \((?:CREATE_TOOLS\.includes\(name\)|isGatedTool\(name\))\) createGateOpened = true/)// Declared per run, so one run's discovery does not leak into the next.expect(src).toMatch(/let createGateOpened = false/)})+ it('the self-heal covers the two tools A6 gated, by name and run-wide', () => {+ // Same hole, same cure: a run that turns out to be a PR after all, or that+ // decides at step six to fan out, must get the schema back rather than+ // calling blind for the remaining twenty steps.+ const defs = [{ name: 'file_read' }, { name: 'pr_resume' }, { name: 'delegate_task' }]+ const ask = 'clean up the parser'+ expect(gateCreateTools(defs, ask).map((d) => d.name)).toEqual(['file_read'])+ // Per-name reopening: only the tool that actually ran comes back.+ expect(gateCreateTools(defs, ask, ['pr_resume']).map((d) => d.name)).toEqual(['file_read', 'pr_resume'])+ // The run-wide boolean the current callsite passes opens everything.+ expect(gateCreateTools(defs, ask, true).map((d) => d.name)).toEqual(+ ['file_read', 'pr_resume', 'delegate_task'],+ )+ })++ it('isGatedTool names exactly the gated five, and nothing that always ships', () => {+ for (const n of [...CREATE_TOOLS, 'pr_resume', 'delegate_task']) expect(isGatedTool(n), n).toBe(true)+ for (const n of ['file_read', 'file_edit', 'shell_execute', 'todo_write', 'web_search']) {+ expect(isGatedTool(n), n).toBe(false)+ }+ expect([...GATE_OPENING_TOOLS].sort()).toEqual([...CREATE_TOOLS, 'pr_resume', 'delegate_task'].sort())+ })+it('a closed gate still tells the model the hatch is there', () => {expect(src).toContain('const CODEX_ASSET_HINT')expect(src).toContain('They are not in your tool list until you do, and the call still works.')diff --git a/src/lib/__tests__/host-platform.test.ts b/src/lib/__tests__/host-platform.test.tsindex 69dc708c..e8a3b15e 100644--- a/src/lib/__tests__/host-platform.test.ts+++ b/src/lib/__tests__/host-platform.test.ts@@ -105,8 +105,11 @@ describe('the tools really are gone', () => {})it('shell_execute is the documented way to open something', () => {+ // The A6 diet shortened the sentence; what has to survive is that the+ // description still names opening files/folders/apps as shell work, so+ // nobody re-adds a tool for it.const tools = read('api', 'mcp', 'builtin-tools.ts')- expect(tools).toMatch(/This is also how you open things on the desktop/)+ expect(tools).toMatch(/open(ing)? (things on the desktop|files, folders or apps)/)})it('the agent prompt states the platform instead of spending a call on it', () => {diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.tsindex 2a1af4cf..f8202762 100644--- a/src/lib/tool-selection.ts+++ b/src/lib/tool-selection.ts@@ -40,6 +40,20 @@ const MEDIA_KEYWORDS = []const WORKFLOW_KEYWORDS = ['workflow', 'run workflow', 'automate']+// A6: the two remaining ride-alongs. pr_resume only ever fires on a PR link or+// a "continue this PR", delegate_task only on an explicit fan-out, and both+// carry a schema on every step of every coding run that never asks for either.+// Same words the TOOL_GROUPS router already uses, so the local and the cloud+// path answer the question identically.+const PR_KEYWORDS = [+ 'pull request', 'pull-request', 'open a pr', 'create a pr', 'the pr', 'this pr',+ 'github', 'gh pr', '/resume', 'pick up review', '/pull/',+]+const DELEGATE_KEYWORDS = [+ 'delegate', 'sub-agent', 'subagent', 'sub agent', 'fan out', 'fan-out',+ 'in parallel', 'parallelize', 'parallelise', 'split the work',+]+/*** The three tools that draw, film and automate. Everything else in the coding* catalog earns its place on every turn; these three cost 1.963 of the 6.186@@ -48,6 +62,33 @@ const WORKFLOW_KEYWORDS = ['workflow', 'run workflow', 'automate']*/export const CREATE_TOOLS = ['image_generate', 'video_generate', 'run_workflow']+/**+ * Every keyword-gated tool and the words that open its gate (A6).+ *+ * CREATE_TOOLS stays its own exported list because the Codex asset line keys+ * off exactly those three; this map is the superset the filter walks.+ */+const GATE_KEYWORDS: Record<string, readonly string[]> = {+ image_generate: MEDIA_KEYWORDS,+ video_generate: MEDIA_KEYWORDS,+ run_workflow: WORKFLOW_KEYWORDS,+ pr_resume: PR_KEYWORDS,+ delegate_task: DELEGATE_KEYWORDS,+}++/**+ * The names whose first real call must reopen the gate for the rest of the run+ * (the createGateOpened self-heal). A run that discovers at step six that it+ * needs a sub-agent, or that the task is a PR after all, gets the schema back+ * from the next step instead of calling blind for the remaining twenty.+ */+export const GATE_OPENING_TOOLS: readonly string[] = Object.keys(GATE_KEYWORDS)++/** True when this tool only ships when the turn asked for it. */+export function isGatedTool(name: string): boolean {+ return name in GATE_KEYWORDS+}+const TOOL_GROUPS: ToolGroup[] = [{// Web search intents. Only EXPLICIT web cues route here. Bare 'search',@@ -254,16 +295,19 @@ export function selectRelevantTools(export function gateCreateTools<T extends { name: string }>(defs: T[],userMessage: string,- opened = false,+ opened: boolean | Iterable<string> = false,): T[] {- if (opened) return defs+ if (opened === true) return defs+ // A caller that tracks WHICH tool reopened the gate may pass the names; the+ // boolean form stays the run-wide "everything is open again" it always was.+ const reopened = opened === false ? null : new Set(opened)const msg = userMessage.toLowerCase()- const wantsMedia = MEDIA_KEYWORDS.some((k) => msg.includes(k))- const wantsFlow = WORKFLOW_KEYWORDS.some((k) => msg.includes(k))return defs.filter((t) => {- if (!CREATE_TOOLS.includes(t.name)) return true+ const words = GATE_KEYWORDS[t.name]+ if (!words) return true+ if (reopened?.has(t.name)) return trueif (msg.includes(t.name)) return true- return t.name === 'run_workflow' ? wantsFlow : wantsMedia+ return words.some((k) => msg.includes(k))})}