Skip to content

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.

fix(agent): the shell stays in its folder, timeouts are capped, a search spiral ends with an honest answer (CA)

purplef2ee264cd561
diff --git a/mobile-client/agent-core.js b/mobile-client/agent-core.js
index d8fc256e..5374b38c 100644
--- a/mobile-client/agent-core.js
+++ b/mobile-client/agent-core.js
@@ -31,10 +31,10 @@ import { stripNonCanonicalTags } from './personas.js'
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, 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. A command still running at its timeout keeps running in the background under a task id.',
+ {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. Paths outside your folder are refused. Timeout at most 120 s, test runs 300 s. A command still running at its timeout keeps running in the background under a task id.',
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, relative to the workspace)',required:false},
- {name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},
+ {name:'timeout',type:'number',description:'Timeout in ms (at most 120000)',required:false},
{name:'shell',type:'string',description:'Override shell: "powershell" | "cmd" | "bash" (default: auto)',required:false},
{name:'stdin',type:'string',description:'Text piped to the command\x27s stdin, e.g. a Python script for `python3 -`.',required:false},
{name:'background',type:'boolean',description:'Run detached; returns a task id immediately instead of waiting.',required:false},
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 04947883..2d315152 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -1196,6 +1196,7 @@ async fn handle_agent_tool(
let code = body.args.get("code").and_then(|v| v.as_str()).unwrap_or("").to_string();
let timeout = body.args.get("timeout").and_then(|v| v.as_u64());
if code.is_empty() { Err("code_execute needs a non-empty `code` argument.".into()) }
+ else if let Some(no) = crate::shell_scope::code_refusal(&code) { Err(no) }
else { crate::commands::agent::execute_code_blocking(code, timeout, chat_id.clone(), None, None, &app_state) }
}
"web_search" => {
@@ -1277,8 +1278,14 @@ async fn handle_agent_tool(
.or_else(|| Some(crate::commands::agent::agent_workspace_for(chat_id.as_deref(), &app_state)
.to_string_lossy()
.to_string()));
- let start_args = serde_json::json!({ "command": command, "cwd": cwd, "chat_id": chat_id });
- crate::commands::bg_tasks::shell_task_start_impl(&start_args).await
+ let root = crate::commands::agent::agent_workspace_for(chat_id.as_deref(), &app_state);
+ let here = cwd.as_deref().map(std::path::PathBuf::from).unwrap_or_else(|| root.clone());
+ // CA (14.11.2026, AG10): the remote shell stays in its folder.
+ if let Some(no) = crate::shell_scope::refusal(&command, &root, &here) { Err(no) }
+ else {
+ let start_args = serde_json::json!({ "command": command, "cwd": cwd, "chat_id": chat_id });
+ crate::commands::bg_tasks::shell_task_start_impl(&start_args).await
+ }
}
else {
// Default cwd → the per-chat workspace folder so `npm install`
@@ -1301,9 +1308,13 @@ async fn handle_agent_tool(
if let Some(ref dir) = cwd {
let _ = std::fs::create_dir_all(dir);
}
- let timeout = body.args.get("timeout").and_then(|v| v.as_u64());
+ // CA (14.11.2026, AG10): at most two minutes, the model's
+ // wish below that; then the command goes on as a task (T1).
+ let timeout = crate::shell_scope::capped_timeout(body.args.get("timeout").and_then(|v| v.as_u64()), &command);
let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);
let stdin = body.args.get("stdin").and_then(|v| v.as_str()).map(String::from);
+ let root = crate::commands::agent::agent_workspace_for(chat_id.as_deref(), &app_state);
+ let here = cwd.as_deref().map(std::path::PathBuf::from).unwrap_or_else(|| root.clone());
// `call_id` ist None: die Fernbruecke hat keinen Kanal, ueber
// den ein Abbruch zurueckkaeme. Ohne Kennung ist der Befehl
// nicht abbrechbar, und das ist ehrlicher als eine Kennung, die
@@ -1312,7 +1323,10 @@ async fn handle_agent_tool(
// `Some(true)` (T1): a command that outruns its timeout keeps
// running as a task the phone reaches with task "status" /
// "kill" above, as the shared tool description promises.
- crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None, None, Some(true)).await
+ // The remote shell stays in its folder: no switch for it, the
+ // phone is a network surface (shell_scope.rs).
+ if let Some(no) = crate::shell_scope::refusal(&command, &root, &here) { Err(no) }
+ else { crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None, None, Some(true)).await }
}
}
"system_info" => crate::commands::system::system_info(),
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 8ba5de9c..18a28329 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -20,6 +20,7 @@ mod linux_media;
mod app_identity;
mod appimage_gio;
mod secret_paths;
+mod shell_scope;
// The chat's HTML preview server. A phone starts no server (mobile_guard.rs).
#[cfg(desktop)]
mod html_preview;
diff --git a/src-tauri/src/shell_scope.rs b/src-tauri/src/shell_scope.rs
new file mode 100644
index 00000000..bdd1c4d7
--- /dev/null
+++ b/src-tauri/src/shell_scope.rs
@@ -0,0 +1,198 @@
+//! The remote agent's shell stays inside its folder (CA, 14.11.2026, AG10).
+//!
+//! Same rule as `src/lib/shell-scope.ts` on the desktop side: a command that
+//! points at the home folder, the disk root or an absolute path outside the
+//! agent's workspace is refused before it runs. The phone reaches the desktop
+//! over the network, so there is no switch for it here: the remote agent
+//! always stays in its folder.
+//!
+//! It reads the command, it does not sandbox the process. It stops what
+//! models actually do, which is to type the path (a measured run went through
+//! `find / -maxdepth 6`, `ls /Users/<name>` and ~/Library for 32 minutes).
+
+use std::path::Path;
+
+use regex::Regex;
+use std::sync::OnceLock;
+
+fn home_ref() -> &'static Regex {
+ static R: OnceLock<Regex> = OnceLock::new();
+ R.get_or_init(|| {
+ Regex::new(r#"(?i)(^|[\s=:"'(])~([/\s"')]|$)|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|%APPDATA%|%LOCALAPPDATA%|\$env:(USERPROFILE|HOME|APPDATA|LOCALAPPDATA)"#)
+ .expect("home regex")
+ })
+}
+
+fn words() -> &'static Regex {
+ static R: OnceLock<Regex> = OnceLock::new();
+ R.get_or_init(|| Regex::new(r#""([^"]*)"|'([^']*)'|([^\s;|&()<>]+)"#).expect("word regex"))
+}
+
+fn system_top() -> &'static Regex {
+ static R: OnceLock<Regex> = OnceLock::new();
+ R.get_or_init(|| {
+ Regex::new(r"^/(Users|home|root|Volumes|mnt|media|etc|var|private|Library|System|Applications|opt|srv|proc|sys)(/|$)")
+ .expect("system regex")
+ })
+}
+
+fn always_fine(p: &str) -> bool {
+ static R: OnceLock<Regex> = OnceLock::new();
+ R.get_or_init(|| {
+ Regex::new(r"^/dev/(null|stdin|stdout|stderr|tty|zero|u?random)$|^/(private/)?tmp(/|$)|^/var/folders/|^/(usr/(local/)?|opt/homebrew/)?s?bin/|^/usr/bin/env$")
+ .expect("fine regex")
+ })
+ .is_match(p)
+}
+
+fn is_abs(p: &str) -> bool {
+ let b = p.as_bytes();
+ p.starts_with('/') || p.starts_with("\\\\") || (b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\'))
+}
+
+fn path_in(word: &str) -> Option<String> {
+ let w = word.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start_matches('>').trim_start_matches('>');
+ let v = match w.split_once('=') {
+ Some((opt, val)) if opt.starts_with('-') => val,
+ _ => w,
+ };
+ let has_dotdot = v.split(['/', '\\']).any(|seg| seg == "..");
+ if is_abs(v) || has_dotdot { Some(v.to_string()) } else { None }
+}
+
+/// The first place `command` reaches outside `root`, as a sentence for the
+/// model, or None. `cwd` is where relative paths start.
+pub fn refusal(command: &str, root: &Path, cwd: &Path) -> Option<String> {
+ let reach = reach_outside(command, root, cwd)?;
+ Some(format!(
+ "Refused: this command reaches {}. You work only inside your folder. Use paths inside the folder. If what you need is not there, stop searching and say so in your answer.",
+ reach
+ ))
+}
+
+fn reach_outside(command: &str, root: &Path, cwd: &Path) -> Option<String> {
+ if home_ref().is_match(command) {
+ return Some("the home folder".into());
+ }
+ for cap in words().captures_iter(command) {
+ let (text, quoted) = match (cap.get(1), cap.get(2), cap.get(3)) {
+ (Some(m), _, _) | (_, Some(m), _) => (m.as_str(), true),
+ (_, _, Some(m)) => (m.as_str(), false),
+ _ => continue,
+ };
+ let Some(p) = path_in(text) else { continue };
+ let b = p.as_bytes();
+ if p == "/" || (b.len() <= 3 && b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':') {
+ return Some("the whole disk".into());
+ }
+ if always_fine(&p) || p.contains("://") {
+ continue;
+ }
+ if quoted && p.starts_with('/') && !system_top().is_match(&p) {
+ continue;
+ }
+ let candidate = if is_abs(&p) { Path::new(&p).to_path_buf() } else { cwd.join(&p) };
+ if crate::commands::filesystem::contain_within(root, &candidate).is_err() {
+ return Some(format!("\"{}\", outside your folder", p));
+ }
+ }
+ None
+}
+
+/// Python code for code_execute: the home folder and absolute system paths
+/// typed into the code.
+pub fn code_refusal(code: &str) -> Option<String> {
+ static HOME: OnceLock<Regex> = OnceLock::new();
+ static ABS: OnceLock<Regex> = OnceLock::new();
+ let home = HOME.get_or_init(|| {
+ Regex::new(r#"expanduser\(|Path\.home\(|os\.environ(\.get)?\(?\[?["']HOME["']|getenv\(["']HOME["']|\$\{?HOME\}?|["']~/"#).expect("code home")
+ });
+ let abs = ABS.get_or_init(|| Regex::new(r#"["'](/[^"'\n]*)["']"#).expect("code abs"));
+ let what = if home.is_match(code) {
+ Some("the home folder".to_string())
+ } else {
+ abs.captures_iter(code).find_map(|c| {
+ let p = c.get(1)?.as_str();
+ if p == "/" {
+ Some("the whole disk".to_string())
+ } else if system_top().is_match(p) && !always_fine(p) {
+ Some(format!("\"{}\", outside your folder", p))
+ } else {
+ None
+ }
+ })
+ }?;
+ Some(format!(
+ "Refused: this code reaches {}. You work only inside your folder. If what you need is not there, say so in your answer.",
+ what
+ ))
+}
+
+/// The remote shell's timeout: the model's wish, at most two minutes, a test
+/// run five (the same budgets the desktop tool names). A command still running
+/// then goes on as a background task, it is not killed.
+pub const REMOTE_SHELL_TIMEOUT_MAX_MS: u64 = 120_000;
+pub const REMOTE_TEST_TIMEOUT_MAX_MS: u64 = 300_000;
+
+fn is_test_run(command: &str) -> bool {
+ static R: OnceLock<Regex> = OnceLock::new();
+ R.get_or_init(|| {
+ Regex::new(r"(^|[\s;&|])((npm|pnpm|yarn|bun)\s+(run\s+)?test|npx\s+(vitest|jest|playwright)|vitest|jest|pytest|python3?\s+-m\s+(pytest|unittest)|cargo\s+test|go\s+test|node\s+--test)(\s|$)")
+ .expect("test regex")
+ })
+ .is_match(command)
+}
+
+pub fn capped_timeout(requested: Option<u64>, command: &str) -> Option<u64> {
+ let (default, cap) = if is_test_run(command) {
+ (REMOTE_TEST_TIMEOUT_MAX_MS, REMOTE_TEST_TIMEOUT_MAX_MS)
+ } else {
+ (REMOTE_SHELL_TIMEOUT_MAX_MS, REMOTE_SHELL_TIMEOUT_MAX_MS)
+ };
+ Some(requested.unwrap_or(default).clamp(1_000, cap))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ fn ws() -> PathBuf {
+ std::env::temp_dir().join("lu-scope-ws")
+ }
+
+ #[test]
+ fn the_folder_itself_is_fine() {
+ let r = ws();
+ for c in ["ls", "find . -name '*.json'", "cat src/a.ts | grep x", "node --test 2>/dev/null", "grep -r \"/api/v1\" .", "/usr/bin/env python3 x.py"] {
+ assert!(refusal(c, &r, &r).is_none(), "{c}");
+ }
+ let inside = format!("cat {}/notes.txt", r.display());
+ assert!(refusal(&inside, &r, &r).is_none());
+ }
+
+ #[test]
+ fn home_root_and_outside_are_refused() {
+ let r = ws();
+ for c in ["find / -maxdepth 6 -iname '*memor*'", "ls ~/Library", "grep -r x $HOME", "ls -la /Users/someone", "cat ../../.ssh/id_rsa", "cat \"/etc/hosts\"", "dir %USERPROFILE%"] {
+ assert!(refusal(c, &r, &r).is_some(), "{c}");
+ }
+ }
+
+ #[test]
+ fn code_paths() {
+ assert!(code_refusal("import os\nprint(os.path.expanduser('~'))").is_some());
+ assert!(code_refusal("open('/etc/passwd').read()").is_some());
+ assert!(code_refusal("open('data.json').read()").is_none());
+ assert!(code_refusal("open('/tmp/x').write('a')").is_none());
+ }
+
+ #[test]
+ fn timeout_is_capped() {
+ assert_eq!(capped_timeout(Some(600_000), "find . -name x"), Some(120_000));
+ assert_eq!(capped_timeout(None, "ls"), Some(120_000));
+ assert_eq!(capped_timeout(Some(5_000), "ls"), Some(5_000));
+ assert_eq!(capped_timeout(Some(900_000), "npm test"), Some(300_000));
+ assert_eq!(capped_timeout(None, "cargo test --lib"), Some(300_000));
+ }
+}
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 92d23c41..4de75178 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -424,14 +424,14 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
+ '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. '
+ + 'Paths outside your folder are refused. Timeout at most 120 s, test runs 300 s. '
+ 'A command still running at its timeout keeps running in the background under a task id.',
inputSchema: {
type: 'object',
properties: {
command: { type: 'string', description: 'The full command to execute. Omit only for task actions.' },
cwd: { type: 'string', description: 'Working directory (optional, relative to the workspace)' },
- timeout: { type: 'number', description: 'Timeout in milliseconds (default: 120000)' },
+ timeout: { type: 'number', description: 'Timeout in ms (at most 120000)' },
shell: { type: 'string', description: 'Override shell: "powershell" | "cmd" | "bash" (default: auto)' },
stdin: { type: 'string', description: 'Text piped to the command\'s stdin, e.g. a Python script for `python3 -`.' },
background: { type: 'boolean', description: 'Run detached; returns a task id immediately instead of waiting.' },
@@ -1002,6 +1002,27 @@ async function executeFileSearch(args: ToolArgs, run?: AgentRunContext): Promise
return JSON.stringify(data)
}
+/**
+ * The front gate of the shell (CA, 14.11.2026, AG10; lib/shell-scope.ts): a
+ * command that points at the home folder, the disk root or a path outside the
+ * agent's folder is refused, unless the user allowed it in Settings → Agent.
+ * "Outside" is the backend jail's own answer, the one the file tools get.
+ */
+async function outsideFolderRefusal(command: string, cwd: unknown, run?: AgentRunContext): Promise<string | null> {
+ const { useSettingsStore } = await import('../../stores/settingsStore')
+ if (useSettingsStore.getState().settings.agentShellOutsideFolder === true) return null
+ const { shellReachOutside, outsideRefusal } = await import('../../lib/shell-scope')
+ const reach = await shellReachOutside(command, async (path) => {
+ try {
+ await backendCall('fs_info', { path, ...chatCtx(run) })
+ return false
+ } catch (e) {
+ return /escapes the allowed workspace/i.test(e instanceof Error ? e.message : String(e))
+ }
+ }, typeof cwd === 'string' && cwd.trim() ? cwd : undefined)
+ return reach ? outsideRefusal(reach) : null
+}
+
async function executeShellExecute(
args: ToolArgs,
run?: AgentRunContext,
@@ -1059,6 +1080,9 @@ async function executeShellExecute(
// Flag abwaehlt, ist keine.
const refusal = rejectShellCommand(command) ?? hardBlockedShellCommand(command)
if (refusal) return refusal
+ // Vor der Hintergrund-Weiche, aus demselben Grund wie die Sperre darueber.
+ const outside = await outsideFolderRefusal(command, args.cwd, run)
+ if (outside) return outside
// `shell` muss mit: das Backend leitet die Argumentform seit ba9557df aus dem
// Shell-NAMEN ab (shell::shell_argv), das Durchreichen ist also folgenlos
@@ -1066,9 +1090,12 @@ async function executeShellExecute(
// kennt StartArgs auf der Rust-Seite gar nicht.
if (args.background) return executeShellExecuteBg({ command, cwd: args.cwd, shell: args.shell }, run, abort)
- // An explicit timeout wins; otherwise a recognised test run keeps the old
- // run_tests budget (300 s) instead of the shell default.
- const timeout = argNumber(args, 'timeout') || commandTimeoutMs(command, 120000)
+ // What the model asks for is a wish under the cap (CA, 14.11.2026: one model
+ // asked for 600 s per `find /`); a recognised test run keeps the run_tests
+ // budget (300 s). A command still running at its timeout is not killed, it
+ // goes on as a background task (T1 below).
+ const { cappedShellTimeout, SHELL_TIMEOUT_DEFAULT_MS } = await import('../../lib/shell-scope')
+ const timeout = cappedShellTimeout(argNumber(args, 'timeout') || undefined, commandTimeoutMs(command, SHELL_TIMEOUT_DEFAULT_MS))
const data = await invokeShell({
command,
args: args.args || null,
@@ -1181,6 +1208,14 @@ async function executeCodeExecute(
// executeShellExecute — die eigene braucht es hier trotzdem.
const bad = missingArgs('code_execute', args, 'code')
if (bad) return bad
+ {
+ const { useSettingsStore } = await import('../../stores/settingsStore')
+ if (useSettingsStore.getState().settings.agentShellOutsideFolder !== true) {
+ const { scanCodePaths, outsideRefusal } = await import('../../lib/shell-scope')
+ const reach = scanCodePaths(argString(args, 'code'))
+ if (reach) return outsideRefusal(reach)
+ }
+ }
const data = await invokeCode({ code: argString(args, 'code'), timeout: 30000, ...chatCtx(run) }, abort)
const output = data.stdout || ''
const err = data.stderr || ''
@@ -1275,6 +1310,8 @@ async function executeShellExecuteBg(
const { rejectShellCommand, hardBlockedShellCommand } = await import('../../lib/shell-command-classify')
const refusal = rejectShellCommand(command) ?? hardBlockedShellCommand(command)
if (refusal) return refusal
+ const outside = await outsideFolderRefusal(command, args.cwd, run)
+ if (outside) return outside
// Thread the chat context through, or the task starts in LU's own directory
// instead of the workspace the foreground shell tool uses.
const { id } = await bgStart({
@@ -1525,7 +1562,7 @@ async function executeRunTests(args: ToolArgs, run?: AgentRunContext, signal?: A
command,
args: null,
cwd: args.cwd || null,
- timeout: argNumber(args, 'timeout') || 300000,
+ timeout: Math.min(argNumber(args, 'timeout') || 300000, 300000),
shell: null,
...chatCtx(run),
}
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index 7b6415a8..b2718c63 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -2468,6 +2468,15 @@ export function SettingsPage() {
Stops an agent run that keeps repeating the same steps (&quot;Loop guard halted the run&quot;). Off: the run goes on until its step limit or until you press Stop.
</div>
<CreditLimitSettings />
+ {/* CA (14.11.2026, AG10): the shell stays in the agent's folder. */}
+ <InlineToggle
+ label="Let the agent look outside its folder"
+ enabled={settings.agentShellOutsideFolder === true}
+ onChange={() => updateSettings({ agentShellOutsideFolder: settings.agentShellOutsideFolder !== true })}
+ />
+ <div className="t-micro text-gray-500 dark:text-gray-500 leading-relaxed pt-0.5">
+ Off: the agent&apos;s commands stay in its folder and never read your home folder or the rest of the disk. Turn on only for a task that needs it.
+ </div>
{/* C59 A2: the compact profile for local models, on by default. */}
<InlineToggle
label="Short tool list for local models"
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6c43bb07..2543ade7 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -3043,7 +3043,10 @@ export function useAgentChat() {
if (batchVerdict.action === 'halt') {
runState.content =
(runState.content ? runState.content + '\n\n' : '') +
- `_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`
+ (batchVerdict.answer
+ // The search spiral knows its honest end (not found).
+ ? batchVerdict.answer
+ : `_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step tasks, or rephrase the instruction.)_`)
scheduleUIUpdate()
// CA U6: one pass without tools says what is done and what is open.
{
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 04e8fb82..6fd833b1 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2306,7 +2306,11 @@ export function useCodex() {
const batchVerdict = recordedVerdict.action === 'ok' ? narrationVerdict : recordedVerdict
if (batchVerdict.action === 'halt') {
diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })
- const msg = `\n\n_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
+ // The search spiral knows its honest end (not found); every other
+ // halt is a loop and says so.
+ const msg = batchVerdict.answer
+ ? `${fullContent.trim() ? '\n\n' : ''}${batchVerdict.answer}`
+ : `\n\n_(halted: ${batchVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)
{
const summary = (isLocalModelByName(activeModel) ? await finishWithoutTools({ provider, model: modelToUse, messages, signal: abort.signal }) : null)
diff --git a/src/lib/__tests__/the-agent-stays-in-its-folder.test.ts b/src/lib/__tests__/the-agent-stays-in-its-folder.test.ts
new file mode 100644
index 00000000..d0a00bc3
--- /dev/null
+++ b/src/lib/__tests__/the-agent-stays-in-its-folder.test.ts
@@ -0,0 +1,185 @@
+/**
+ * CA, 14.11.2026, bench AG10: a model that could not find a fact in its memory
+ * spent 32 minutes on `find / -maxdepth 6`, `ls /Users/<name>`, greps through
+ * ~/Library/Application Support and `ps aux`, with shell timeouts of 600 s,
+ * and ended with no answer. Three fixes, pinned here:
+ * 1. the shell gate (lib/shell-scope.ts),
+ * 2. the timeout cap,
+ * 3. the search spiral in the loop guard (detector 9).
+ */
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import {
+ cappedShellTimeout, outsideRefusal, scanCodePaths, scanShellPaths, shellReachOutside,
+ SHELL_TIMEOUT_DEFAULT_MS, SHELL_TIMEOUT_MAX_MS, TEST_RUN_TIMEOUT_MAX_MS,
+} from '../shell-scope'
+import { AgentLoopGuard, huntHaltAnswer, isHuntCall } from '../agent-loop-guard'
+
+/** The backend jail, as the tool asks it: inside /work/app or not. */
+const jail = async (p: string) => {
+ const parts: string[] = []
+ for (const seg of p.split('/')) {
+ if (seg === '..') parts.pop()
+ else if (seg && seg !== '.') parts.push(seg)
+ }
+ const full = '/' + parts.join('/')
+ return !(full === '/work/app' || full.startsWith('/work/app/'))
+}
+
+describe('the shell gate', () => {
+ it('lets the folder be the folder', async () => {
+ for (const c of [
+ 'ls -la', 'find . -name "*.json" 2>/dev/null', 'cat src/a.ts | grep x', 'node --test',
+ 'grep -r "/api/v1" src', 'python3 - < script.py', '/usr/bin/env python3 run.py',
+ 'cat /work/app/notes.md', 'git log HEAD~1', 'echo hi > /tmp/x', 'curl https://example.com/a/b',
+ ]) {
+ expect(await shellReachOutside(c, jail), c).toBeNull()
+ }
+ })
+
+ it('refuses the home folder, the disk root and paths outside, as AG10 typed them', async () => {
+ const cases: Array<[string, string]> = [
+ ["find / -maxdepth 6 -iname '*.json' -path '*memor*' 2>/dev/null", 'root'],
+ ['ls -la /Users/someone/ 2>&1 | head -50', 'outside'],
+ ["grep -rliE 'editor|commit' ~/Library/Application\\ Support/lu-vault", 'home'],
+ ['ls -la ~/.lu ~/.config/lu ~/lu 2>/dev/null', 'home'],
+ ['echo HOME=$HOME; whoami', 'home'],
+ ['cat ../../.ssh/id_rsa', 'outside'],
+ ['cat "/etc/hosts"', 'outside'],
+ ['dir %USERPROFILE%\\Documents', 'home'],
+ ['type C:\\Windows\\win.ini', 'outside'],
+ ]
+ for (const [c, why] of cases) {
+ const r = await shellReachOutside(c, jail)
+ expect(r?.why, c).toBe(why)
+ }
+ })
+
+ it('a relative path from a subfolder is judged from there', async () => {
+ expect(await shellReachOutside('cat ../README.md', jail, '/work/app/src')).toBeNull()
+ expect((await shellReachOutside('cat ../../x', jail, '/work/app/src'))?.why).toBe('outside')
+ })
+
+ it('a quoted pattern is not taken for a path, a quoted system path is', () => {
+ expect(scanShellPaths('grep -r "/api/v1" .').check).toEqual([])
+ expect(scanShellPaths("grep x '/Users/a/b'").check).toEqual(['/Users/a/b'])
+ })
+
+ it('the refusal tells the model to stop looking, and where to allow more', () => {
+ const text = outsideRefusal({ path: '/', why: 'root' })
+ expect(text).toMatch(/^Refused:/)
+ expect(text).toMatch(/Settings → Agent/)
+ expect(text).toMatch(/stop searching and say so/)
+ })
+
+ it('code_execute: the home folder and system paths typed into the code', () => {
+ expect(scanCodePaths("import os\nprint(os.listdir(os.path.expanduser('~')))")?.why).toBe('home')
+ expect(scanCodePaths("from pathlib import Path\nPath.home()")?.why).toBe('home')
+ expect(scanCodePaths("open('/etc/passwd').read()")?.why).toBe('outside')
+ expect(scanCodePaths("open('data/a.json').read()")).toBeNull()
+ expect(scanCodePaths("open('/tmp/out.txt','w')")).toBeNull()
+ })
+
+ it('every way into the shell asks the gate, unless the user allowed more', () => {
+ const src = readFileSync('src/api/mcp/builtin-tools.ts', 'utf8')
+ const fn = (name: string) => { const a = src.indexOf(`async function ${name}(`); return src.slice(a, src.indexOf('\n}\n', a)) }
+ const fg = fn('executeShellExecute')
+ // Before the background switch, so `background: true` is no way around it.
+ expect(fg.indexOf('outsideFolderRefusal(command')).toBeGreaterThan(0)
+ expect(fg.indexOf('outsideFolderRefusal(command')).toBeLessThan(fg.indexOf('if (args.background)'))
+ expect(fn('executeShellExecuteBg')).toMatch(/outsideFolderRefusal\(command/)
+ expect(fn('executeCodeExecute')).toMatch(/scanCodePaths\(/)
+ expect(fn('outsideFolderRefusal')).toMatch(/agentShellOutsideFolder === true/)
+ // "Outside" is the backend jail's own answer, the one the file tools get.
+ expect(fn('outsideFolderRefusal')).toMatch(/fs_info/)
+ })
+
+ it('the switch is off unless the user turns it on, and the agent cannot turn it on', async () => {
+ const page = readFileSync('src/components/settings/SettingsPage.tsx', 'utf8')
+ expect(page).toMatch(/enabled=\{settings\.agentShellOutsideFolder === true\}/)
+ const { lockedRule } = await import('../settings-catalog')
+ expect(lockedRule('agentShellOutsideFolder')).toBeTruthy()
+ })
+
+ it('the phone remote runs the same gate in the desktop, always on', () => {
+ const remote = readFileSync('src-tauri/src/commands/remote.rs', 'utf8')
+ expect(remote.match(/crate::shell_scope::refusal\(&command, &root, &here\)/g)?.length).toBe(2)
+ expect(remote).toMatch(/crate::shell_scope::code_refusal\(&code\)/)
+ expect(remote).toMatch(/crate::shell_scope::capped_timeout\(/)
+ })
+})
+
+describe('the timeout cap', () => {
+ it('600 s asked is 120 s given; a test run may have 300 s, never more', () => {
+ expect(cappedShellTimeout(600_000, SHELL_TIMEOUT_DEFAULT_MS)).toBe(SHELL_TIMEOUT_MAX_MS)
+ expect(cappedShellTimeout(undefined, SHELL_TIMEOUT_DEFAULT_MS)).toBe(120_000)
+ expect(cappedShellTimeout(5_000, SHELL_TIMEOUT_DEFAULT_MS)).toBe(5_000)
+ expect(cappedShellTimeout(undefined, 300_000)).toBe(300_000)
+ expect(cappedShellTimeout(3_600_000, 300_000)).toBe(TEST_RUN_TIMEOUT_MAX_MS)
+ })
+})
+
+describe('detector 9: the search spiral', () => {
+ const call = (name: string, args: Record<string, unknown>) => ({ name, args: JSON.stringify(args) })
+ const AG10 = [
+ ...['editor', 'commit message language', 'commit', 'Editor Präferenz', 'Sprache', 'VS Code', 'German', 'git', 'workflow']
+ .map((q) => call('memory', { action: 'search', query: q })),
+ call('file_list', { path: '.' }),
+ call('shell_execute', { command: "pwd; echo '---'; ls -la; git config --list" }),
+ call('shell_execute', { command: "find ~/Library/Application\\ Support -maxdepth 3 -iname '*memor*' 2>/dev/null" }),
+ call('memory', { action: 'search', query: 'commit messages' }),
+ call('memory', { action: 'search', query: 'favourite editor' }),
+ call('shell_execute', { command: "grep -rliE 'editor|commit' ~/Library/Application\\ Support/lu-vault" }),
+ call('shell_execute', { command: "find / -maxdepth 6 -iname '*.json' -path '*memor*' 2>/dev/null | grep -v node" }),
+ call('shell_execute', { command: 'ls -la ~/Library/Application\\ Support/Locally\\ Uncensored\\ ca/' }),
+ call('shell_execute', { command: "find ~/Desktop -maxdepth 4 -iname '*memor*'" }),
+ call('shell_execute', { command: 'ls -la /Users/someone/ 2>&1 | head -50' }),
+ call('shell_execute', { command: "echo HOME=$HOME; whoami; ps aux | grep -iE 'lu|labs'" }),
+ ]
+
+ it('the AG10 run steers at twelve lookups and ends at twenty, with an honest answer', () => {
+ const g = new AgentLoopGuard()
+ const verdicts = AG10.map((c) => g.recordBatch([c]))
+ const steerAt = verdicts.findIndex((v) => v.action === 'steer' && /searched 12 times/.test(v.message))
+ const haltAt = verdicts.findIndex((v) => v.action === 'halt')
+ expect(steerAt).toBe(11)
+ expect(haltAt).toBe(19)
+ const halt = verdicts[haltAt] as { action: 'halt'; reason: string; answer?: string }
+ expect(halt.answer).toBe(huntHaltAnswer(20))
+ expect(halt.answer).toMatch(/^I could not find it\./)
+ })
+
+ it('reading what a search found neither counts nor resets', () => {
+ const g = new AgentLoopGuard()
+ for (let i = 0; i < 11; i++) {
+ g.recordBatch([call('file_search', { path: '.', pattern: `p${i}` })])
+ g.recordBatch([call('file_read', { path: `f${i}.ts` })])
+ }
+ const v = g.recordBatch([call('file_search', { path: '.', pattern: 'p11' })])
+ expect(v.action).toBe('steer')
+ })
+
+ it('an edit or a test run in between is progress: a codebase explored and changed never trips it', () => {
+ const g = new AgentLoopGuard()
+ for (let round = 0; round < 5; round++) {
+ for (let i = 0; i < 9; i++) expect(g.recordBatch([call('file_search', { path: 'src', pattern: `r${round}n${i}` })]).action).toBe('ok')
+ expect(g.recordBatch([call('file_edit', { path: `src/m${round}.ts`, old_string: 'a', new_string: 'b' })]).action).toBe('ok')
+ expect(g.recordBatch([call('shell_execute', { command: 'npm test' })]).action).toBe('ok')
+ }
+ })
+
+ it('what counts as only looking', () => {
+ expect(isHuntCall('memory', JSON.stringify({ action: 'search', query: 'x' }))).toBe(true)
+ expect(isHuntCall('memory', JSON.stringify({ action: 'add', content: 'x' }))).toBe(false)
+ expect(isHuntCall('shell_execute', JSON.stringify({ command: 'find . -name x 2>/dev/null' }))).toBe(true)
+ expect(isHuntCall('shell_execute', JSON.stringify({ command: 'ls > list.txt' }))).toBe(false)
+ expect(isHuntCall('shell_execute', JSON.stringify({ command: 'npm test' }))).toBe(false)
+ expect(isHuntCall('file_write', JSON.stringify({ path: 'a', content: 'b' }))).toBe(false)
+ })
+
+ it('all three loops end a spiral with its answer instead of "the model is looping"', () => {
+ expect(readFileSync('src/hooks/useAgentChat.ts', 'utf8')).toMatch(/batchVerdict\.answer\s*\n?\s*\/\/[^\n]*\n\s*\? batchVerdict\.answer/)
+ expect(readFileSync('src/hooks/useCodex.ts', 'utf8')).toMatch(/const msg = batchVerdict\.answer/)
+ expect(readFileSync('src/mobile/remote/remoteAgent.ts', 'utf8')).toMatch(/if \(verdict\.answer\) return finish\('done'/)
+ })
+})
diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.ts
index 4d0b6c68..502ddfdd 100644
--- a/src/lib/agent-loop-guard.ts
+++ b/src/lib/agent-loop-guard.ts
@@ -89,7 +89,9 @@
export type LoopGuardVerdict =
| { action: 'ok' }
| { action: 'steer'; message: string }
- | { action: 'halt'; reason: string }
+ /** `answer`: what the run says instead of "the model is looping", where the
+ * guard knows the honest outcome (the search spiral: not found). */
+ | { action: 'halt'; reason: string; answer?: string }
const CONSECUTIVE_HALT_AT = 3
const BATCH_WINDOW = 6
@@ -145,6 +147,46 @@ const SEARCH_TOOLS = new Set<string>(['web_search'])
const SEARCH_STEER_AT = 6
const SEARCH_HALT_AT = 12
+/**
+ * Detector 9: the search spiral (CA, 14.11.2026, bench AG10). A model that
+ * could not find a fact searched its memory nine times with nine different
+ * words, then ran about twenty different shell searches across the disk, for
+ * 32 minutes, and gave no answer. No call was a repeat and no two were alike
+ * enough for detector 8. What they shared: each only looked, and nothing was
+ * written or run in between. Lookups since the last call that changed or ran
+ * something are counted (file_read neither counts nor resets: reading what a
+ * search found is the normal next step, and a hunt reads too). Twelve steer the
+ * model to act on what it found or say what it could not find; twenty end the
+ * run with an honest "not found" instead of silence. Wide on purpose: a model
+ * exploring a large codebase greps a lot before its first edit.
+ */
+const HUNT_STEER_AT = 12
+const HUNT_HALT_AT = 20
+const HUNT_TOOLS = new Set<string>(['file_search', 'file_list', 'session_search', 'memory_search', 'web_search', 'tool_search'])
+const HUNT_SHELL = /(^|[\s;|&(`$])(find|grep|egrep|rg|ag|ls|locate|mdfind|ps|whoami|cat|head|tail|tree|du|stat|echo|printenv|env|which|type)(\s|$)/
+// A program in command position (start, or after ; & | ( or `), so `grep -v node`
+// is still a lookup and `npm test` is not.
+const HUNT_SHELL_WRITES = /(^|[^2&])>|(^|[;&|(`]\s*)(sudo\s+)?(rm|mv|cp|mkdir|touch|tee|chmod|chown|ln|npm|npx|pnpm|yarn|bun|node|python3?|pip3?|pytest|jest|vitest|make|cargo|go|curl|wget|git\s+(commit|add|push|checkout|reset|merge|rebase|apply|stash|clone|pull))\b|\bsed\s+-i|\bxargs\b/
+const HUNT_NEUTRAL = new Set<string>(['file_read', 'todo_write', 'get_current_time'])
+
+/** A call that only looks for something. */
+export function isHuntCall(name: string, argsJson: string): boolean {
+ if (HUNT_TOOLS.has(name)) return true
+ let a: Record<string, unknown> = {}
+ try { a = JSON.parse(argsJson) as Record<string, unknown> } catch { /* not an object */ }
+ if (name === 'memory') return /^(search|list|get|recall|find)$/i.test(String(a?.action ?? ''))
+ if (name === 'shell_execute') {
+ const command = typeof a?.command === 'string' ? a.command : ''
+ return !!command && HUNT_SHELL.test(command) && !HUNT_SHELL_WRITES.test(command)
+ }
+ return false
+}
+
+/** The run's end when the spiral halts: plain, and honest about it. */
+export function huntHaltAnswer(n: number): string {
+ return `I could not find it. I looked ${n} times (memory, files and searches) without finding anything, so I stopped instead of searching further. If you know where it is, tell me and I will look there.`
+}
+
/**
* Detector 8 (C83). Five silent near-copies in a row get one word, eight end
* the run. In the incident that is 8 calls instead of 233.
@@ -313,6 +355,9 @@ export class AgentLoopGuard {
/** Reads whose capped result was already forgiven once (detector 3). */
private trimForgiven = new Set<string>()
+ /** Detector 9: lookups since the last call that changed or ran something. */
+ private huntCount = 0
+ private huntSteered = false
/**
* Record one iteration's tool-call batch BEFORE executing it. `args` must
@@ -333,6 +378,42 @@ export class AgentLoopGuard {
opts: { trimmedReadKeys?: ReadonlySet<string> } = {},
): LoopGuardVerdict {
if (!this.enabled || calls.length === 0) return { action: 'ok' }
+ const hunt = this.recordHunt(calls)
+ const v = this.recordBatchDetectors(calls, opts)
+ if (v.action === 'halt') return v
+ if (hunt.action === 'halt') return hunt
+ return v.action === 'steer' ? v : hunt
+ }
+
+ /** Detector 9, the search spiral (see HUNT_STEER_AT). */
+ private recordHunt(calls: Array<{ name: string; args: string }>): LoopGuardVerdict {
+ for (const c of calls) {
+ if (HUNT_NEUTRAL.has(c.name)) continue
+ if (isHuntCall(c.name, c.args)) this.huntCount++
+ else { this.huntCount = 0; this.huntSteered = false }
+ }
+ if (this.huntCount >= HUNT_HALT_AT) {
+ return {
+ action: 'halt',
+ reason: `${this.huntCount} searches in a row without finding or changing anything`,
+ answer: huntHaltAnswer(this.huntCount),
+ }
+ }
+ if (this.huntCount >= HUNT_STEER_AT && !this.huntSteered) {
+ this.huntSteered = true
+ return {
+ action: 'steer',
+ message: `You have searched ${this.huntCount} times in a row without changing anything. `
+ + 'If you have found what you need, act on it now. If it is not there, stop searching and say plainly what you could not find. Do not search outside your folder.',
+ }
+ }
+ return { action: 'ok' }
+ }
+
+ private recordBatchDetectors(
+ calls: Array<{ name: string; args: string }>,
+ opts: { trimmedReadKeys?: ReadonlySet<string> },
+ ): LoopGuardVerdict {
// browser_scroll (P-L, C53) repeats its arguments by design: every call
// moves the page and its answer names the new position. A batch of
// nothing but scrolls is therefore not a repeat; it gets its own, wider
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 5137da75..9f422c02 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -63,6 +63,8 @@ export const DEFAULT_SETTINGS: Settings = {
agentMaxToolCalls: 400,
agentMaxIterations: 200,
agentLoopGuard: true,
+ // CA (14.11.2026, AG10): the agent's shell stays in its folder (lib/shell-scope.ts).
+ agentShellOutsideFolder: false,
agentCompactAuto: true,
// Die heutigen festen Werte aus sub-agent.ts, unveraendert uebernommen:
// wer nichts einstellt, bekommt exakt das Verhalten von 2.6.7.
diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.ts
index fafe1918..53a29459 100644
--- a/src/lib/settings-catalog.ts
+++ b/src/lib/settings-catalog.ts
@@ -455,7 +455,7 @@ export const LOCK_RULES: readonly LockRule[] = [
},
{
category: 'permissions', what: 'Permissions', where: 'the permission bar of the chat or Settings → Agent',
- names: ['permissions', 'toolPermissions', 'sandboxLevel', 'bypass', 'autoApprove', 'perToolOverrides'],
+ names: ['permissions', 'toolPermissions', 'sandboxLevel', 'bypass', 'autoApprove', 'perToolOverrides', 'agentShellOutsideFolder'],
pattern: /permission|sandbox|bypass|autoapprove|allowall|trust/,
},
{
diff --git a/src/lib/settings-reset.ts b/src/lib/settings-reset.ts
index 5b2daba1..18396dfa 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', 'agentCompactAuto',
+ 'agentMaxToolCalls', 'agentMaxIterations', 'agentLoopGuard', 'agentCompactAuto', 'agentShellOutsideFolder',
'subAgentMaxToolCalls', 'subAgentMaxIterations', 'loopMaxPasses',
'searchProvider', 'braveApiKey', 'tavilyApiKey', 'exaApiKey', 'searchUserAgent', 'webStrictUrls',
'codexArchitectMode', 'codexArchitectModel', 'codexArchitectAllowCloud',
diff --git a/src/lib/shell-scope.ts b/src/lib/shell-scope.ts
new file mode 100644
index 00000000..cba911cc
--- /dev/null
+++ b/src/lib/shell-scope.ts
@@ -0,0 +1,148 @@
+/**
+ * The agent's shell stays inside its folder (CA, 14.11.2026, AG10).
+ *
+ * The file tools were always jailed to the workspace by the backend
+ * (filesystem.rs, "Path escapes the allowed workspace"). The shell was not: it
+ * starts in the folder, and from there a command can read anything the user
+ * can. In a measured run (DeepSeek v4.1 Flash, AG10) a model that could not
+ * find a fact in its memory spent 32 minutes on `find / -maxdepth 6`,
+ * `ls /Users/<name>`, greps through ~/Library/Application Support and
+ * `ps aux`, then gave no answer at all.
+ *
+ * This is the front gate for that: before a command runs, every path in it is
+ * looked at. Home (`~`, `$HOME`, `%USERPROFILE%`), the file-system root and
+ * absolute paths outside the folder are refused, unless the user allowed the
+ * agent outside its folder in Settings → Agent. Absolute paths are judged by
+ * the same backend jail the file tools use, so "inside" means exactly the
+ * same thing for both.
+ *
+ * It reads the command, it does not sandbox the process: a command that hides
+ * a path from it (built from variables, base64) still runs. It stops what the
+ * models actually do, which is to type the path.
+ */
+
+/** Where a command may point without asking: devices, temp, system programs. */
+const ALWAYS_FINE = [
+ /^\/dev\/(null|stdin|stdout|stderr|tty|zero|u?random)$/,
+ /^\/(private\/)?tmp(\/|$)/,
+ /^\/var\/folders\//,
+ /^\/(usr\/(local\/)?|opt\/homebrew\/)?s?bin\//,
+ /^\/usr\/bin\/env$/,
+]
+
+/** A quoted string that starts with one of these is a path, not a pattern. */
+const SYSTEM_TOP = /^\/(Users|home|root|Volumes|mnt|media|etc|var|private|Library|System|Applications|opt|srv|proc|sys)(\/|$)/
+
+const HOME_REF = /(^|[\s=:"'(])~(?=[/\s"')]|$)|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|%APPDATA%|%LOCALAPPDATA%|\$env:(USERPROFILE|HOME|APPDATA|LOCALAPPDATA)/i
+
+export interface OutsideReach {
+ /** What the command points at, as the model wrote it. */
+ path: string
+ why: 'home' | 'root' | 'outside'
+}
+
+/** Words of a command with their quoting kept apart. Rough on purpose. */
+function words(command: string): Array<{ text: string; quoted: boolean }> {
+ const out: Array<{ text: string; quoted: boolean }> = []
+ const re = /"([^"]*)"|'([^']*)'|([^\s;|&()<>]+)/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(command))) {
+ if (m[1] !== undefined) out.push({ text: m[1], quoted: true })
+ else if (m[2] !== undefined) out.push({ text: m[2], quoted: true })
+ else out.push({ text: m[3], quoted: false })
+ }
+ return out
+}
+
+/** The path inside a word: the word itself, or what follows `--opt=` / `-I`. */
+function pathIn(word: string): string | null {
+ const w = word.replace(/^[0-9]?>>?/, '')
+ const eq = w.match(/^-{1,2}[\w-]+=(.+)$/)
+ const v = eq ? eq[1] : w
+ if (/^\/|^[A-Za-z]:[\\/]|^\\\\/.test(v)) return v
+ if (/(^|[\\/])\.\.([\\/]|$)/.test(v)) return v
+ return null
+}
+
+/**
+ * Paths in a command that point outside the folder for sure (home, root), and
+ * candidates the backend jail has to judge (absolute paths, `..`).
+ */
+export function scanShellPaths(command: string): { sure: OutsideReach[]; check: string[] } {
+ const sure: OutsideReach[] = []
+ const check: string[] = []
+ const home = command.match(HOME_REF)
+ if (home) sure.push({ path: home[0].trim(), why: 'home' })
+ for (const { text, quoted } of words(command)) {
+ const p = pathIn(text)
+ if (!p) continue
+ if (p === '/' || /^[A-Za-z]:[\\/]?$/.test(p)) { sure.push({ path: p, why: 'root' }); continue }
+ if (ALWAYS_FINE.some((r) => r.test(p))) continue
+ // A quoted "/api/v1" is a search pattern far more often than a path.
+ if (quoted && p.startsWith('/') && !SYSTEM_TOP.test(p)) continue
+ // URLs are not paths.
+ if (/^[a-z]+:\/\//i.test(p)) continue
+ check.push(p)
+ }
+ return { sure, check: [...new Set(check)] }
+}
+
+/**
+ * The first place the command reaches outside the folder, or null.
+ * `isOutside` is the backend jail's answer for one path (relative paths are
+ * taken from `cwd` when the command runs in a subfolder).
+ */
+export async function shellReachOutside(
+ command: string,
+ isOutside: (path: string) => Promise<boolean>,
+ cwd?: string,
+): Promise<OutsideReach | null> {
+ const { sure, check } = scanShellPaths(command)
+ if (sure.length) return sure[0]
+ for (const p of check) {
+ const full = cwd && !/^\/|^[A-Za-z]:[\\/]|^\\\\/.test(p) ? `${cwd.replace(/[\\/]+$/, '')}/${p}` : p
+ if (await isOutside(full)) return { path: p, why: 'outside' }
+ }
+ return null
+}
+
+/** What the model reads when the gate refuses. Tells it to stop looking. */
+export function outsideRefusal(reach: OutsideReach): string {
+ const where = reach.why === 'home' ? 'the home folder' : reach.why === 'root' ? 'the whole disk' : `"${reach.path}", outside your folder`
+ return `Refused: this command reaches ${where}. You work only inside your folder; the user can allow more in Settings → Agent. `
+ + 'Use paths inside the folder. If what you need is not there, stop searching and say so in your answer.'
+}
+
+/**
+ * Python code for code_execute, the same idea: the home folder and absolute
+ * system paths typed into the code.
+ */
+export function scanCodePaths(code: string): OutsideReach | null {
+ const home = code.match(/expanduser\(|Path\.home\(|os\.environ(\.get)?\(?\[?["']HOME["']|getenv\(["']HOME["']|\$\{?HOME\}?|["']~\//)
+ if (home) return { path: home[0], why: 'home' }
+ const re = /["'](\/[^"'\n]*)["']/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(code))) {
+ const p = m[1]
+ if (p === '/') return { path: p, why: 'root' }
+ if (SYSTEM_TOP.test(p) && !ALWAYS_FINE.some((r) => r.test(p))) return { path: p, why: 'outside' }
+ }
+ return null
+}
+
+/** Shell timeouts (CA, 14.11.2026): a model asked for 600 s per `find /`. */
+export const SHELL_TIMEOUT_DEFAULT_MS = 120_000
+/** Test runs keep their longer budget; nothing else gets more than this. */
+export const SHELL_TIMEOUT_MAX_MS = 120_000
+export const TEST_RUN_TIMEOUT_MAX_MS = 300_000
+
+/**
+ * The timeout a command runs with. What the model asks for is a wish below the
+ * cap; a recognised test run may use the test budget.
+ */
+export function cappedShellTimeout(requested: number | undefined, kindDefault: number): number {
+ const isTestBudget = kindDefault > SHELL_TIMEOUT_DEFAULT_MS
+ const cap = isTestBudget ? TEST_RUN_TIMEOUT_MAX_MS : SHELL_TIMEOUT_MAX_MS
+ const want = requested && requested > 0 ? requested : kindDefault
+ return Math.min(Math.max(want, 1_000), cap)
+}
diff --git a/src/mobile/remote/remoteAgent.ts b/src/mobile/remote/remoteAgent.ts
index 70689366..28522b19 100644
--- a/src/mobile/remote/remoteAgent.ts
+++ b/src/mobile/remote/remoteAgent.ts
@@ -498,7 +498,11 @@ export async function runRemoteAgentLoop(run: RemoteAgentRun): Promise<RemoteAge
const verdict = said.action === 'halt'
? said
: guard.recordBatch(calls.map((c) => ({ name: c.function.name, args: JSON.stringify(c.function.arguments ?? {}) })))
- if (verdict.action === 'halt') return finish('looping', lastContent)
+ if (verdict.action === 'halt') {
+ // The search spiral ends with an honest "not found" as the answer.
+ if (verdict.answer) return finish('done', [lastContent, verdict.answer].filter((x) => x.trim()).join('\n\n'))
+ return finish('looping', lastContent)
+ }
pendingSteer = verdict.action === 'steer' ? verdict.message : said.action === 'steer' ? said.message : null
}
messages.push({
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 533345a9..910d5a34 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -191,6 +191,10 @@ export interface Settings {
agentLoopGuard?: boolean
/** CA (14.11.2026): credits one agent task may use before it pauses and
* asks (LU Cloud, lib/agent-cost-brake.ts). 0 = no limit. */
+ /** CA (14.11.2026, AG10): the agent's shell may reach outside its folder
+ * (home, other folders, the whole disk). Off unless the user turns it on;
+ * locked from the agent (settings-catalog, 'paths'). lib/shell-scope.ts. */
+ agentShellOutsideFolder?: boolean
agentRunCreditLimit?: number
/** Credits all agent runs together may use in a rolling hour. 0 = no limit. */
agentHourCreditLimit?: number