Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(tools): use installed ripgrep for native file search (#5948)
chengyongrue0b8efa0beff
diff --git a/docs/configuration.md b/docs/configuration.mdindex 78d2d8645..73b16cca0 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -42,6 +42,7 @@ the focused guides first and come back here for exact fields and defaults.| Add fallback chains | [Model Fallbacks](#model-fallbacks) || Configure voice transcription | [Transcription Settings](#transcription-settings) || Tune channel defaults | [Channel Settings](#channel-settings) |+| Configure local file search | [File Search](#file-search) || Configure web search and fetch | [Web Tools](#web-tools) || Enable image generation | [Image Generation](#image-generation) || Add MCP servers | [MCP](#mcp-model-context-protocol) |@@ -1688,6 +1689,10 @@ When a channel `send()` raises, nanobot retries at the channel-manager layer. By>> If a channel is completely unreachable, nanobot cannot notify the user through that same channel. Watch logs for `Failed to send to {channel} after N attempts` to spot persistent delivery failures.+## File Search++When ripgrep (`rg`) is installed, nanobot automatically uses it in place of the built-in `grep` and `find_files` tools.+## Web Toolsnanobot incorporates basic tools for accessing the web. These include searching via APIs, and fetching arbitrary web pages in Markdown format. They are enabled by default, and can be configured in `~/.nanobot/config.json` under `tools.web`.diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.pyindex 3fc9ed541..bfc52d5bd 100644--- a/nanobot/agent/tools/exec_session.py+++ b/nanobot/agent/tools/exec_session.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport codecs+import shleximport timeimport uuidfrom collections import deque@@ -280,7 +281,7 @@ class ExecSessionManager:async def start(self,*,- command: str,+ command: str | list[str],cwd: str,env: dict[str, str],timeout: int | None,@@ -301,7 +302,7 @@ class ExecSessionManager:session = _ExecSession(session_id=session_id,process=process,- command=command,+ command=shlex.join(command) if isinstance(command, list) else command,cwd=cwd,timeout=timeout,owner_session_key=owner_session_key,@@ -445,7 +446,7 @@ class ExecSessionManager:async def _spawn(self,- command: str,+ command: str | list[str],cwd: str,env: dict[str, str],shell_program: str | None,diff --git a/nanobot/agent/tools/loader.py b/nanobot/agent/tools/loader.pyindex 85cc8283d..4fb2aaca3 100644--- a/nanobot/agent/tools/loader.py+++ b/nanobot/agent/tools/loader.py@@ -121,6 +121,12 @@ class ToolLoader:builtin_names.add(tool.name)except Exception:logger.exception("Failed to register tool: %s", cls_label)+ if not is_plugin_source and "rg" in builtin_names:+ replaced = builtin_names & {"grep", "find_files"}+ for name in replaced:+ registry.unregister(name)+ registered = [name for name in registered if name not in replaced]+ builtin_names.difference_update(replaced)return registereddiff --git a/nanobot/agent/tools/rg.py b/nanobot/agent/tools/rg.pynew file mode 100644index 000000000..d6c99dbac--- /dev/null+++ b/nanobot/agent/tools/rg.py@@ -0,0 +1,56 @@+"""Installed ripgrep with native arguments and shared process controls."""++# pyright: reportIncompatibleMethodOverride=false++from __future__ import annotations++import os+import shutil+from typing import Any++from nanobot.agent.tools.base import ToolResult+from nanobot.agent.tools.context import ToolContext+from nanobot.agent.tools.shell import ExecTool+++class RgTool(ExecTool):+ @classmethod+ def enabled(cls, ctx: ToolContext) -> bool:+ if not ctx.config.file.enable or not super().enabled(ctx):+ return False+ cfg = ctx.config.exec+ path = os.pathsep.join(part for part in (+ cfg.path_prepend, os.environ.get("PATH", ""), cfg.path_append,+ ) if part)+ return shutil.which("rg", path=path) is not None++ @property+ def name(self) -> str:+ return "rg"++ @property+ def description(self) -> str:+ return (+ "Search file contents and discover files with ripgrep. "+ "Accepts native rg arguments as an array of strings."+ )++ @property+ def parameters(self) -> dict[str, Any]:+ schema = super().parameters+ properties = schema["properties"]+ for name in ("command", "cmd", "shell", "login"):+ properties.pop(name, None)+ properties["args"] = {+ "type": "array", "items": {"type": "string"}, "minItems": 1,+ "description": "Native rg arguments, with each argument as one array element",+ }+ schema["required"] = ["args"]+ return schema++ async def execute(self, args: list[str], **kwargs: Any) -> str:+ if not args:+ return ToolResult.error("Error: Provide rg arguments, such as --help or --files.")+ for name in ("command", "cmd", "shell", "login"):+ kwargs.pop(name, None)+ return await super().execute(command=["rg", *args], **kwargs)diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.pyindex 89bc4a81f..59b6bfb8c 100644--- a/nanobot/agent/tools/shell.py+++ b/nanobot/agent/tools/shell.py@@ -107,7 +107,7 @@ class ExecToolConfig(Base):@dataclass(slots=True)class _PreparedCommand:- command: str+ command: str | list[str]cwd: strenv: dict[str, str]timeout: int | None@@ -272,7 +272,7 @@ class ExecTool(Tool):return Trueasync def execute(- self, command: str | None = None, cmd: str | None = None,+ self, command: str | list[str] | None = None, cmd: str | None = None,working_dir: str | None = None, workdir: str | None = None,timeout: int | None = None, shell: str | None = None,login: bool | None = None, yield_time_ms: int | None = None,@@ -399,7 +399,7 @@ class ExecTool(Tool):def _prepare_command(self,- command: str,+ command: str | list[str],working_dir: str | None = None,timeout: int | None = None,shell: str | None = None,@@ -445,7 +445,7 @@ class ExecTool(Tool):# continuing to block commands after workspace restriction is disabled.if access.restrict_to_workspace:guard_error = self._guard_command(- command,+ shlex.join(command) if isinstance(command, list) else command,cwd,restrict_to_workspace=True,workspace_root=workspace_root,@@ -461,21 +461,22 @@ class ExecTool(Tool):)else:workspace = workspace_root or cwd- command = wrap_command(+ wrapped = wrap_command(self.sandbox,- command,+ shlex.join(command) if isinstance(command, list) else command,workspace,cwd,sandbox_ro_binds=[str(p) for p in self.sandbox_ro_binds],sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds],)+ command = shlex.split(wrapped) if isinstance(command, list) else wrappedcwd = str(Path(workspace).resolve())effective_timeout = self._resolve_timeout(timeout)env = self._build_env()if self.path_prepend or self.path_append:- if _IS_WINDOWS:+ if _IS_WINDOWS or isinstance(command, list):env["PATH"] = self._compose_path(env.get("PATH", ""))else:command = self._wrap_path_export(command, env)@@ -517,14 +518,43 @@ class ExecTool(Tool):@staticmethodasync def _spawn(- command: str, cwd: str, env: dict[str, str],+ command: str | list[str], cwd: str, env: dict[str, str],shell_program: str | None = None,login: bool = False,*,stdin: int = asyncio.subprocess.DEVNULL,process_tree: bool = False,) -> asyncio.subprocess.Process:- """Launch *command* in a platform-appropriate shell."""+ """Launch an argument vector directly or a command string through a shell."""+ if isinstance(command, list):+ executable = shutil.which(command[0], path=env.get("PATH", ""))+ if executable is None:+ raise FileNotFoundError(f"Executable not found: {command[0]}")+ windows_job = None+ process = None+ try:+ if process_tree and sys.platform == "win32":+ windows_job = ExecTool._create_windows_job()+ process = await asyncio.create_subprocess_exec(+ executable, *command[1:],+ stdin=stdin,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=cwd,+ env=env,+ creationflags=windows_job.creation_flags if windows_job else 0,+ start_new_session=process_tree and sys.platform != "win32",+ )+ if windows_job is not None:+ windows_job.assign_and_resume(process.pid)+ setattr(process, _PROCESS_TREE_OWNER_ATTR, windows_job)+ return process+ except BaseException:+ if windows_job is not None:+ windows_job.terminate()+ if process is not None:+ await ExecTool._kill_process(process)+ raiseif _IS_WINDOWS:windows_job = Noneprocess = Nonediff --git a/nanobot/skills/memory/SKILL.md b/nanobot/skills/memory/SKILL.mdindex e71bf4dd0..2f2372985 100644--- a/nanobot/skills/memory/SKILL.md+++ b/nanobot/skills/memory/SKILL.md@@ -7,14 +7,8 @@ description: Search past conversations in the agent's history log.## Search Past Events-Search the exact `History log` path from the system prompt with `grep`; a project-relative-`memory/history.jsonl` may belong to a different workspace. The log is append-only JSONL,-with `cursor`, `timestamp`, and `content` per entry, and is not loaded into context.+Search the exact `History log` path from the system prompt using an available text-search+tool. This path belongs to the agent workspace, which can differ from the current project.-Start broad searches with `output_mode="count"`, then narrow by topic or date and request-matching content. Use `fixed_strings=true` for literal timestamps or JSON fragments.-Page long results with `head_limit` / `offset` and use `context_before` / `context_after`-when nearby entries matter.--Example (replace `<history-log-path>` with the path from the system prompt):-`grep(pattern="project-name", path="<history-log-path>", output_mode="content", case_insensitive=true, head_limit=20)`+The append-only JSONL log stores `cursor`, `timestamp`, and `content` per entry. Retrieve+entries on demand by topic or date, and inspect neighboring entries when context matters.diff --git a/nanobot/templates/agent/identity.md b/nanobot/templates/agent/identity.mdindex e680f7e53..8ca90c663 100644--- a/nanobot/templates/agent/identity.md+++ b/nanobot/templates/agent/identity.md@@ -6,12 +6,12 @@Nanobot's agent workspace is at: {{ agent_workspace_path }}- Agent profile: {{ agent_workspace_path }}/SOUL.md and {{ agent_workspace_path }}/USER.md- Long-term memory: {{ agent_workspace_path }}/memory/MEMORY.md-- History log: {{ agent_workspace_path }}/memory/history.jsonl (append-only JSONL; prefer built-in `grep` for search).+- History log: {{ agent_workspace_path }}/memory/history.jsonl (append-only JSONL).- Custom skills: {{ agent_workspace_path }}/skills/{% raw %}{skill-name}{% endraw %}/SKILL.md{% else %}- Agent profile: SOUL.md and USER.md- Long-term memory: memory/MEMORY.md-- History log: memory/history.jsonl (append-only JSONL; prefer built-in `grep` for search).+- History log: memory/history.jsonl (append-only JSONL).- Custom skills: skills/{% raw %}{skill-name}{% endraw %}/SKILL.md{% endif %}diff --git a/nanobot/templates/agent/tool_contract.md b/nanobot/templates/agent/tool_contract.mdindex 445c3a80f..e34586745 100644--- a/nanobot/templates/agent/tool_contract.md+++ b/nanobot/templates/agent/tool_contract.md@@ -1,77 +1,5 @@# Tool Usage Notes-## General Tool Contract--- Use the narrowest structured tool that directly matches the task.-- Use read-only discovery before writes when state is uncertain.-- Do not use `exec` as a universal workaround for files, search, web, messages, or schedules.-- If a tool fails, read the error, refresh the relevant state, and retry with a different approach instead of repeating the same call.-- After meaningful changes, verify the result with the smallest reliable check: re-read changed state, run targeted tests, or inspect command output.-- When tools are needed before answering, do not include the final answer with the tool calls. Wait for the tool results, then answer once.-- Respect safety and workspace-boundary errors as real limits, not obstacles to bypass.-- Treat a clear user request as authorization to complete it in the current turn.-- For multi-step tasks, outline the plan briefly and then execute it. Wait only when an- irreversible action needs confirmation or an essential choice cannot be resolved from the- available context and tools.-- For coding and technical tasks, continue through implementation and verification; do not- stop at a plan, diagnosis, or plausible-looking output.--## Discovery and Reading--- Use `find_files` or `list_dir` for uncertain paths, `grep` for content, and `read_file` for a known path.-- `grep` returns matches with five context lines by default; use `files_with_matches` for paths or `count` for totals.-- Use `fixed_strings=true` for literal keywords containing regex characters.-- Use `head_limit` and `offset` to page across large result sets.-- Search tools enforce binary and file-size limits and report skipped files in the result.--## File and Coding Workflows--- For code or config changes, the default loop is: locate (`find_files`/`grep`), inspect (`read_file`), edit (`apply_patch`), then verify (`exec` or re-read).-- Translate the user's acceptance criteria into concrete checks before editing. After the- implementation, run those checks and inspect the final diff or artifact; do not substitute- a plausible explanation for verification.-- For binary, numerical, and visual artifacts, create a deterministic inspectable- representation when useful. Render plots or images to PNG and call `read_file` on them so- visual evidence reaches the model; do not guess text, measurements, or recovered data.-- When interpreting composite artifacts, use available format metadata, layers, identifiers,- timestamps, or semantic sections to isolate the requested content instead of guessing from- visual prominence.-- Never invent missing records or measurements. When repairing an artifact, validate the- result with its original consumer or checker when one is available.-- Use `apply_patch` as the default code editing tool, especially for multi-file changes, structural edits, generated code, moves, adds, or deletes.-- Use `apply_patch dry_run=true` when the patch is uncertain and you want validation plus a change summary before writing.-- Use `edit_file` only for small exact replacements in one file, with `old_text` copied from `read_file`.-- Use `write_file` for new files or intentional full-file rewrites, not routine partial edits.-- If `apply_patch` or `edit_file` fails, re-read with `force=true`, narrow the context, and try a smaller patch rather than switching to shell `sed` or `echo`.--## Process Execution--- Use `exec` for processes, not file inspection or editing.-- For interaction or early output, set `yield_time_ms` and continue with `exec_session` (`until_exit=true` when no further input is needed).-- Use `list_exec_sessions` to recover session IDs.--## CLI App Attachments--- When Runtime Context lists a `CLI App Attachment` or `CLI App Mention`, treat the `@name` as an app capability the user intentionally attached to the current turn.-- If the task may need app-specific behavior, read the listed skill first, then call `run_cli_app` with that `name`.-- Do not run an attached CLI app through shell or generic process tools unless the user explicitly asks for that lower-level path.-- If the app CLI is missing, lacks local desktop/app/API prerequisites, or cannot complete the requested action, explain that concrete blocker and what was attempted.--## Web and External Information--- Use web tools when the user asks for current information, a specific URL, or information likely to have changed.-- Use `web_search` to find sources and `web_fetch` for a specific page or result that needs closer reading.-- Do not invent freshness-sensitive facts when tools can verify them.--## Messaging and Media--- Reply directly with text for the current conversation. Do not use the 'message' tool for normal replies in the current chat.-- Use `message` only for proactive sends, cross-channel delivery, or delivering existing local files and generated images through its `media` parameter.-- `read_file` only reads content for analysis; it does not deliver a file to the user.-- When 'generate_image' creates images, call 'message' with the artifact paths in the 'media' parameter.--## Scheduling and Background Work--- Use `cron` for scheduled reminders or recurring jobs; do not run `nanobot cron` through `exec`.-- For heartbeat tasks, update `HEARTBEAT.md`; the default gateway heartbeat cron job handles periodic checks when enabled.-- Do not write reminders only to memory files when the user expects an actual notification.+- Treat a clear user request as authorization to complete the task, including execution and verification.+- Ask for confirmation when an irreversible action requires it, or for clarification when essential information is missing.+- Wait for tool results before writing the final answer.diff --git a/nanobot/utils/tool_hints.py b/nanobot/utils/tool_hints.pyindex cb5dd6854..1146aed33 100644--- a/nanobot/utils/tool_hints.py+++ b/nanobot/utils/tool_hints.py@@ -2,6 +2,7 @@from __future__ import annotations+import jsonimport refrom typing import cast@@ -15,6 +16,7 @@ _TOOL_FORMATS: dict[str, tuple[list[str], str, bool, bool]] = {"edit": (["file_path", "path"], "edit {}", True, False),"find_files": (["query", "glob", "path"], "find {}", False, False),"grep": (["pattern"], 'grep "{}"', False, False),+ "rg": (["args"], "rg {}", False, False),"exec": (["command"], "$ {}", False, True),"list_exec_sessions": ([], "exec sessions", False, False),"web_search": (["query"], 'search "{}"', False, False),@@ -87,6 +89,12 @@ def _extract_arg(tc: ToolCallRequest, key_args: list[str]) -> str | None:val = args.get(key)if isinstance(val, str) and val:return val+ if key == "args" and isinstance(val, list) and val:+ return " ".join(+ arg if isinstance(arg, str) and arg and not re.search(r"[\s\"']", arg)+ else json.dumps(arg, ensure_ascii=False)+ for arg in cast(list[object], val)+ )for val in args.values():if isinstance(val, str) and val:return valdiff --git a/tests/agent/test_context_builder.py b/tests/agent/test_context_builder.pyindex 5f8611dc4..16c11126b 100644--- a/tests/agent/test_context_builder.py+++ b/tests/agent/test_context_builder.py@@ -207,33 +207,23 @@ class TestIsTemplateContent:class TestBundledToolContract:- def test_tool_contract_balances_general_and_coding_workflows(self):+ def test_tool_contract_contains_shared_execution_policy(self):from importlib.resources import files as pkg_filestpl = pkg_files("nanobot") / "templates" / "agent" / "tool_contract.md"content = tpl.read_text(encoding="utf-8")- assert "## General Tool Contract" in content- assert "Use the narrowest structured tool" in content- assert "Do not use `exec` as a universal workaround" in content- assert "## File and Coding Workflows" in content- assert "`grep` returns matches with five context lines by default" in content- assert "apply_patch" in content- assert "acceptance criteria into concrete checks" in content- assert "visual evidence reaches the model" in contentassert "clear user request as authorization" in content- assert "Never invent missing records or measurements" in content- assert "## Web and External Information" in content- assert "## Messaging and Media" in content- assert "## Scheduling and Background Work" in content+ assert "execution and verification" in content+ assert "irreversible action" in content+ assert "Wait for tool results" in contentdef test_tool_contract_is_injected_without_workspace_file(self, tmp_path):builder = _builder(tmp_path)prompt = builder.build_system_prompt()assert "# Tool Usage Notes" in prompt- assert "## General Tool Contract" in prompt- assert "Do not use `exec` as a universal workaround" in prompt+ assert "clear user request as authorization" in prompt# ---------------------------------------------------------------------------@@ -305,7 +295,6 @@ class TestBuildSystemPrompt:def test_default_identity_uses_relative_agent_paths(self, tmp_path):result = ContextBuilder(tmp_path)._get_identity()- assert str(tmp_path.resolve()) not in resultassert "Agent profile: SOUL.md and USER.md" in resultassert "History log: memory/history.jsonl" in resultassert "Custom skills: skills/{skill-name}/SKILL.md" in result@@ -318,10 +307,9 @@ class TestBuildSystemPrompt:result = ContextBuilder(agent_home)._get_identity(workspace=project)- assert str(project.resolve()) not in resultassert f"agent workspace is at: {agent_home.resolve()}" in resultassert f"{agent_home.resolve()}/SOUL.md" in result- assert f"{project.resolve()}/SOUL.md" not in result+ assert f"Custom skills: {agent_home.resolve()}/skills/" in resultdef test_includes_bootstrap_files(self, tmp_path):(tmp_path / "AGENTS.md").write_text("Be helpful and concise.", encoding="utf-8")diff --git a/tests/agent/test_context_prompt_cache.py b/tests/agent/test_context_prompt_cache.pyindex cc481d90e..37dc2df24 100644--- a/tests/agent/test_context_prompt_cache.py+++ b/tests/agent/test_context_prompt_cache.py@@ -118,9 +118,7 @@ def test_execution_rules_in_system_prompt(tmp_path) -> None:prompt = builder.build_system_prompt()assert "clear user request" in prompt- assert "multi-step tasks" in prompt- assert "read-only discovery before writes" in prompt- assert "verify the result" in prompt+ assert "execution and verification" in promptdef test_execution_rules_reach_existing_workspace_soul(tmp_path) -> None:@@ -152,8 +150,8 @@ def test_default_soul_template_keeps_execution_policy_in_tool_contract() -> Noneassert "## Execution Rules" not in soulassert "clear user request" not in soulassert "clear user request" in contract- assert "multi-step tasks" in contract- assert "irreversible action needs confirmation" in contract+ assert "execution and verification" in contract+ assert "Ask for confirmation when an irreversible action requires it" in contractdef test_channel_format_hint_telegram(tmp_path) -> None:@@ -202,18 +200,6 @@ def test_build_messages_passes_channel_to_system_prompt(tmp_path) -> None:assert "messaging app" in system-def test_system_prompt_keeps_message_tool_out_of_current_chat_replies(tmp_path) -> None:- workspace = _make_workspace(tmp_path)- builder = ContextBuilder(workspace)-- prompt = builder.build_system_prompt(channel="slack")-- assert "Do not use the 'message' tool for normal replies in the current chat" in prompt- assert "When 'generate_image' creates images" in prompt- assert "call 'message' with the artifact paths in the 'media' parameter" in prompt- assert "Wait for the tool results, then answer once" in prompt--def test_memory_skill_is_lazy_loaded_from_skills_index(tmp_path) -> None:"""Memory search guidance should be discoverable without loading its full body."""workspace = _make_workspace(tmp_path)@@ -239,11 +225,10 @@ def test_fresh_workspace_omits_default_prompt_scaffolding(tmp_path) -> None:assert "## USER.md" not in promptassert "8281248569" not in promptassert "(your name)" not in prompt- assert prompt.count("Do not use the 'message' tool for normal replies") == 1def test_template_memory_md_is_skipped(tmp_path) -> None:- """MEMORY.md matching the bundled template should not inject the Memory section."""+ """Template content is omitted while memory locations remain available."""workspace = _make_workspace(tmp_path)from nanobot.utils.helpers import sync_workspace_templatessync_workspace_templates(workspace, silent=True)@@ -251,8 +236,8 @@ def test_template_memory_md_is_skipped(tmp_path) -> None:builder = ContextBuilder(workspace)prompt = builder.build_system_prompt()- # This block is produced only when populated long-term memory is injected.- assert "# Memory\n\n## Long-term Memory" not in prompt+ assert "## Long-term Memory" not in prompt+ assert "History log: memory/history.jsonl" in promptassert "This file is automatically updated by nanobot" not in promptdiff --git a/tests/agent/test_skills_loader.py b/tests/agent/test_skills_loader.pyindex d5e2c98df..91cb7e3ab 100644--- a/tests/agent/test_skills_loader.py+++ b/tests/agent/test_skills_loader.py@@ -350,8 +350,7 @@ def test_bundled_skills_use_agent_owned_paths(tmp_path: Path) -> None:update_setup = loader.load_skill("update-setup")assert memory is not None- assert "<history-log-path>" in memory- assert 'path="memory/history.jsonl"' not in memory+ assert "`History log` path from the system prompt" in memoryassert update_setup is not Noneassert "<agent-workspace>/skills/update/SKILL.md" in update_setupassert "Never substitute a project-relative" in update_setupdiff --git a/tests/agent/test_tool_hint.py b/tests/agent/test_tool_hint.pyindex 5181bf72c..147b2de35 100644--- a/tests/agent/test_tool_hint.py+++ b/tests/agent/test_tool_hint.py@@ -16,6 +16,17 @@ def _hint(calls, max_length=40):class TestToolHintKnownTools:"""Test registered tool types produce correct formatted output."""+ def test_rg_shows_argument_boundaries(self):+ assert _hint([_tc("rg", {"args": ["-n", "hello world", "src"]})]) == 'rg -n "hello world" src'++ def test_rg_shows_regex_and_empty_argument(self):+ assert _hint([_tc("rg", {"args": [r"resolve\(", ""]})]) == 'rg resolve\\( ""'++ def test_rg_truncates_long_arguments(self):+ result = _hint([_tc("rg", {"args": ["x" * 100]})])+ assert result.endswith("…")+ assert len(result) == 43+def test_read_file_short_path(self):result = _hint([_tc("read_file", {"path": "foo.txt"})])assert result == 'read foo.txt'diff --git a/tests/test_file_tool_toggle.py b/tests/test_file_tool_toggle.pyindex 3df2d00d0..8353ede92 100644--- a/tests/test_file_tool_toggle.py+++ b/tests/test_file_tool_toggle.py@@ -12,6 +12,7 @@ FILE_TOOL_NAMES = {"edit_file","find_files","grep",+ "rg","list_dir","read_file","write_file",diff --git a/tests/tools/test_rg_tool.py b/tests/tools/test_rg_tool.pynew file mode 100644index 000000000..445157692--- /dev/null+++ b/tests/tools/test_rg_tool.py@@ -0,0 +1,235 @@+"""Registration and exec delegation for ripgrep."""++import asyncio+import os+import re+import shlex+import shutil+import sys+from unittest.mock import AsyncMock++import pytest++from nanobot.agent.tools.context import ToolContext+from nanobot.agent.tools.exec_session import ExecSessionManager+from nanobot.agent.tools.loader import ToolLoader+from nanobot.agent.tools.registry import ToolRegistry+from nanobot.agent.tools.rg import RgTool+from nanobot.agent.tools.search import FindFilesTool, GrepTool+from nanobot.agent.tools.shell import ExecTool, _PreparedCommand+from nanobot.config.schema import ToolsConfig++[email protected]("installed", [True, False])[email protected]("exec_enabled", [True, False])[email protected]("file_enabled", [True, False])[email protected]("scope", ["core", "subagent"])[email protected]("classes", [+ [RgTool, GrepTool, FindFilesTool], [GrepTool, FindFilesTool, RgTool],+])+def test_loader_selects_one_search_backend(tmp_path, monkeypatch, installed, exec_enabled, file_enabled, scope, classes):+ monkeypatch.setattr("nanobot.agent.tools.rg.shutil.which", lambda *a, **kw: "rg" if installed else None)+ config = ToolsConfig()+ config.exec.enable = exec_enabled+ config.file.enable = file_enabled+ ctx = ToolContext(config=config, workspace=str(tmp_path))+ registry = ToolRegistry()+ registered = ToolLoader(test_classes=classes).load(ctx, registry, scope=scope)+ expected = {"rg"} if installed and exec_enabled else {"grep", "find_files"}+ assert set(registry.tool_names) == (expected if file_enabled else set())+ assert set(registered) == set(registry.tool_names)+++def test_loader_keeps_builtin_search_when_rg_creation_fails(tmp_path, monkeypatch):+ monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))++ def fail_create(cls, ctx):+ raise RuntimeError("rg initialization failed")++ monkeypatch.setattr(RgTool, "create", classmethod(fail_create))+ registry = ToolRegistry()+ registered = ToolLoader(test_classes=[RgTool, GrepTool, FindFilesTool]).load(+ ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry,+ )+ assert set(registered) == {"grep", "find_files"}+ assert set(registry.tool_names) == {"grep", "find_files"}+++def test_loader_can_load_builtin_search_independently(tmp_path, monkeypatch):+ monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))+ registry = ToolRegistry()+ registered = ToolLoader(test_classes=[GrepTool, FindFilesTool]).load(+ ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry,+ )+ assert set(registered) == {"grep", "find_files"}+ assert set(registry.tool_names) == {"grep", "find_files"}+++def test_loader_preserves_plugin_search_tool(tmp_path, monkeypatch):+ monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))+ loader = ToolLoader(test_classes=[RgTool, GrepTool, FindFilesTool])+ monkeypatch.setattr(loader, "_discover_plugins", lambda: {"external_grep": GrepTool})+ registry = ToolRegistry()+ registered = loader.load(ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry)+ assert registered == ["rg", "grep"]+ assert set(registry.tool_names) == {"rg", "grep"}+++def test_detection_uses_exec_path_configuration(tmp_path, monkeypatch):+ config = ToolsConfig()+ config.exec.path_prepend = str(tmp_path / "before")+ config.exec.path_append = str(tmp_path / "after")+ captured = {}++ def which(command, *, path):+ captured.update(command=command, path=path)+ return "rg"++ monkeypatch.setattr("nanobot.agent.tools.rg.shutil.which", which)+ assert RgTool.enabled(ToolContext(config=config, workspace=str(tmp_path)))+ assert captured["path"] == os.pathsep.join([+ config.exec.path_prepend, os.environ.get("PATH", ""), config.exec.path_append,+ ])+++async def test_rg_forwards_native_arguments_and_exec_options(monkeypatch):+ execute = AsyncMock(return_value="native output")+ monkeypatch.setattr(ExecTool, "execute", execute)+ arguments = ["--engine=pcre2", "--sort", "path", "--json", "(?<=hello)world", "."]+ result = await RgTool().execute(+ args=arguments, working_dir="project", timeout=12,+ yield_time_ms=25, max_output_chars=1500,+ )+ assert result == "native output"+ execute.assert_awaited_once_with(+ command=["rg", *arguments], working_dir="project", timeout=12,+ yield_time_ms=25, max_output_chars=1500,+ )+ assert RgTool().read_only is False+++def test_schema_exposes_arguments_and_exec_controls():+ schema = RgTool().parameters+ assert schema["properties"]["args"]["type"] == "array"+ assert schema["properties"]["args"]["items"] == {"type": "string"}+ assert schema["required"] == ["args"]+ assert {"working_dir", "timeout", "yield_time_ms"} <= schema["properties"].keys()+ assert "command" in ExecTool().parameters["properties"]++[email protected](shutil.which("rg") is None, reason="ripgrep not installed")+async def test_native_search_and_file_discovery_via_exec(tmp_path):+ (tmp_path / "source.py").write_text("before\nneedle\nafter\n", encoding="utf-8")+ (tmp_path / "other.txt").write_text("unrelated\n", encoding="utf-8")+ tool = RgTool(working_dir=str(tmp_path), restrict_to_workspace=True)+ result = await tool.execute(args=["-n", "-C1", "-g", "*.py", "needle", "."])+ assert "2:needle" in result+ assert "before" in result and "after" in result+ assert "Exit code: 0" in result+ files = await tool.execute(args=["--files", "-g", "*.py", "."])+ assert "source.py" in files+ absent = await tool.execute(args=["absent", "."])+ assert "Exit code: 1" in absent+++async def test_exec_workspace_policy_applies(tmp_path):+ result = await RgTool(working_dir=str(tmp_path), restrict_to_workspace=True).execute(+ args=["--files"], working_dir=str(tmp_path.parent),+ )+ assert "outside the configured workspace" in result++[email protected](shutil.which("rg") is None, reason="ripgrep not installed")+async def test_native_arguments_preserve_spaces_and_shell_characters(tmp_path):+ text = 'hello world | $HOME > output; "quoted" & $(echo hi)'+ (tmp_path / "space name.txt").write_text(text + "\n", encoding="utf-8")+ tool = RgTool(working_dir=str(tmp_path))+ result = await tool.execute(args=["-n", "-F", "--", text, "space name.txt"])+ assert f"1:{text}" in result+ assert "Exit code: 0" in result++[email protected](shutil.which("rg") is None, reason="ripgrep not installed")+async def test_native_search_session(tmp_path):+ (tmp_path / "source.txt").write_text("needle\n", encoding="utf-8")+ manager = ExecSessionManager()+ tool = RgTool(working_dir=str(tmp_path), session_manager=manager)+ try:+ result = await tool.execute(args=["-n", "needle", "."], yield_time_ms=0)+ session = re.search(r"session_id:\s*([0-9a-f]+)", result)+ if session:+ poll = await manager.write(+ session_id=session.group(1), chars=None, close_stdin=False, terminate=False,+ yield_time_ms=10000, max_output_chars=1000,+ )+ result += poll.output+ assert poll.exit_code == 0+ assert "1:needle" in result+ finally:+ await manager.close_all()+++async def test_direct_process_preserves_arguments_and_output_limit(tmp_path):+ tool = ExecTool(working_dir=str(tmp_path))+ result = await tool.execute(+ command=[sys.executable, "-c", "print('x' * 4000)"], max_output_chars=1000,+ )+ assert "chars truncated" in result+ assert "Exit code: 0" in result+++async def test_direct_process_timeout(tmp_path):+ result = await ExecTool(working_dir=str(tmp_path)).execute(+ command=[sys.executable, "-c", "import time; time.sleep(20)"], timeout=1,+ )+ assert "timed out after 1 seconds" in result+++async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):+ spawned = asyncio.Event()+ processes = []+ original_spawn = ExecTool._spawn++ async def capture(*args, **kwargs):+ process = await original_spawn(*args, **kwargs)+ processes.append(process)+ spawned.set()+ return process++ monkeypatch.setattr(ExecTool, "_spawn", staticmethod(capture))+ task = asyncio.create_task(ExecTool(working_dir=str(tmp_path)).execute(+ command=[sys.executable, "-c", "import time; time.sleep(20)"],+ ))+ await asyncio.wait_for(spawned.wait(), timeout=5)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert isinstance(processes[0].returncode, int)++[email protected](shutil.which("rg") is None, reason="ripgrep not installed")+async def test_direct_search_uses_configured_path(tmp_path, monkeypatch):+ installed = shutil.which("rg")+ assert installed+ bin_dir = tmp_path / "custom bin"+ bin_dir.mkdir()+ shutil.copy2(installed, bin_dir / ("rg.exe" if sys.platform == "win32" else "rg"))+ monkeypatch.setenv("PATH", "")+ result = await RgTool(working_dir=str(tmp_path), path_prepend=str(bin_dir)).execute(+ args=["--version"],+ )+ assert "ripgrep" in result+ assert "Exit code: 0" in result++[email protected]("backend", ["bwrap", "seatbelt"])+def test_direct_search_preserves_sandbox_and_arguments(tmp_path, monkeypatch, backend):+ monkeypatch.setattr("nanobot.agent.tools.shell._IS_WINDOWS", False)+ args = ["rg", "-F", "hello | $HOME; 'world'", "."]+ prepared = RgTool(working_dir=str(tmp_path), sandbox=backend)._prepare_command(args)+ assert isinstance(prepared, _PreparedCommand)+ assert isinstance(prepared.command, list)+ assert prepared.command[0] == ("bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec")+ assert prepared.command[-2] == "-c"+ inner_command = prepared.command[-1].split("\n")[-1]+ assert shlex.split(inner_command) == argsdiff --git a/tests/tools/test_search_tools.py b/tests/tools/test_search_tools.pyindex 4c7468df1..192938680 100644--- a/tests/tools/test_search_tools.py+++ b/tests/tools/test_search_tools.py@@ -758,19 +758,24 @@ async def test_search_tools_reject_paths_outside_workspace(tmp_path: Path) -> Noassert grep_result.startswith("Error:")-def test_agent_loop_registers_grep(tmp_path: Path) -> None:[email protected]("use_rg", [True, False])+def test_agent_loop_registers_search_backend(tmp_path: Path, monkeypatch, use_rg) -> None:+ monkeypatch.setattr("nanobot.agent.tools.rg.RgTool.enabled", lambda ctx: use_rg)bus = MessageBus()provider = MagicMock()provider.get_default_model.return_value = "test-model"loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")- assert "find_files" in loop.tools.tool_names- assert "grep" in loop.tools.tool_names+ assert ("rg" in loop.tools.tool_names) == use_rg+ assert ("find_files" in loop.tools.tool_names) == (not use_rg)+ assert ("grep" in loop.tools.tool_names) == (not use_rg)@pytest.mark.asyncio-async def test_subagent_registers_grep(tmp_path: Path) -> None:[email protected]("use_rg", [True, False])+async def test_subagent_registers_search_backend(tmp_path: Path, monkeypatch, use_rg) -> None:+ monkeypatch.setattr("nanobot.agent.tools.rg.RgTool.enabled", lambda ctx: use_rg)bus = MessageBus()provider = MagicMock()provider.get_default_model.return_value = "test-model"@@ -804,8 +809,9 @@ async def test_subagent_registers_grep(tmp_path: Path) -> None:LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),)- assert "find_files" in captured["tool_names"]- assert "grep" in captured["tool_names"]+ assert ("rg" in captured["tool_names"]) == use_rg+ assert ("find_files" in captured["tool_names"]) == (not use_rg)+ assert ("grep" in captured["tool_names"]) == (not use_rg)def test_subagent_prompt_respects_disabled_skills(tmp_path: Path) -> None:diff --git a/tests/tools/test_tool_loader.py b/tests/tools/test_tool_loader.pyindex 90040103c..afb0181b0 100644--- a/tests/tools/test_tool_loader.py+++ b/tests/tools/test_tool_loader.py@@ -1,6 +1,7 @@"""Tests for tool plugin architecture: ToolLoader, ToolContext, metadata."""from __future__ import annotations+import shutilfrom dataclasses import fieldsfrom pathlib import Pathfrom typing import Any@@ -445,10 +446,11 @@ def test_loader_registers_same_tools_as_old_hardcoded():expected = {"read_file", "write_file", "edit_file", "list_dir",- "find_files", "grep", "exec", "exec_session", "list_exec_sessions",+ "exec", "exec_session", "list_exec_sessions","web_search", "web_fetch","message", "spawn", "cron","my",}actual = set(registered)+ expected.update({"rg"} if shutil.which("rg") else {"find_files", "grep"})assert expected <= actual, f"Missing tools: {expected - actual}"diff --git a/tui/src/tool-renderers.test.ts b/tui/src/tool-renderers.test.tsindex aa88a8027..c6fc2c18e 100644--- a/tui/src/tool-renderers.test.ts+++ b/tui/src/tool-renderers.test.ts@@ -3,6 +3,20 @@ import { describe, expect, test } from "bun:test"import { mergeToolEvent, renderToolEvent } from "./tool-renderers"describe("tool renderers", () => {+ test("shows rg search phases and argument boundaries", () => {+ const start = { name: "rg", phase: "start", arguments: { args: ["-n", "hello world", "src"] } }+ expect(renderToolEvent(start)).toBe(' › Searching files -n "hello world" src')+ expect(renderToolEvent(mergeToolEvent(start, { name: "rg", phase: "end", result: "src/a:1:hello world" })))+ .toBe(' ✓ Searched files -n "hello world" src')+ expect(renderToolEvent({ name: "rg", phase: "error", error: "invalid regex" }))+ .toBe(" × Search failed invalid regex")+ })++ test("shows rg regex characters and empty arguments", () => {+ expect(renderToolEvent({ name: "rg", phase: "end", arguments: { args: [String.raw`resolve\(`, ""] } }))+ .toBe(' ✓ Searched files resolve\\( ""')+ })+test("retains start arguments when an end frame only carries output", () => {const event = mergeToolEvent({ call_id: "exec-1", phase: "start", name: "exec", arguments: { cmd: "git status" } },diff --git a/tui/src/tool-renderers.ts b/tui/src/tool-renderers.tsindex 9b9479eb3..f5bd9c299 100644--- a/tui/src/tool-renderers.ts+++ b/tui/src/tool-renderers.ts@@ -54,6 +54,7 @@ function toolLabel(return phase === "end" ? "Delegated" : phase === "error" ? "Delegation failed" : "Delegating"}if (name === "web_search") return "Search web"+ if (name === "rg") return phase === "end" ? "Searched files" : phase === "error" ? "Search failed" : "Searching files"if (name === "web_fetch") return "Fetch"return name}@@ -72,6 +73,11 @@ function toolDetail(}if (/^(?:spawn|spawn_agent)$/u.test(name)) return compact(args.label ?? args.task, 56)if (name === "web_search") return compact(args.query ?? args.q)+ if (name === "rg" && Array.isArray(args.args)) {+ return compact(args.args.map((arg) =>+ typeof arg === "string" && arg && !/[\s"']/u.test(arg) ? arg : JSON.stringify(arg),+ ).join(" "))+ }if (name === "web_fetch") return compact(args.url)if (/session/u.test(name)) return compact(args.session_key ?? args.chat_id ?? args.query)if (Object.keys(args).length) return compact(args)diff --git a/webui/src/components/thread/activity/generic-tool-model.ts b/webui/src/components/thread/activity/generic-tool-model.tsindex 5e7f12208..72167f141 100644--- a/webui/src/components/thread/activity/generic-tool-model.ts+++ b/webui/src/components/thread/activity/generic-tool-model.ts@@ -8,6 +8,7 @@ export type ToolFamily = "content-search" | "file-search" | "list" | "read" | "minterface ToolField {key:| "query"+ | "args"| "pattern"| "glob"| "path"@@ -88,6 +89,14 @@ export function parseGenericToolTrace(line: string): GenericToolTrace | null {if (!call || isExcludedTool(call.name)) return null;const family = toolFamily(call.name);const fields = safeFields(call.args);+ if (call.name === "rg" && call.args && typeof call.args === "object") {+ const argv = (call.args as Record<string, unknown>).args;+ if (Array.isArray(argv) && argv.every((arg) => typeof arg === "string")) {+ fields.push({ key: "args", value: argv.map((arg) =>+ arg && !/[\s"']/u.test(arg) ? arg : JSON.stringify(arg),+ ).join(" ") });+ }+ }const collectedSource = fields.some((field) => isCollectedSourcePath(field.value));return {name: call.name,@@ -283,6 +292,7 @@ function activityLabel(function activityDetail(items: GenericToolRunItem[], family: ToolFamily, name: string): string {if (items.length !== 1) return "";const trace = items[0].trace;+ if (name === "rg") return safeText(fieldValue(trace, "args"));if (family === "content-search") {return quote(fieldValue(trace, "query") || fieldValue(trace, "pattern"));}diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 82d6203cb..f5fd7bf8b 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -1867,8 +1867,8 @@"searchedFiles": "Searched files","searchFilesFailed": "Could not search files","findingFiles": "Finding files",- "foundFiles": "Found files",- "findFilesFailed": "Could not find files",+ "foundFiles": "File search complete",+ "findFilesFailed": "Could not search for files","listingFiles": "Listing files","listedFiles": "Listed files","listFilesFailed": "Could not list files",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 816f8e319..6e434a3bb 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -1696,8 +1696,8 @@"searchedFiles": "Búsqueda en archivos completada","searchFilesFailed": "No se pudo buscar en los archivos","findingFiles": "Buscando archivos",- "foundFiles": "Archivos encontrados",- "findFilesFailed": "No se pudieron encontrar archivos",+ "foundFiles": "Búsqueda de archivos completada",+ "findFilesFailed": "No se pudieron buscar archivos","listingFiles": "Listando archivos","listedFiles": "Archivos listados","listFilesFailed": "No se pudieron listar los archivos",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex d812136b0..fa5e4b25c 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -1695,8 +1695,8 @@"searchedFiles": "Recherche terminée dans les fichiers","searchFilesFailed": "Impossible de rechercher dans les fichiers","findingFiles": "Recherche de fichiers",- "foundFiles": "Fichiers trouvés",- "findFilesFailed": "Impossible de trouver les fichiers",+ "foundFiles": "Recherche de fichiers terminée",+ "findFilesFailed": "Impossible de rechercher des fichiers","listingFiles": "Liste des fichiers","listedFiles": "Fichiers listés","listFilesFailed": "Impossible de lister les fichiers",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 8b86464a9..4bfaa1374 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -1695,8 +1695,8 @@"searchedFiles": "Pencarian file selesai","searchFilesFailed": "Tidak dapat mencari di file","findingFiles": "Mencari file",- "foundFiles": "File ditemukan",- "findFilesFailed": "Tidak dapat menemukan file",+ "foundFiles": "Pencarian file selesai",+ "findFilesFailed": "Pencarian file gagal","listingFiles": "Membuat daftar file","listedFiles": "File terdaftar","listFilesFailed": "Tidak dapat membuat daftar file",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex 556ea9353..72d74490c 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -1692,11 +1692,11 @@"reviewedSources": "ソースを確認しました","reviewSourcesFailed": "ソースを確認できませんでした","searchingFiles": "ファイルを検索中",- "searchedFiles": "ファイルを検索しました",+ "searchedFiles": "ファイル検索完了","searchFilesFailed": "ファイルを検索できませんでした",- "findingFiles": "ファイルを探索中",- "foundFiles": "ファイルを見つけました",- "findFilesFailed": "ファイルを見つけられませんでした",+ "findingFiles": "ファイルを検索中",+ "foundFiles": "ファイル検索完了",+ "findFilesFailed": "ファイルの検索に失敗しました","listingFiles": "ファイルを一覧表示中","listedFiles": "ファイルを一覧表示しました","listFilesFailed": "ファイルを一覧表示できませんでした",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 1695bc995..855c8a0b0 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -1695,8 +1695,8 @@"searchedFiles": "파일 검색 완료","searchFilesFailed": "파일을 검색하지 못함","findingFiles": "파일 찾는 중",- "foundFiles": "파일 찾음",- "findFilesFailed": "파일을 찾지 못함",+ "foundFiles": "파일 검색 완료",+ "findFilesFailed": "파일 검색 실패","listingFiles": "파일 목록 작성 중","listedFiles": "파일 목록 작성 완료","listFilesFailed": "파일 목록을 작성하지 못함",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 0225d5657..78ba410f3 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -1681,8 +1681,8 @@"searchedFiles": "Pesquisa nos arquivos concluída","searchFilesFailed": "Não foi possível pesquisar nos arquivos","findingFiles": "Procurando arquivos",- "foundFiles": "Arquivos encontrados",- "findFilesFailed": "Não foi possível encontrar arquivos",+ "foundFiles": "Busca de arquivos concluída",+ "findFilesFailed": "Não foi possível buscar arquivos","listingFiles": "Listando arquivos","listedFiles": "Arquivos listados","listFilesFailed": "Não foi possível listar os arquivos",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 446963c61..e8b28263e 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -1692,11 +1692,11 @@"reviewedSources": "Đã xem lại nguồn","reviewSourcesFailed": "Không thể xem lại nguồn","searchingFiles": "Đang tìm trong tệp",- "searchedFiles": "Đã tìm trong tệp",+ "searchedFiles": "Đã hoàn tất tìm kiếm trong tệp","searchFilesFailed": "Không thể tìm trong tệp","findingFiles": "Đang tìm tệp",- "foundFiles": "Đã tìm thấy tệp",- "findFilesFailed": "Không thể tìm thấy tệp",+ "foundFiles": "Đã hoàn tất tìm kiếm tệp",+ "findFilesFailed": "Không thể tìm kiếm tệp","listingFiles": "Đang liệt kê tệp","listedFiles": "Đã liệt kê tệp","listFilesFailed": "Không thể liệt kê tệp",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex ca3aeb500..a708a6756 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -1859,27 +1859,27 @@"activityWorkingFor": "处理中 {{duration}}","activityWorked": "已处理","agentActivity": {- "reviewingSources": "正在检查来源",- "reviewedSources": "已检查来源",- "reviewSourcesFailed": "无法检查来源",+ "reviewingSources": "正在查阅资料",+ "reviewedSources": "资料查阅完成",+ "reviewSourcesFailed": "资料查阅失败","searchingFiles": "正在搜索文件",- "searchedFiles": "已搜索文件",- "searchFilesFailed": "无法搜索文件",+ "searchedFiles": "文件搜索完成",+ "searchFilesFailed": "文件搜索失败","findingFiles": "正在查找文件",- "foundFiles": "已找到文件",- "findFilesFailed": "无法查找文件",+ "foundFiles": "文件查找完成",+ "findFilesFailed": "文件查找失败","listingFiles": "正在列出文件","listedFiles": "已列出文件","listFilesFailed": "无法列出文件",- "readingSource": "正在读取来源",- "readSource": "已读取来源",- "readSourceFailed": "无法读取来源",+ "readingSource": "正在读取资料",+ "readSource": "资料读取完成",+ "readSourceFailed": "资料读取失败","readingFile": "正在读取文件","readFile": "已读取文件","readFileFailed": "无法读取文件","searchingMemory": "正在搜索记忆",- "searchedMemory": "已搜索记忆",- "searchMemoryFailed": "无法搜索记忆",+ "searchedMemory": "记忆搜索完成",+ "searchMemoryFailed": "记忆搜索失败","generatingImage": "正在生成图片","generatedImage": "已生成图片","generateImageFailed": "无法生成图片",@@ -1924,12 +1924,12 @@"completeToolFailed": "无法完成 {{name}}","files_one": "{{count}} 个文件","files_other": "{{count}} 个文件",- "searches_one": "{{count}} 次搜索",- "searches_other": "{{count}} 次搜索",+ "searches_one": "{{count}} 次",+ "searches_other": "{{count}} 次","actions_one": "{{count}} 个操作","actions_other": "{{count}} 个操作","searching": "正在搜索 {{target}}",- "searched": "已搜索 {{target}}",+ "searched": "{{target}} 搜索完成","searchFailed": "无法搜索 {{target}}","web": "网页","reading": "正在读取",@@ -1980,7 +1980,7 @@"waitedForPage": "已等待页面","pageNotReady": "页面未就绪","searchingPlain": "正在搜索",- "searchedPlain": "已搜索",+ "searchedPlain": "搜索完成","searchFailedPlain": "无法搜索","toolFailed": "{{name}} 失败","toolCompleted": "{{name}} 已完成",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 60819a52e..15662d24d 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -1687,27 +1687,27 @@"activityWorked": "已處理","activityWorkedFor": "已處理 {{duration}}","agentActivity": {- "reviewingSources": "正在檢查來源",- "reviewedSources": "已檢查來源",- "reviewSourcesFailed": "無法檢查來源",+ "reviewingSources": "正在查閱資料",+ "reviewedSources": "資料查閱完成",+ "reviewSourcesFailed": "資料查閱失敗","searchingFiles": "正在搜尋檔案",- "searchedFiles": "已搜尋檔案",- "searchFilesFailed": "無法搜尋檔案",+ "searchedFiles": "檔案搜尋完成",+ "searchFilesFailed": "檔案搜尋失敗","findingFiles": "正在尋找檔案",- "foundFiles": "已找到檔案",- "findFilesFailed": "無法尋找檔案",+ "foundFiles": "檔案搜尋完成",+ "findFilesFailed": "檔案搜尋失敗","listingFiles": "正在列出檔案","listedFiles": "已列出檔案","listFilesFailed": "無法列出檔案",- "readingSource": "正在讀取來源",- "readSource": "已讀取來源",- "readSourceFailed": "無法讀取來源",+ "readingSource": "正在讀取資料",+ "readSource": "資料讀取完成",+ "readSourceFailed": "資料讀取失敗","readingFile": "正在讀取檔案","readFile": "已讀取檔案","readFileFailed": "無法讀取檔案","searchingMemory": "正在搜尋記憶",- "searchedMemory": "已搜尋記憶",- "searchMemoryFailed": "無法搜尋記憶",+ "searchedMemory": "記憶搜尋完成",+ "searchMemoryFailed": "記憶搜尋失敗","generatingImage": "正在產生圖片","generatedImage": "已產生圖片","generateImageFailed": "無法產生圖片",@@ -1752,12 +1752,12 @@"completeToolFailed": "無法完成 {{name}}","files_one": "{{count}} 個檔案","files_other": "{{count}} 個檔案",- "searches_one": "{{count}} 次搜尋",- "searches_other": "{{count}} 次搜尋",+ "searches_one": "{{count}} 次",+ "searches_other": "{{count}} 次","actions_one": "{{count}} 個操作","actions_other": "{{count}} 個操作","searching": "正在搜尋 {{target}}",- "searched": "已搜尋 {{target}}",+ "searched": "{{target}} 搜尋完成","searchFailed": "無法搜尋 {{target}}","web": "網頁","reading": "正在讀取",@@ -1808,7 +1808,7 @@"waitedForPage": "已等待頁面","pageNotReady": "頁面尚未就緒","searchingPlain": "正在搜尋",- "searchedPlain": "已搜尋",+ "searchedPlain": "搜尋完成","searchFailedPlain": "無法搜尋","toolFailed": "{{name}} 失敗","toolCompleted": "{{name}} 已完成",diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsxindex 3e9f05ca7..c95d2fc9f 100644--- a/webui/src/tests/agent-activity-cluster.test.tsx+++ b/webui/src/tests/agent-activity-cluster.test.tsx@@ -152,7 +152,7 @@ describe("AgentActivityCluster", () => {await act(async () => setAppLanguage("zh-CN"));- expect(screen.getByText(`已搜索文件 “${query}”`)).toBeInTheDocument();+ expect(screen.getByText(`文件搜索完成 “${query}”`)).toBeInTheDocument();expect(screen.getByText(`正在读取文件 ${path}`)).toBeInTheDocument();expect(screen.getByText("正在使用 Blender · --json --background scene.blend")).toBeInTheDocument();expect(screen.getByText("正在打开 example.com · Browserbase")).toBeInTheDocument();@@ -161,7 +161,7 @@ describe("AgentActivityCluster", () => {await act(async () => setAppLanguage("ja"));- expect(screen.getByText(`“${query}” · ファイルを検索しました`)).toBeInTheDocument();+ expect(screen.getByText(`“${query}” · ファイル検索完了`)).toBeInTheDocument();expect(screen.getByText(`${path} · ファイルを読み取り中`)).toBeInTheDocument();expect(screen.getByText("Blender を使用中 · --json --background scene.blend")).toBeInTheDocument();expect(screen.getByText("example.com · 開いています · Browserbase")).toBeInTheDocument();@@ -1523,7 +1523,7 @@ describe("AgentActivityCluster", () => {/>,);- expect(screen.getByText("Found files *.tsx")).toBeInTheDocument();+ expect(screen.getByText("File search complete *.tsx")).toBeInTheDocument();expect(screen.getByText("Listed files memory")).toBeInTheDocument();expect(screen.getByText("Searching files “dream_cursor”")).toBeInTheDocument();expect(screen.queryByText("Technical details")).not.toBeInTheDocument();diff --git a/webui/src/tests/generic-tool-model.test.ts b/webui/src/tests/generic-tool-model.test.tsindex c305af17f..8886fef83 100644--- a/webui/src/tests/generic-tool-model.test.ts+++ b/webui/src/tests/generic-tool-model.test.ts@@ -15,8 +15,25 @@ function describeRun(line: string, status: GenericToolStatus = "done") {}describe("generic tool activity semantics", () => {+ it.each(["running", "done", "error"] as const)("shows rg arguments during %s", (status) => {+ const presentation = describeRun('rg({"args":["-n","hello world","src"]})', status);+ expect(presentation.detail).toBe('-n "hello world" src');+ expect(presentation.status).toBe(status);+ });++ it("bounds and redacts rg argument previews", () => {+ const presentation = describeRun(`rg(${JSON.stringify({ args: ["sk-proj-abcdefghijklmno", "x".repeat(120)] })})`);+ expect(presentation.detail).toContain("<redacted>");+ expect(presentation.detail.length).toBeLessThanOrEqual(88);+ });++ it("shows rg regex characters and empty arguments", () => {+ const presentation = describeRun(`rg(${JSON.stringify({ args: [String.raw`resolve\(`, ""] })})`);+ expect(presentation.detail).toBe('resolve\\( ""');+ });+it.each([- ['find_files({"glob":"*.tsx"})', "Found files", "*.tsx"],+ ['find_files({"glob":"*.tsx"})', "File search complete", "*.tsx"],['grep({"pattern":"dream_cursor"})', "Searched files", "“dream_cursor”"],['list_dir({"path":"memory"})', "Listed files", "memory"],['read_file({"path":"docs/guide.md"})', "Read file", "docs/guide.md"],@@ -90,8 +107,8 @@ describe("generic tool activity semantics", () => {{ trace: first, status: "done" },{ trace: second, status: "done" },], i18n.t)).toMatchObject({- label: "已搜索文件",- aside: "2 次搜索",+ label: "文件搜索完成",+ aside: "2 次",});});diff --git a/webui/src/tests/i18n-agent-activity.test.tsx b/webui/src/tests/i18n-agent-activity.test.tsxindex 10235cd5b..6731b7dd9 100644--- a/webui/src/tests/i18n-agent-activity.test.tsx+++ b/webui/src/tests/i18n-agent-activity.test.tsx@@ -29,7 +29,15 @@ describe("localized agent activity contracts", () => {await setAppLanguage(locale);const trace = parseGenericToolTrace('read_file({"path":"src/app.tsx"})')!;+ const rg = parseGenericToolTrace('rg({"args":["-n","hello world","src"]})')!;for (const status of ["running", "done", "error"] as const) {+ const rgPresentation = describeGenericToolRun([{ trace: rg, status }], i18n.t);+ const searchKey = status === "running" ? "searchingFiles" : status === "done" ? "searchedFiles" : "searchFilesFailed";+ expect(rgPresentation).toMatchObject({+ label: translated[searchKey],+ detail: '-n "hello world" src',+ status,+ });const generic = describeGenericToolRun([{ trace, status }], i18n.t);const command = describeTraceLine('exec({"command":"bun run test"})', status, i18n.t);const browser = describeMcpActivity("browser_press_key", { key: "Enter" }, status, i18n.t);