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
fix(agent): what the bench found in the first after-run (C59)
purplec919197a9b34
diff --git a/dev-server/__tests__/dev-bank-wie-die-app.test.ts b/dev-server/__tests__/dev-bank-wie-die-app.test.tsnew file mode 100644index 00000000..dde888f2--- /dev/null+++ b/dev-server/__tests__/dev-bank-wie-die-app.test.ts@@ -0,0 +1,75 @@+/**+ * C59: two places where the browser dev server answered differently from the+ * app, found by the agent bench (it runs against this server).+ *+ * 1. fs-read of a missing file answered 200 with an `error` field, and+ * file_read turned that into an empty text. Rust's fs_read returns an+ * error. A 9B took the missing file for an empty one, made up numbers and+ * wrote them into it.+ * 2. shell-execute ran in the Vite process folder (the repo) when the model+ * sent no cwd. Rust runs in the workspace, and a relative cwd inside it.+ *+ * Run: npx vitest run dev-server/__tests__/dev-bank-wie-die-app.test.ts+ */+import { afterAll, describe, expect, it } from 'vitest'+import { mkdirSync, realpathSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { registerFsRoutes } from '../fs-routes'+import { devShellCwd } from '../exec-routes'+import { AGENT_WORKSPACE_DIR } from '../../src/lib/app-identity'+import { routeHolen } from './echte-anfrage'+import { anfrageImHeim, arbeitsordnerIn, frischesHeim, kulisseAufraeumen } from './kaefig-kulisse'++afterAll(kulisseAufraeumen)++function lesen(koerper: Record<string, unknown>, heim: string) {+ return anfrageImHeim(routeHolen(registerFsRoutes, '/local-api/fs-read'), heim, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(koerper),+ })+}++describe('fs-read like fs_read in Rust', () => {+ it('a missing file is a 404 with "File not found", not an empty text', async () => {+ const heim = frischesHeim()+ const ws = arbeitsordnerIn(heim)+ const res = await lesen({ path: 'daten/werte.txt', workingDirectory: ws }, heim)+ expect(res.status).toBe(404)+ expect((res.json() as { error?: string }).error).toBe('File not found: daten/werte.txt')+ })++ it('a file that is there still reads', async () => {+ const heim = frischesHeim()+ const ws = arbeitsordnerIn(heim)+ mkdirSync(join(ws, 'data'), { recursive: true })+ writeFileSync(join(ws, 'data', 'werte.txt'), '12\n7\n')+ const res = await lesen({ path: 'data/werte.txt', workingDirectory: ws }, heim)+ expect(res.status).toBe(200)+ expect((res.json() as { content?: string }).content).toBe('12\n7\n')+ })+})++describe('the folder a dev shell command runs in', () => {+ const same = (a: string, b: string) => expect(realpathSync(a)).toBe(realpathSync(b))++ it('the workspace without a cwd, never the Vite folder', () => {+ const heim = frischesHeim()+ const ws = arbeitsordnerIn(heim)+ same(devShellCwd(undefined, 'c1', ws, heim), ws)+ expect(realpathSync(devShellCwd(undefined, 'c1', ws, heim))).not.toBe(realpathSync(process.cwd()))+ })++ it('a relative cwd inside the workspace, a missing one falls back to it', () => {+ const heim = frischesHeim()+ const ws = arbeitsordnerIn(heim)+ mkdirSync(join(ws, 'fotos'), { recursive: true })+ same(devShellCwd('fotos', 'c1', ws, heim), join(ws, 'fotos'))+ same(devShellCwd('fehlt', 'c1', ws, heim), ws)+ })++ it('without a folder workspace: the chat sandbox under the home', () => {+ const heim = frischesHeim()+ same(devShellCwd('', 'mein-chat', undefined, heim), join(heim, AGENT_WORKSPACE_DIR, 'mein-chat'))+ })+})diff --git a/dev-server/exec-routes.ts b/dev-server/exec-routes.tsindex 85706df1..fb7fc837 100644--- a/dev-server/exec-routes.ts+++ b/dev-server/exec-routes.ts@@ -1,10 +1,27 @@import { spawn, execSync } from 'child_process'-import { mkdirSync, rmSync } from 'fs'+import { existsSync, mkdirSync, rmSync, statSync } from 'fs'import os from 'os'-import { join } from 'path'+import { join, resolve as resolvePath } from 'path'import type { RouteMount } from './routes'import { requirePost, withJsonBody } from './http'import { bodyNumber, bodyString } from '../src/dev/http-body'+import { devWorkspaceRoot } from '../src/lib/dev-fs-jail'++/**+ * The folder a dev-server shell command runs in, the same rule as+ * shell.rs (cwd_in_workspace): the chat's workspace, a relative cwd inside it,+ * an absolute folder as it is. It used to be the Vite process folder (the+ * repo itself) whenever the model sent no cwd (C59 bench, 2026-11-09).+ */+export function devShellCwd(cwd?: string, chatId?: string, workingDirectory?: string, home = os.homedir()): string {+ const base = devWorkspaceRoot(home, chatId, workingDirectory)+ mkdirSync(base, { recursive: true })+ const want = (cwd ?? '').trim()+ if (!want) return base+ // resolve() keeps an absolute cwd as it is and joins a relative one onto base.+ const p = resolvePath(base, want)+ return existsSync(p) && statSync(p).isDirectory() ? p : base+}/*** Die beiden Endpunkte, die aus einem Request heraus einen Prozess starten.@@ -116,7 +133,7 @@ export function registerExecRoutes(routes: RouteMount): void {let killed = falseconst proc = spawn(shellBin, shellArgs, {- cwd: cwd || undefined,+ cwd: devShellCwd(cwd, bodyString(body, 'chatId'), bodyString(body, 'workingDirectory')),stdio: ['ignore', 'pipe', 'pipe'],shell: false,})diff --git a/dev-server/fs-routes.ts b/dev-server/fs-routes.tsindex 43e05885..0f45d90b 100644--- a/dev-server/fs-routes.ts+++ b/dev-server/fs-routes.ts@@ -71,8 +71,12 @@ export function registerFsRoutes(routes: RouteMount): void {res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ content, encoding: 'utf8' }))} catch (err) {- res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ error: String(err) }))+ // Wie fs_read in Rust: ein Lesefehler ist ein Fehler, keine leere Datei.+ // Mit 200 + `error` las file_read daraus "" — ein 9B hielt eine+ // fehlende Datei für leer, erfand Zahlen und schrieb sie hinein (C59).+ const missing = (err as NodeJS.ErrnoException)?.code === 'ENOENT'+ res.writeHead(missing ? 404 : 500, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ error: missing ? `File not found: ${bodyString(body, 'path') || resolved}` : String(err) }))}})})diff --git a/e2e/agent-live/run.bench.ts b/e2e/agent-live/run.bench.tsindex 50f82579..c0ec0e15 100644--- a/e2e/agent-live/run.bench.ts+++ b/e2e/agent-live/run.bench.ts@@ -131,7 +131,7 @@ async function waitForRun(page: Page, convId: string): Promise<'done' | 'timeoutinterface Facts {answer: string- toolCalls: Array<{ name: string; args: unknown; status: string }>+ toolCalls: Array<{ name: string; args: unknown; status: string; result?: string }>reflections: string[]usage: unknownerrors: string[]@@ -144,11 +144,11 @@ async function collect(page: Page, convId: string): Promise<Facts> {const msgs = (conv?.messages ?? []) as Array<{ role: string; content: string; agentBlocks?: Array<{ phase: string; content: string; toolCalls?: Array<{ toolName: string; args: unknown; status: string }> }>; requestUsage?: unknown; error?: { kind: string; detail: string } }>const assistant = msgs.filter((m) => m.role === 'assistant')const blocks = assistant.flatMap((m) => m.agentBlocks ?? [])- const audit = (A['/src/stores/toolAuditStore.ts'].useToolAuditStore.getState().entries[id] ?? []) as Array<{ toolName: string; args: unknown; status: string }>+ const audit = (A['/src/stores/toolAuditStore.ts'].useToolAuditStore.getState().entries[id] ?? []) as Array<{ toolName: string; args: unknown; status: string; resultPreview?: string; error?: string }>const fromBlocks = blocks.flatMap((b) => (b.toolCalls ?? []).map((c) => ({ name: c.toolName, args: c.args, status: c.status })))return {answer: assistant.map((m) => m.content).join('\n').trim(),- toolCalls: (audit.length ? audit.map((e) => ({ name: e.toolName, args: e.args, status: e.status })) : fromBlocks).filter((c) => c.name !== 'context_decay'),+ toolCalls: (audit.length ? audit.map((e) => ({ name: e.toolName, args: e.args, status: e.status, result: String(e.resultPreview ?? e.error ?? '').slice(0, 240) })) : fromBlocks).filter((c) => c.name !== 'context_decay'),reflections: blocks.filter((b) => b.phase === 'reflection').map((b) => b.content.slice(0, 300)),usage: assistant.map((m) => m.requestUsage ?? null),errors: assistant.flatMap((m) => (m.error ? [`${m.error.kind}: ${m.error.detail}`] : [])),@@ -183,6 +183,8 @@ for (const model of MODELS) {ok: check.ok, detail: check.detail,calls: facts.toolCalls.length, failedCalls: failed,tools: facts.toolCalls.map((c) => c.name),+ // What each call sent and got back, short: enough to see why a run went wrong.+ trace: facts.toolCalls.map((c) => ({ name: c.name, status: c.status, args: JSON.stringify(c.args ?? {}).slice(0, 240), result: c.result ?? '' })),planned: facts.toolCalls.some((c) => c.name === 'todo_write'),guardSteer: facts.reflections.filter((s) => /Loop guard steered/i.test(s)).length,guardHalt: facts.reflections.filter((s) => /Loop guard halted/i.test(s)).length + (/\(halted:/.test(facts.answer) ? 1 : 0),diff --git a/e2e/agent-live/settings-shot.bench.ts b/e2e/agent-live/settings-shot.bench.tsindex 463a7d6a..9ebea331 100644--- a/e2e/agent-live/settings-shot.bench.ts+++ b/e2e/agent-live/settings-shot.bench.ts@@ -6,13 +6,23 @@ const OUT = process.env.LU_BENCH_SHOTtest('C59 switch in the settings', async ({ page }) => {test.skip(!OUT, 'set LU_BENCH_SHOT')+ // Tall enough that the whole block of agent switches is painted at once.+ await page.setViewportSize({ width: 1280, height: 4000 })await seedOnboardingDone(page)await page.goto('/')await page.getByRole('button', { name: /settings/i }).first().click()+ await page.getByRole('button', { name: 'Agent', exact: true }).click()const label = page.getByText('Short tool list for local models', { exact: true })+ // The section opens on a click when it starts folded.+ if (!(await label.isVisible().catch(() => false))) {+ await page.getByRole('button', { name: /Agent Permissions/i }).first().click()+ }await label.scrollIntoViewIfNeeded()await expect(label).toBeVisible()await expect(page.getByText(/finds every other tool with tool_search/)).toBeVisible()- const box = await label.locator('xpath=ancestor::*[self::section or self::div][4]').boundingBox()- await page.screenshot({ path: OUT!, clip: box ?? undefined })+ // The switch row, the line under it and the switches just above it.+ // The section unfolds with an animation; measure after it has settled.+ await page.waitForTimeout(1500)+ const b = await label.boundingBox()+ await page.screenshot({ path: OUT!, clip: b ? { x: Math.max(0, b.x - 24), y: Math.max(0, b.y - 70), width: 800, height: 170 } : undefined })})diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 27f84157..62a1609b 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -294,15 +294,21 @@ pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {// `pnpm install` / `cargo build`, so a task the model started "in the// project" ran somewhere else entirely. Fall back to the workspace the// foreground shell tool resolves.- let cwd = match a.cwd.clone() {+ let root = crate::commands::filesystem::workspace_root(+ a.chat_id.as_deref(),+ a.working_directory.as_deref(),+ );+ let cwd = match a.cwd.clone().filter(|c| !c.trim().is_empty()) {+ // A relative cwd is relative to the workspace, as the tool says,+ // not to LU's own process folder (C59).+ Some(c) if std::path::Path::new(c.trim()).is_relative() => {+ root.join(c.trim()).to_str().map(|s| s.to_string())+ }Some(c) => Some(c),- None => crate::commands::filesystem::workspace_root(- a.chat_id.as_deref(),- a.working_directory.as_deref(),- )- .to_str()- .map(|s| s.to_string())- .filter(|s| std::path::Path::new(s).is_dir()),+ None => root+ .to_str()+ .map(|s| s.to_string())+ .filter(|s| std::path::Path::new(s).is_dir()),};if let Some(cwd) = &cwd {let p = std::path::Path::new(cwd);@@ -1181,6 +1187,29 @@ mod cwd_default_tests {// Negative control: the folder that must NOT have won.assert!(!same_directory(&seen, &a), "the task ran in the fallback {a:?}");}++ /// The tool says cwd is relative to the workspace. A relative one used to+ /// be taken against LU's own process folder (C59).+ #[tokio::test]+ async fn a_relative_cwd_is_inside_the_workspace() {+ let _isolation = super::sweep_isolation().await;+ let ws = crate::os_paths::test_dir("bg-rel");+ std::fs::create_dir_all(ws.join("sub")).unwrap();++ let start = shell_task_start_impl(&super::a_task_that_prints_its_directory(json!({+ "cwd": "sub",+ "working_directory": ws.to_string_lossy(),+ })))+ .await+ .expect("start");+ let id = start["id"].as_str().unwrap().to_string();++ let seen = reported_directory(&id).await;+ assert!(+ same_directory(&seen, &ws.join("sub")),+ "relative cwd not joined onto the workspace: reported {seen:?}",+ );+ }}/// The background task and its foreground twin, held against each other.diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex 76c3a11c..f523b589 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -28,6 +28,23 @@ fn workspace_cwd(chat_id: Option<&str>) -> PathBuf {.join(crate::commands::agent::sanitize_chat_slug(chat_id.unwrap_or("default")))}+/// The folder a command runs in. The tool tells the model that `cwd` is+/// "relative to the workspace", so a relative one is joined onto the+/// workspace; it used to be checked against the app's own process folder,+/// failed there, and the command ran in the workspace root instead of the+/// subfolder the model asked for (C59 bench, 2026-11-09). An absolute cwd+/// that exists is used as is; anything that is not a folder falls back to+/// the workspace.+pub(crate) fn cwd_in_workspace(cwd: Option<&str>, base: &Path) -> PathBuf {+ match cwd.map(str::trim).filter(|s| !s.is_empty()).map(Path::new) {+ Some(p) => {+ let p = if p.is_absolute() { p.to_path_buf() } else { base.join(p) };+ if p.is_dir() { p } else { base.to_path_buf() }+ }+ None => base.to_path_buf(),+ }+}+/// How much of a command's output travels back to the model. Anything past this/// is still read off the pipe — it has to be, or the child blocks — but dropped.const MAX_CAPTURE: usize = 256 * 1024;@@ -953,19 +970,17 @@ fn shell_execute_sync(// back to the per-chat agent workspace (created if missing) so a relative// command never runs in the app's ambient cwd and scatters files into// ~/Documents (2026-06-04). Mirrors the file tools' path resolution.- let workdir: PathBuf = match cwd.as_ref().map(Path::new) {- Some(p) if p.is_dir() => p.to_path_buf(),- _ => match working_directory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {- // Folder workspace (the user's repo, from chatCtx.workingDirectory)- // wins over the per-chat sandbox for relative commands (#62).- Some(wd) => PathBuf::from(wd),- None => {- let w = workspace_cwd(chat_id.as_deref());- let _ = std::fs::create_dir_all(&w);- w- }- },+ let base: PathBuf = match working_directory.as_deref().map(str::trim).filter(|s| !s.is_empty()) {+ // Folder workspace (the user's repo, from chatCtx.workingDirectory)+ // wins over the per-chat sandbox for relative commands (#62).+ Some(wd) => PathBuf::from(wd),+ None => {+ let w = workspace_cwd(chat_id.as_deref());+ let _ = std::fs::create_dir_all(&w);+ w+ }};+ let workdir = cwd_in_workspace(cwd.as_deref(), &base);if workdir.is_dir() {cmd.current_dir(&workdir);}@@ -1713,3 +1728,24 @@ mod stranger_tests {assert!(!is_a_stranger_under(40, 1000, table.into_iter()));}}++#[cfg(test)]+mod cwd_in_workspace_tests {+ use super::cwd_in_workspace;++ #[test]+ fn a_relative_cwd_lands_inside_the_workspace() {+ let ws = std::env::temp_dir().join(format!("lu-cwd-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(ws.join("fotos")).unwrap();+ assert_eq!(cwd_in_workspace(Some("fotos"), &ws), ws.join("fotos"));+ assert_eq!(cwd_in_workspace(Some(" fotos "), &ws), ws.join("fotos"));+ // Not a folder there: the workspace, never the app's own folder.+ assert_eq!(cwd_in_workspace(Some("fehlt"), &ws), ws);+ assert_eq!(cwd_in_workspace(None, &ws), ws);+ assert_eq!(cwd_in_workspace(Some(""), &ws), ws);+ // An absolute folder is used as it is.+ let abs = ws.join("fotos");+ assert_eq!(cwd_in_workspace(abs.to_str(), &ws), abs);+ let _ = std::fs::remove_dir_all(&ws);+ }+}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 61223199..cac01983 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -171,7 +171,7 @@ 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 { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS, COMPACT_PREFER } 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'@@ -1995,7 +1995,7 @@ export function useAgentChat() {toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts, undefined, { purpose: 'tool-selection' })),phoneToolCtx, SMALL_MODEL_MAX_TOOLS,),- ...(compactRun ? { maxTools: COMPACT_MAX_TOOLS } : {}),+ ...(compactRun ? { maxTools: COMPACT_MAX_TOOLS, prefer: COMPACT_PREFER } : {}),reaText,},), planAllowed), toolRegistry.getAll())diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex bd73ea14..f9636033 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -84,7 +84,7 @@ 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, applyMaxTools } from '../lib/tool-selection'-import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS } from '../lib/agent-profile'+import { agentProfileFor, resultCharsFor, COMPACT_MAX_TOOLS, COMPACT_PREFER } 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'@@ -1604,7 +1604,7 @@ export function useCodex() {: !isLocalModelByName(activeModel)? codexTools: compactRun- ? applyMaxTools(selectRelevantTools(lastUserMsg, codexTools, permissions, undefined, reaText), COMPACT_MAX_TOOLS)+ ? applyMaxTools(selectRelevantTools(lastUserMsg, codexTools, permissions, undefined, reaText), COMPACT_MAX_TOOLS, [...COMPACT_PREFER]): 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.diff --git a/src/lib/__tests__/agent-compact-profile.test.ts b/src/lib/__tests__/agent-compact-profile.test.tsindex 2374ade9..e6453930 100644--- a/src/lib/__tests__/agent-compact-profile.test.ts+++ b/src/lib/__tests__/agent-compact-profile.test.ts@@ -135,3 +135,39 @@ describe('briefs from the tool itself and from foreign servers', () => {expect(briefFor({ name: 'y', description: 'Read <tools> now', source: 'external' })).not.toContain('<tools>')})})++describe('the compact list keeps the tools for this computer (C59 bench, AG3)', () => {+ const full = [+ ...CATALOG,+ tool('file_edit', 'Change part of a file.'),+ tool('todo_write', 'The plan.'),+ tool('file_list', 'List a folder.'),+ tool('file_search', 'Search file contents.'),+ tool('web_search', 'Search the web.'),+ tool('web_fetch', 'Read a web page.'),+ tool('screenshot', 'Take a screenshot.'),+ tool('clipboard_read', 'Read the clipboard.'),+ tool('process_list', 'List running processes.'),+ tool('system_info', 'Show system info.'),+ tool('image_describe', 'Describe an image file.'),+ ]+ // An embedding that likes media and web tools best: the ranking that left+ // shell_execute out of "rename these photos" on the 9B.+ const embed = async (texts: string[]) => texts.map((t) => (/image|video|web|screenshot|picture|clip/i.test(t) || /Benenne/.test(t) ? [1, 0] : [0, 1]))+ const perms = Object.fromEntries(full.map((t) => [t.category, 'auto'])) as never++ it('rename photos: shell_execute, file_list and file_search survive the cap', async () => {+ const { selectRelevantToolsAsync } = await import('../tool-selection')+ const { COMPACT_PREFER } = await import('../agent-profile')+ const got = (await selectRelevantToolsAsync('Benenne alle IMG_*.jpg in fotos/ um', full, perms, {+ embed, embeddingThreshold: 0, maxTools: COMPACT_MAX_TOOLS, prefer: COMPACT_PREFER,+ })).map((t) => t.name)+ expect(got.length).toBeLessThanOrEqual(COMPACT_MAX_TOOLS)+ for (const n of ['shell_execute', 'file_list', 'file_search', ...ALWAYS_INCLUDE]) expect(got, n).toContain(n)+ })++ it('tool_search finds the shell by its job', () => {+ expect(searchTools('rename files in directory', [...CATALOG, tool('file_list', 'List a folder.')]).map((t) => t.name)).toContain('shell_execute')+ expect(searchTools('move or delete a file', CATALOG).map((t) => t.name)).toContain('shell_execute')+ })+})diff --git a/src/lib/__tests__/loop-guard-search-streak.test.ts b/src/lib/__tests__/loop-guard-search-streak.test.tsnew file mode 100644index 00000000..de80cba2--- /dev/null+++ b/src/lib/__tests__/loop-guard-search-streak.test.ts@@ -0,0 +1,32 @@+/**+ * C59 bench, AG3 on the 9B: 23 web searches in one turn, each query a word+ * apart, so no repeat detector fired. A streak of search-only steps now+ * steers at six and ends the turn at twelve.+ */+import { describe, it, expect } from 'vitest'+import { AgentLoopGuard } from '../agent-loop-guard'++const search = (q: string) => [{ name: 'web_search', args: JSON.stringify({ query: q }) }]++describe('web searches in a row', () => {+ it('steer at six, halt at twelve, each query different', () => {+ const g = new AgentLoopGuard()+ const verdicts = Array.from({ length: 12 }, (_, i) => g.recordBatch(search(`bash mv rename ${i}`)).action)+ expect(verdicts.slice(0, 5).every((v) => v === 'ok')).toBe(true)+ expect(verdicts[5]).toBe('steer')+ expect(verdicts.slice(6, 11).every((v) => v === 'ok')).toBe(true)+ expect(verdicts[11]).toBe('halt')+ })++ it('reading a page in between starts the count again', () => {+ const g = new AgentLoopGuard()+ for (let i = 0; i < 5; i++) expect(g.recordBatch(search(`q${i}`)).action).toBe('ok')+ expect(g.recordBatch([{ name: 'web_fetch', args: JSON.stringify({ url: 'https://example.org' }) }]).action).toBe('ok')+ for (let i = 0; i < 5; i++) expect(g.recordBatch(search(`r${i}`)).action).toBe('ok')+ })++ it('switched off, it stays quiet', () => {+ const g = new AgentLoopGuard({ enabled: false })+ for (let i = 0; i < 15; i++) expect(g.recordBatch(search(`q${i}`)).action).toBe('ok')+ })+})diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.tsindex 5ff11e70..6cac7a4c 100644--- a/src/lib/agent-loop-guard.ts+++ b/src/lib/agent-loop-guard.ts@@ -123,6 +123,17 @@ const SCROLL_TOOLS = new Set<string>(['browser_scroll'])const SCROLL_STEER_AT = 10const SCROLL_HALT_AT = 20+/**+ * Web searches in a row with nothing read or done in between (C59 bench).+ * Each query differs by a word, so the repeat detectors never fire: a 9B+ * that lacked the shell searched the web 23 times for "mv" in one turn.+ * Six searches without opening a page is a model that has stopped reading+ * its results; twelve is a stall.+ */+const SEARCH_TOOLS = new Set<string>(['web_search'])+const SEARCH_STEER_AT = 6+const SEARCH_HALT_AT = 12+/** Tools whose args carry a shell command whose first token names the work. */const EXEC_TOOLS = new Set<string>(['shell_execute', 'shell_execute_background'])@@ -174,6 +185,9 @@ export class AgentLoopGuard {/** Batches of nothing but browser_scroll in a row (P-L, C53). */private scrollStreak = 0private scrollSteered = false+ /** Batches of nothing but web_search in a row (C59). */+ private searchStreak = 0+ private searchSteered = falseprivate windowSteered = new Set<string>()private narrationRowSteered = falseprivate lastNarration = ''@@ -229,6 +243,22 @@ export class AgentLoopGuard {}this.scrollStreak = 0this.scrollSteered = false+ if (calls.every((c) => SEARCH_TOOLS.has(c.name))) {+ this.searchStreak+++ if (this.searchStreak >= SEARCH_HALT_AT) {+ return { action: 'halt', reason: `${this.searchStreak} web searches in a row without reading a page or doing anything else` }+ }+ if (this.searchStreak >= SEARCH_STEER_AT && !this.searchSteered) {+ this.searchSteered = true+ return {+ action: 'steer',+ message: `You searched the web ${this.searchStreak} times in a row. Stop searching: read the best result with web_fetch, or do the task with the tools you have. If a tool you need is missing, ask tool_search once.`,+ }+ }+ } else {+ this.searchStreak = 0+ this.searchSteered = false+ }const keys = calls.map((c) => `${c.name}|${c.args}`)const sig = [...keys].sort().join('||')const trimmed = opts.trimmedReadKeysdiff --git a/src/lib/agent-profile.ts b/src/lib/agent-profile.tsindex 05f227f9..2b4ad135 100644--- a/src/lib/agent-profile.ts+++ b/src/lib/agent-profile.ts@@ -21,8 +21,24 @@ 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+/**+ * The tool list of a compact run, before tool_search and unlocked tools.+ * 8 was too few: the four always-on tools plus a semantic ranking left+ * shell_execute out of "rename these photos", and the 9B tried file_edit on+ * the folder and then searched the web 25 times for "mv" (C59 bench). Ten+ * holds the four, the local trio and the web pair, with one slot to spare.+ */+export const COMPACT_MAX_TOOLS = 10++/**+ * The keyword router's picks that a compact list keeps before the semantic+ * ranking fills the rest: the tools for working on this computer, then the+ * web. Only names the keyword router chose are moved forward, so a pure file+ * task never gets the web pair this way and a web question keeps both halves.+ */+export const COMPACT_PREFER: readonly string[] = [+ 'shell_execute', 'file_list', 'file_search', 'web_search', 'web_fetch', 'web_research',+]/** A tool result in a compact run: about 4k tokens, an eighth of a 32k window. */export const COMPACT_RESULT_CHARS = 16_000diff --git a/src/lib/plugins/__tests__/rea-tools-stay-for-a-follow-up.test.ts b/src/lib/plugins/__tests__/rea-tools-stay-for-a-follow-up.test.tsindex afae59ac..26157db8 100644--- a/src/lib/plugins/__tests__/rea-tools-stay-for-a-follow-up.test.ts+++ b/src/lib/plugins/__tests__/rea-tools-stay-for-a-follow-up.test.ts@@ -74,6 +74,6 @@ describe('the turn after a stopped run keeps the REA tools', () => {expect(read('useCodex.ts')).toMatch(/maxTools: SMALL_MODEL_MAX_TOOLS,\s+reaText,/)// Since the phone line joined (3.0.8) the options go through withPhoneToolCap// first; reaText rides next to it in the same object.- expect(read('useAgentChat.ts').match(/phoneToolCtx, SMALL_MODEL_MAX_TOOLS,\s+\),\s+(?:\.\.\.\(compactRun \? \{ maxTools: COMPACT_MAX_TOOLS \} : \{\}\),\s+)?reaText,\s+\}/g)).toHaveLength(2)+ expect(read('useAgentChat.ts').match(/phoneToolCtx, SMALL_MODEL_MAX_TOOLS,\s+\),\s+(?:\.\.\.\(compactRun \? \{ maxTools: COMPACT_MAX_TOOLS, prefer: COMPACT_PREFER \} : \{\}\),\s+)?reaText,\s+\}/g)).toHaveLength(2)})})diff --git a/src/lib/tool-search.ts b/src/lib/tool-search.tsindex 957d2d09..834f076a 100644--- a/src/lib/tool-search.ts+++ b/src/lib/tool-search.ts@@ -86,7 +86,9 @@ function scoreTools(query: string, catalog: readonly MCPToolDefinition[]): Score.filter((t) => t.name !== TOOL_SEARCH).map((t) => {const name = words(t.name)- const desc = words(t.description)+ // The one-line brief counts too: it names jobs ("rename", "move") the+ // long description only shows as commands, and a 9B searches by job.+ const desc = words(`${t.description} ${CORE_BRIEFS[t.name] ?? ''}`)let score = 0for (const w of q) {if (name.some((n) => close(n, w))) score += 3@@ -128,7 +130,7 @@ export const CORE_BRIEFS: Readonly<Record<string, string>> = {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.',+ shell_execute: 'Run one shell command in the workspace: git, tests, scripts, and to rename, move, copy or delete files (mv, cp, mkdir). Returns stdout, stderr, exit code.',}/**diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.tsindex 8b3d4cef..f8d3ed22 100644--- a/src/lib/tool-selection.ts+++ b/src/lib/tool-selection.ts@@ -575,13 +575,18 @@ export async function selectRelevantToolsAsync(userMessage: string,allTools: MCPToolDefinition[],permissions: PermissionMap,- opts?: { embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number; maxTools?: number; reaText?: string },+ opts?: {+ embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number; maxTools?: number; reaText?: string+ /** Keyword picks that go ahead of the semantic ranking under the cap+ * (agent-profile COMPACT_PREFER). Unset: the ranking alone, as before. */+ prefer?: readonly string[]+ },): Promise<MCPToolDefinition[]> {const threshold = opts?.embeddingThreshold ?? EMBEDDING_ROUTING_THRESHOLDconst available = allTools.filter((t) => permissions[t.category] !== 'blocked')const pinned = mentionedToolNames(userMessage, available)if (!opts?.embed || available.length <= threshold) {- return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions, undefined, opts?.reaText), opts?.maxTools, undefined, pinned)+ return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions, undefined, opts?.reaText), opts?.maxTools, opts?.prefer ? [...opts.prefer] : undefined, pinned)}try {const semanticNames = await selectToolsByEmbedding(@@ -593,13 +598,17 @@ export async function selectRelevantToolsAsync(const keyword = selectRelevantTools(userMessage, allTools, permissions, undefined, opts?.reaText)const union = new Set<string>([...semanticNames, ...keyword.map((t) => t.name)])const selected = available.filter((t) => union.has(t.name))+ const keywordNames = new Set(keyword.map((t) => t.name))+ const rank = opts.prefer+ ? [...opts.prefer.filter((n) => keywordNames.has(n)), ...semanticNames]+ : semanticNames// 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. Verbatim-named// tools are pinned past the cap on both paths.- return applyMaxTools(selected, opts.maxTools, semanticNames, pinned)+ return applyMaxTools(selected, opts.maxTools, rank, pinned)} catch {- return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions, undefined, opts?.reaText), opts?.maxTools, undefined, pinned)+ return applyMaxTools(selectRelevantTools(userMessage, allTools, permissions, undefined, opts?.reaText), opts?.maxTools, opts?.prefer ? [...opts.prefer] : undefined, pinned)}}