feat(tools): use installed ripgrep for native file search (#5948)

* feat(tools): expose installed ripgrep through exec

* refactor(tools): launch ripgrep with native argument vectors

* refactor(tools): reuse the fresh exec parameter schema

* fix(tools): select search backend in loader and display rg arguments

* fix(ui): simplify rg previews and localize search completion

* docs: simplify ripgrep configuration note

* docs: keep ripgrep note on one line
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-28 13:44:51 +08:00
1 parent b8893aba56
commit e0b8efa0be
33 files changed
+514 -204

No files matched your search

+4 -3
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import codecs
import shlex
import time
import uuid
from 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,
+6
View File
@@ -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 registered
+56
View File
@@ -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)
+39 -9
View File
@@ -107,7 +107,7 @@ class ExecToolConfig(Base):
@dataclass(slots=True)
class _PreparedCommand:
command: str
command: str | list[str]
cwd: str
env: dict[str, str]
timeout: int | None
@@ -272,7 +272,7 @@ class ExecTool(Tool):
return True
async 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 wrapped
cwd = 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):
@staticmethod
async 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)
raise
if _IS_WINDOWS:
windows_job = None
process = None
+4 -10
View File
@@ -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.
+2 -2
View File
@@ -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 %}
+3 -75
View File
@@ -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.
+8
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
import re
from 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 val