feat(webui): add project workspaces and access controls (#4007)
* feat(webui): add project workspaces and access controls * feat(webui): add project workspaces and access controls * refactor(tools): centralize workspace access resolution * refactor(webui): remove unused workspace host state * fix(webui): hide estimated file edit label * fix(webui): clarify file edit deletion feedback * fix(webui): label deleted file activity * fix(webui): flatten file edit activity rows * fix(core): remove path-only patch deletion * fix(core): keep apply patch non-destructive * refactor(webui): trim workspace host plumbing * fix(tools): register exec with tools config
This commit is contained in:
@@ -68,11 +68,13 @@ class ContextBuilder:
|
||||
skill_names: list[str] | None = None,
|
||||
channel: str | None = None,
|
||||
session_summary: str | None = None,
|
||||
workspace: Path | None = None,
|
||||
) -> str:
|
||||
"""Build the system prompt from identity, bootstrap files, memory, and skills."""
|
||||
parts = [self._get_identity(channel=channel)]
|
||||
root = workspace or self.workspace
|
||||
parts = [self._get_identity(channel=channel, workspace=root)]
|
||||
|
||||
bootstrap = self._load_bootstrap_files()
|
||||
bootstrap = self._load_bootstrap_files(root)
|
||||
if bootstrap:
|
||||
parts.append(bootstrap)
|
||||
|
||||
@@ -106,9 +108,10 @@ class ContextBuilder:
|
||||
|
||||
return "\n\n---\n\n".join(parts)
|
||||
|
||||
def _get_identity(self, channel: str | None = None) -> str:
|
||||
def _get_identity(self, channel: str | None = None, workspace: Path | None = None) -> str:
|
||||
"""Get the core identity section."""
|
||||
workspace_path = str(self.workspace.expanduser().resolve())
|
||||
root = workspace or self.workspace
|
||||
workspace_path = str(root.expanduser().resolve())
|
||||
system = platform.system()
|
||||
runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}, Python {platform.python_version()}"
|
||||
|
||||
@@ -152,12 +155,13 @@ class ContextBuilder:
|
||||
|
||||
return _to_blocks(left) + _to_blocks(right)
|
||||
|
||||
def _load_bootstrap_files(self) -> str:
|
||||
def _load_bootstrap_files(self, workspace: Path | None = None) -> str:
|
||||
"""Load all bootstrap files from workspace."""
|
||||
parts = []
|
||||
root = workspace or self.workspace
|
||||
|
||||
for filename in self.BOOTSTRAP_FILES:
|
||||
file_path = self.workspace / filename
|
||||
file_path = root / filename
|
||||
if file_path.exists():
|
||||
content = file_path.read_text(encoding="utf-8")
|
||||
parts.append(f"## {filename}\n\n{content}")
|
||||
@@ -185,11 +189,18 @@ class ContextBuilder:
|
||||
session_summary: str | None = None,
|
||||
session_metadata: Mapping[str, Any] | None = None,
|
||||
current_runtime_lines: Sequence[str] | None = None,
|
||||
workspace: Path | None = None,
|
||||
runtime_state: Any | None = None,
|
||||
inbound_message: Any | None = None,
|
||||
skip_runtime_lines: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Build the complete message list for an LLM call."""
|
||||
root = workspace or self.workspace
|
||||
extra = [
|
||||
*goal_state_runtime_lines(session_metadata),
|
||||
]
|
||||
if runtime_state is not None and inbound_message is not None:
|
||||
extra.extend(runtime_lines(runtime_state, inbound_message, root, skip=skip_runtime_lines))
|
||||
if current_runtime_lines:
|
||||
extra.extend(line for line in current_runtime_lines if line)
|
||||
runtime_ctx = self._build_runtime_context(
|
||||
@@ -210,7 +221,15 @@ class ContextBuilder:
|
||||
else:
|
||||
merged = user_content + [{"type": "text", "text": runtime_ctx}]
|
||||
messages = [
|
||||
{"role": "system", "content": self.build_system_prompt(skill_names, channel=channel, session_summary=session_summary)},
|
||||
{
|
||||
"role": "system",
|
||||
"content": self.build_system_prompt(
|
||||
skill_names,
|
||||
channel=channel,
|
||||
session_summary=session_summary,
|
||||
workspace=root,
|
||||
),
|
||||
},
|
||||
*history,
|
||||
]
|
||||
if messages[-1].get("role") == current_role:
|
||||
|
||||
+58
-13
@@ -25,8 +25,14 @@ from nanobot.agent.runner import _MAX_INJECTIONS_PER_TURN, AgentRunner, AgentRun
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.file_state import FileStateStore, bind_file_states, reset_file_states
|
||||
from nanobot.agent.tools.message import MessageTool
|
||||
from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.tools.self import MyTool
|
||||
from nanobot.security.workspace_access import (
|
||||
WorkspaceScopeResolver,
|
||||
bind_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
)
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.command import CommandContext, CommandRouter, register_builtin_commands
|
||||
@@ -114,7 +120,6 @@ class TurnContext:
|
||||
|
||||
pending_queue: asyncio.Queue | None = None
|
||||
pending_summary: str | None = None
|
||||
|
||||
turn_wall_started_at: float = field(default_factory=time.time)
|
||||
turn_latency_ms: int | None = None
|
||||
|
||||
@@ -241,6 +246,10 @@ class AgentLoop:
|
||||
self._image_generation_provider_configs["openrouter"] = image_generation_provider_config
|
||||
self.cron_service = cron_service
|
||||
self.restrict_to_workspace = restrict_to_workspace
|
||||
self.workspace_scopes = WorkspaceScopeResolver(
|
||||
default_workspace=workspace,
|
||||
default_restrict_to_workspace=restrict_to_workspace,
|
||||
)
|
||||
self._start_time = time.time()
|
||||
self._last_usage: dict[str, int] = {}
|
||||
self._pending_turn_latency_ms: dict[str, int] = {}
|
||||
@@ -470,6 +479,7 @@ class AgentLoop:
|
||||
provider_snapshot_loader=self._provider_snapshot_loader,
|
||||
image_generation_provider_configs=self._image_generation_provider_configs,
|
||||
timezone=self.context.timezone or "UTC",
|
||||
workspace_sandbox=self.workspace_scopes.sandbox_status,
|
||||
)
|
||||
loader = ToolLoader()
|
||||
registered = loader.load(ctx, self.tools)
|
||||
@@ -493,7 +503,7 @@ class AgentLoop:
|
||||
session_key: str | None = None,
|
||||
) -> None:
|
||||
"""Update context for all tools that need routing info."""
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.context import ContextAware
|
||||
|
||||
if session_key is not None:
|
||||
effective_key = session_key
|
||||
@@ -575,6 +585,7 @@ class AgentLoop:
|
||||
pending_summary: str | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Build the initial message list for the LLM turn."""
|
||||
scope = self.workspace_scopes.for_message(msg, session.metadata)
|
||||
return self.context.build_messages(
|
||||
history=history,
|
||||
current_message=image_generation_prompt(msg.content, msg.metadata),
|
||||
@@ -583,7 +594,10 @@ class AgentLoop:
|
||||
chat_id=self._runtime_chat_id(msg),
|
||||
sender_id=msg.sender_id,
|
||||
session_summary=pending_summary,
|
||||
session_metadata=session.metadata, current_runtime_lines=agent_context.runtime_lines(self, msg, self.context.workspace),
|
||||
session_metadata=session.metadata,
|
||||
workspace=scope.project_path,
|
||||
runtime_state=self,
|
||||
inbound_message=msg,
|
||||
)
|
||||
|
||||
async def _dispatch_command_inline(
|
||||
@@ -733,7 +747,21 @@ class AgentLoop:
|
||||
return items
|
||||
|
||||
active_session_key = session.key if session else session_key
|
||||
effective_scope = self.workspace_scopes.for_turn(
|
||||
channel=channel,
|
||||
message_metadata=metadata,
|
||||
session_metadata=session.metadata if session is not None else None,
|
||||
)
|
||||
request_ctx = RequestContext(
|
||||
channel=channel,
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
session_key=active_session_key,
|
||||
metadata=dict(metadata or {}),
|
||||
)
|
||||
file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key))
|
||||
request_token = bind_request_context(request_ctx)
|
||||
workspace_token = bind_workspace_scope(effective_scope)
|
||||
# Build continuation message that embeds the active goal objective so
|
||||
# the LLM can see it even if earlier Runtime Context was truncated.
|
||||
_goal_lines = goal_state_runtime_lines(session.metadata if session is not None else None)
|
||||
@@ -753,7 +781,7 @@ class AgentLoop:
|
||||
hook=hook,
|
||||
error_message="Sorry, I encountered an error calling the AI model.",
|
||||
concurrent_tools=True,
|
||||
workspace=self.workspace,
|
||||
workspace=effective_scope.project_path,
|
||||
session_key=session.key if session else None,
|
||||
context_window_tokens=self.context_window_tokens,
|
||||
context_block_limit=self.context_block_limit,
|
||||
@@ -774,6 +802,8 @@ class AgentLoop:
|
||||
goal_continue_message=_goal_continue,
|
||||
))
|
||||
finally:
|
||||
reset_workspace_scope(workspace_token)
|
||||
reset_request_context(request_token)
|
||||
reset_file_states(file_state_token)
|
||||
self._last_usage = result.usage
|
||||
if result.stop_reason == "max_iterations":
|
||||
@@ -1063,6 +1093,7 @@ class AgentLoop:
|
||||
}
|
||||
history = session.get_history(**_hist_kwargs)
|
||||
current_role = "assistant" if is_subagent else "user"
|
||||
workspace_scope = self.workspace_scopes.for_message(msg, session.metadata)
|
||||
|
||||
messages = self.context.build_messages(
|
||||
history=history,
|
||||
@@ -1072,7 +1103,11 @@ class AgentLoop:
|
||||
current_role=current_role,
|
||||
sender_id=msg.sender_id,
|
||||
session_summary=pending,
|
||||
session_metadata=session.metadata, current_runtime_lines=agent_context.runtime_lines(self, msg, self.context.workspace, skip=is_subagent),
|
||||
session_metadata=session.metadata,
|
||||
workspace=workspace_scope.project_path,
|
||||
runtime_state=self,
|
||||
inbound_message=msg,
|
||||
skip_runtime_lines=is_subagent,
|
||||
)
|
||||
t_wall = time.time()
|
||||
final_content, _, all_msgs, stop_reason, _ = await self._run_agent_loop(
|
||||
@@ -1248,6 +1283,7 @@ class AgentLoop:
|
||||
if ctx.session is None:
|
||||
ctx.session = self.sessions.get_or_create(ctx.session_key)
|
||||
mark_webui_session(ctx.session, msg.metadata)
|
||||
self.workspace_scopes.persist_message_scope(ctx.session, msg)
|
||||
|
||||
if self._restore_runtime_checkpoint(ctx.session):
|
||||
self.sessions.save(ctx.session)
|
||||
@@ -1315,7 +1351,10 @@ class AgentLoop:
|
||||
)
|
||||
|
||||
ctx.initial_messages = self._build_initial_messages(
|
||||
ctx.msg, ctx.session, ctx.history, ctx.pending_summary
|
||||
ctx.msg,
|
||||
ctx.session,
|
||||
ctx.history,
|
||||
ctx.pending_summary,
|
||||
)
|
||||
ctx.user_persisted_early = self._persist_user_message_early(
|
||||
ctx.msg, ctx.session
|
||||
@@ -1618,10 +1657,16 @@ class AgentLoop:
|
||||
channel=channel, sender_id="user", chat_id=chat_id,
|
||||
content=content, media=media or [],
|
||||
)
|
||||
return await self._process_message(
|
||||
msg,
|
||||
session_key=session_key,
|
||||
on_progress=on_progress,
|
||||
on_stream=on_stream,
|
||||
on_stream_end=on_stream_end,
|
||||
)
|
||||
try:
|
||||
return await self._process_message(
|
||||
msg,
|
||||
session_key=session_key,
|
||||
on_progress=on_progress,
|
||||
on_stream=on_stream,
|
||||
on_stream_end=on_stream_end,
|
||||
)
|
||||
finally:
|
||||
if channel == "websocket":
|
||||
await self._webui_turns.publish_run_status(msg, "idle")
|
||||
self._pending_turn_latency_ms.pop(session_key, None)
|
||||
self._webui_turns.discard(session_key)
|
||||
|
||||
+52
-21
@@ -16,6 +16,12 @@ from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.file_state import FileStates
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.security.workspace_access import (
|
||||
WorkspaceScope,
|
||||
bind_workspace_scope,
|
||||
reset_workspace_scope,
|
||||
workspace_sandbox_status,
|
||||
)
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import AgentDefaults, ToolsConfig
|
||||
@@ -128,6 +134,10 @@ class SubagentManager:
|
||||
config=cfg,
|
||||
workspace=str(root.resolve()),
|
||||
file_state_store=FileStates(),
|
||||
workspace_sandbox=workspace_sandbox_status(
|
||||
restrict_to_workspace=cfg.restrict_to_workspace,
|
||||
workspace=root,
|
||||
),
|
||||
)
|
||||
ToolLoader().load(ctx, registry, scope="subagent")
|
||||
return registry
|
||||
@@ -146,6 +156,7 @@ class SubagentManager:
|
||||
session_key: str | None = None,
|
||||
origin_message_id: str | None = None,
|
||||
temperature: float | None = None,
|
||||
workspace_scope: WorkspaceScope | None = None,
|
||||
) -> str:
|
||||
"""Spawn a subagent to execute a task in the background."""
|
||||
task_id = str(uuid.uuid4())[:8]
|
||||
@@ -162,7 +173,14 @@ class SubagentManager:
|
||||
|
||||
bg_task = asyncio.create_task(
|
||||
self._run_subagent(
|
||||
task_id, task, display_label, origin, status, origin_message_id, temperature
|
||||
task_id,
|
||||
task,
|
||||
display_label,
|
||||
origin,
|
||||
status,
|
||||
origin_message_id,
|
||||
temperature,
|
||||
workspace_scope,
|
||||
)
|
||||
)
|
||||
self._running_tasks[task_id] = bg_task
|
||||
@@ -191,6 +209,7 @@ class SubagentManager:
|
||||
status: SubagentStatus,
|
||||
origin_message_id: str | None = None,
|
||||
temperature: float | None = None,
|
||||
workspace_scope: WorkspaceScope | None = None,
|
||||
) -> None:
|
||||
"""Execute the subagent task and announce the result."""
|
||||
logger.info("Subagent [{}] starting task: {}", task_id, label)
|
||||
@@ -200,8 +219,13 @@ class SubagentManager:
|
||||
status.iteration = payload.get("iteration", status.iteration)
|
||||
|
||||
try:
|
||||
tools = self._build_tools()
|
||||
system_prompt = self._build_subagent_prompt()
|
||||
root = workspace_scope.project_path if workspace_scope is not None else self.workspace
|
||||
cfg = None
|
||||
if workspace_scope is not None:
|
||||
cfg = self._subagent_tools_config()
|
||||
cfg.restrict_to_workspace = workspace_scope.restrict_to_workspace
|
||||
tools = self._build_tools(workspace=root, tools_config=cfg)
|
||||
system_prompt = self._build_subagent_prompt(workspace=root)
|
||||
messages: list[dict[str, Any]] = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": task},
|
||||
@@ -213,21 +237,27 @@ class SubagentManager:
|
||||
if self._llm_wall_timeout_for_session
|
||||
else None
|
||||
)
|
||||
result = await self.runner.run(AgentRunSpec(
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model=self.model,
|
||||
temperature=temperature,
|
||||
max_iterations=self.max_iterations,
|
||||
max_tool_result_chars=self.max_tool_result_chars,
|
||||
hook=_SubagentHook(task_id, status),
|
||||
max_iterations_message="Task completed but no final response was generated.",
|
||||
error_message=None,
|
||||
fail_on_tool_error=True,
|
||||
checkpoint_callback=_on_checkpoint,
|
||||
session_key=sess_key,
|
||||
llm_timeout_s=llm_timeout,
|
||||
))
|
||||
token = bind_workspace_scope(workspace_scope) if workspace_scope is not None else None
|
||||
try:
|
||||
result = await self.runner.run(AgentRunSpec(
|
||||
initial_messages=messages,
|
||||
tools=tools,
|
||||
model=self.model,
|
||||
temperature=temperature,
|
||||
max_iterations=self.max_iterations,
|
||||
max_tool_result_chars=self.max_tool_result_chars,
|
||||
hook=_SubagentHook(task_id, status),
|
||||
max_iterations_message="Task completed but no final response was generated.",
|
||||
error_message=None,
|
||||
fail_on_tool_error=True,
|
||||
checkpoint_callback=_on_checkpoint,
|
||||
session_key=sess_key,
|
||||
workspace=root,
|
||||
llm_timeout_s=llm_timeout,
|
||||
))
|
||||
finally:
|
||||
if token is not None:
|
||||
reset_workspace_scope(token)
|
||||
status.phase = "done"
|
||||
status.stop_reason = result.stop_reason
|
||||
|
||||
@@ -321,20 +351,21 @@ class SubagentManager:
|
||||
lines.append(f"- {result.error}")
|
||||
return "\n".join(lines) or (result.error or "Error: subagent execution failed.")
|
||||
|
||||
def _build_subagent_prompt(self) -> str:
|
||||
def _build_subagent_prompt(self, workspace: Path | None = None) -> str:
|
||||
"""Build a focused system prompt for the subagent."""
|
||||
from nanobot.agent.context import ContextBuilder
|
||||
from nanobot.agent.skills import SkillsLoader
|
||||
|
||||
time_ctx = ContextBuilder._build_runtime_context(None, None)
|
||||
root = workspace or self.workspace
|
||||
skills_summary = SkillsLoader(
|
||||
self.workspace,
|
||||
root,
|
||||
disabled_skills=self.disabled_skills,
|
||||
).build_skills_summary()
|
||||
return render_template(
|
||||
"agent/subagent_system.md",
|
||||
time_ctx=time_ctx,
|
||||
workspace=str(self.workspace),
|
||||
workspace=str(root),
|
||||
skills_summary=skills_summary or "",
|
||||
)
|
||||
|
||||
|
||||
@@ -88,11 +88,11 @@ def _format_summary(summary: _PatchSummary) -> str:
|
||||
items=ObjectSchema(
|
||||
path=StringSchema("Relative path to the file to edit."),
|
||||
action=StringSchema(
|
||||
"Operation type: replace (find and replace text), add (append new content or create file), delete (remove text).",
|
||||
enum=["replace", "add", "delete"],
|
||||
"Operation type: replace or add.",
|
||||
enum=["replace", "add"],
|
||||
),
|
||||
old_text=StringSchema(
|
||||
"Exact text to search for in the file. Required for replace and delete.",
|
||||
"Exact text to search for in the file. Required for replace.",
|
||||
nullable=True,
|
||||
),
|
||||
new_text=StringSchema(
|
||||
@@ -124,7 +124,8 @@ class ApplyPatchTool(_FsTool):
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Default tool for code edits. Supports multi-file changes in a single call. "
|
||||
"Provide a list of structured edits, each specifying a file path, action (replace/add/delete), and the text to change. "
|
||||
"Provide a list of structured edits, each specifying a file path, action "
|
||||
"(replace/add), and the exact text to change. "
|
||||
"Paths must be relative. Set dry_run=true to validate and preview without writing files. "
|
||||
"Use edit_file only for small exact replacements on a single file."
|
||||
)
|
||||
@@ -140,7 +141,6 @@ class ApplyPatchTool(_FsTool):
|
||||
raise _PatchError("must provide edits")
|
||||
|
||||
writes: dict[Path, str] = {}
|
||||
deletes: set[Path] = set()
|
||||
summaries: list[_PatchSummary] = []
|
||||
|
||||
for edit in edits:
|
||||
@@ -183,7 +183,6 @@ class ApplyPatchTool(_FsTool):
|
||||
if uses_crlf:
|
||||
new_norm = new_norm.replace("\n", "\r\n")
|
||||
writes[source] = new_norm
|
||||
deletes.discard(source)
|
||||
added, deleted = _line_diff_stats(content, new_norm)
|
||||
action_name = "update"
|
||||
else:
|
||||
@@ -191,7 +190,6 @@ class ApplyPatchTool(_FsTool):
|
||||
if new_norm and not new_norm.endswith("\n"):
|
||||
new_norm += "\n"
|
||||
writes[source] = new_norm
|
||||
deletes.discard(source)
|
||||
added = _text_line_count(new_norm)
|
||||
deleted = 0
|
||||
action_name = "add"
|
||||
@@ -246,7 +244,6 @@ class ApplyPatchTool(_FsTool):
|
||||
new_norm = new_norm.replace("\n", "\r\n")
|
||||
|
||||
writes[source] = new_norm
|
||||
deletes.discard(source)
|
||||
added, deleted = _line_diff_stats(content, new_norm)
|
||||
summaries.append(
|
||||
_PatchSummary(
|
||||
@@ -254,62 +251,6 @@ class ApplyPatchTool(_FsTool):
|
||||
)
|
||||
)
|
||||
|
||||
elif action == "delete":
|
||||
old_text = edit.get("old_text") or ""
|
||||
if not old_text:
|
||||
raise _PatchError(f"old_text required for delete: {path}")
|
||||
|
||||
pending = writes.get(source)
|
||||
if pending is not None:
|
||||
content = pending
|
||||
elif source.exists():
|
||||
raw = source.read_bytes()
|
||||
try:
|
||||
content = raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise _PatchError(f"file is not UTF-8 text: {path}")
|
||||
else:
|
||||
raise _PatchError(f"file to update does not exist: {path}")
|
||||
|
||||
if pending is None and not source.is_file():
|
||||
raise _PatchError(f"path to update is not a file: {path}")
|
||||
|
||||
uses_crlf = "\r\n" in content
|
||||
norm_content = content.replace("\r\n", "\n")
|
||||
norm_old = old_text.replace("\r\n", "\n")
|
||||
|
||||
pos = norm_content.find(norm_old)
|
||||
if pos < 0:
|
||||
raise _PatchError(f"old_text not found in {path}")
|
||||
if norm_content.find(norm_old, pos + 1) >= 0:
|
||||
raise _PatchError(f"old_text appears multiple times in {path}")
|
||||
|
||||
if norm_old == norm_content:
|
||||
deletes.add(source)
|
||||
writes.pop(source, None)
|
||||
added, deleted = 0, _text_line_count(content)
|
||||
summaries.append(
|
||||
_PatchSummary(
|
||||
action="delete", path=path, added=added, deleted=deleted
|
||||
)
|
||||
)
|
||||
else:
|
||||
new_norm = (
|
||||
norm_content[:pos] + norm_content[pos + len(norm_old) :]
|
||||
)
|
||||
if new_norm and not new_norm.endswith("\n"):
|
||||
new_norm += "\n"
|
||||
if uses_crlf:
|
||||
new_norm = new_norm.replace("\n", "\r\n")
|
||||
writes[source] = new_norm
|
||||
deletes.discard(source)
|
||||
added, deleted = _line_diff_stats(content, new_norm)
|
||||
summaries.append(
|
||||
_PatchSummary(
|
||||
action="update", path=path, added=added, deleted=deleted
|
||||
)
|
||||
)
|
||||
|
||||
else:
|
||||
raise _PatchError(f"unknown action: {action}")
|
||||
|
||||
@@ -319,13 +260,10 @@ class ApplyPatchTool(_FsTool):
|
||||
)
|
||||
|
||||
backups: dict[Path, bytes | None] = {}
|
||||
for path in set(writes) | deletes:
|
||||
for path in writes:
|
||||
backups[path] = path.read_bytes() if path.exists() else None
|
||||
|
||||
try:
|
||||
for path in deletes:
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
for path, content in writes.items():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8", newline="")
|
||||
@@ -339,7 +277,7 @@ class ApplyPatchTool(_FsTool):
|
||||
path.write_bytes(data)
|
||||
raise
|
||||
|
||||
for path in set(writes) | deletes:
|
||||
for path in writes:
|
||||
self._file_states.record_write(path)
|
||||
return "Patch applied:\n" + "\n".join(
|
||||
_format_summary(summary) for summary in summaries
|
||||
|
||||
@@ -9,6 +9,7 @@ from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.schema import ArraySchema, BooleanSchema, IntegerSchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig
|
||||
from nanobot.config.schema import Base
|
||||
|
||||
@@ -113,7 +114,12 @@ class CliAppsTool(Tool):
|
||||
working_dir: str | None = None,
|
||||
timeout: int | None = None,
|
||||
) -> str:
|
||||
manager = CliAppManager(workspace=self.workspace, runtime=self.runtime)
|
||||
access = current_tool_workspace(
|
||||
self.workspace,
|
||||
restrict_to_workspace=self.restrict_to_workspace,
|
||||
)
|
||||
workspace = access.project_path or self.workspace
|
||||
manager = CliAppManager(workspace=workspace, runtime=self.runtime)
|
||||
try:
|
||||
return manager.run(
|
||||
name,
|
||||
@@ -121,7 +127,7 @@ class CliAppsTool(Tool):
|
||||
json_output=bool(json),
|
||||
working_dir=working_dir,
|
||||
timeout=timeout,
|
||||
restrict_to_workspace=self.restrict_to_workspace,
|
||||
restrict_to_workspace=access.restrict_to_workspace,
|
||||
)
|
||||
except CliAppError as exc:
|
||||
return f"Error: {exc.message}"
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
"""Runtime context for tool construction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextvars import ContextVar, Token
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Protocol, runtime_checkable
|
||||
|
||||
_CURRENT_REQUEST_CONTEXT: ContextVar["RequestContext | None"] = ContextVar(
|
||||
"nanobot_tool_request_context",
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RequestContext:
|
||||
@@ -21,6 +27,23 @@ class ContextAware(Protocol):
|
||||
...
|
||||
|
||||
|
||||
def bind_request_context(ctx: RequestContext) -> Token[RequestContext | None]:
|
||||
return _CURRENT_REQUEST_CONTEXT.set(ctx)
|
||||
|
||||
|
||||
def reset_request_context(token: Token[RequestContext | None]) -> None:
|
||||
_CURRENT_REQUEST_CONTEXT.reset(token)
|
||||
|
||||
|
||||
def current_request_context() -> RequestContext | None:
|
||||
return _CURRENT_REQUEST_CONTEXT.get()
|
||||
|
||||
|
||||
def current_request_session_key() -> str | None:
|
||||
ctx = current_request_context()
|
||||
return ctx.session_key if ctx else None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolContext:
|
||||
config: Any
|
||||
@@ -33,3 +56,4 @@ class ToolContext:
|
||||
provider_snapshot_loader: Callable[[], Any] | None = None
|
||||
image_generation_provider_configs: dict[str, Any] | None = None
|
||||
timezone: str = "UTC"
|
||||
workspace_sandbox: Any | None = None
|
||||
|
||||
@@ -10,6 +10,7 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.context import current_request_session_key
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.schema import BooleanSchema, IntegerSchema, StringSchema, tool_parameters_schema
|
||||
|
||||
@@ -43,6 +44,7 @@ class ExecSessionInfo:
|
||||
idle_s: float
|
||||
remaining_s: float
|
||||
returncode: int | None
|
||||
owner_session_key: str | None = None
|
||||
|
||||
|
||||
class _ExecSession:
|
||||
@@ -54,11 +56,13 @@ class _ExecSession:
|
||||
command: str,
|
||||
cwd: str,
|
||||
timeout: int | None,
|
||||
owner_session_key: str | None = None,
|
||||
) -> None:
|
||||
self.session_id = session_id
|
||||
self.process = process
|
||||
self.command = command
|
||||
self.cwd = cwd
|
||||
self.owner_session_key = owner_session_key
|
||||
self.started_at = time.monotonic()
|
||||
# timeout None/0 means no limit; an infinite deadline is never reached.
|
||||
self.deadline = time.monotonic() + timeout if timeout else float("inf")
|
||||
@@ -175,6 +179,7 @@ class ExecSessionManager:
|
||||
login: bool,
|
||||
yield_time_ms: int,
|
||||
max_output_chars: int,
|
||||
owner_session_key: str | None = None,
|
||||
) -> tuple[str, _SessionPoll]:
|
||||
async with self._lock:
|
||||
await self._cleanup_locked()
|
||||
@@ -188,6 +193,7 @@ class ExecSessionManager:
|
||||
command=command,
|
||||
cwd=cwd,
|
||||
timeout=timeout,
|
||||
owner_session_key=owner_session_key,
|
||||
)
|
||||
self._sessions[session_id] = session
|
||||
|
||||
@@ -206,12 +212,19 @@ class ExecSessionManager:
|
||||
terminate: bool,
|
||||
yield_time_ms: int,
|
||||
max_output_chars: int,
|
||||
owner_session_key: str | None = None,
|
||||
) -> _SessionPoll:
|
||||
async with self._lock:
|
||||
await self._cleanup_locked()
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
raise KeyError(session_id)
|
||||
if (
|
||||
owner_session_key
|
||||
and session.owner_session_key
|
||||
and session.owner_session_key != owner_session_key
|
||||
):
|
||||
raise KeyError(session_id)
|
||||
|
||||
if chars:
|
||||
error = await session.write(chars)
|
||||
@@ -236,7 +249,7 @@ class ExecSessionManager:
|
||||
self._sessions.pop(session_id, None)
|
||||
return poll
|
||||
|
||||
async def list(self) -> list[ExecSessionInfo]:
|
||||
async def list(self, *, owner_session_key: str | None = None) -> list[ExecSessionInfo]:
|
||||
async with self._lock:
|
||||
await self._cleanup_locked()
|
||||
now = time.monotonic()
|
||||
@@ -249,8 +262,12 @@ class ExecSessionManager:
|
||||
idle_s=max(0.0, now - session.last_access),
|
||||
remaining_s=max(0.0, session.deadline - now),
|
||||
returncode=session.process.returncode,
|
||||
owner_session_key=session.owner_session_key,
|
||||
)
|
||||
for session_id, session in sorted(self._sessions.items())
|
||||
if not owner_session_key
|
||||
or not session.owner_session_key
|
||||
or session.owner_session_key == owner_session_key
|
||||
]
|
||||
|
||||
async def _cleanup_locked(self) -> None:
|
||||
@@ -477,6 +494,7 @@ class WriteStdinTool(Tool):
|
||||
terminate=terminate,
|
||||
yield_time_ms=clamp_session_int(yield_time_ms, DEFAULT_YIELD_MS, 0, MAX_YIELD_MS),
|
||||
max_output_chars=output_limit,
|
||||
owner_session_key=current_request_session_key(),
|
||||
)
|
||||
return format_session_poll(session_id, poll)
|
||||
except KeyError:
|
||||
@@ -510,6 +528,7 @@ class WriteStdinTool(Tool):
|
||||
terminate=terminate if first else False,
|
||||
yield_time_ms=step_ms,
|
||||
max_output_chars=max_output_chars,
|
||||
owner_session_key=current_request_session_key(),
|
||||
)
|
||||
first = False
|
||||
if poll.output:
|
||||
@@ -573,7 +592,9 @@ class ListExecSessionsTool(Tool):
|
||||
|
||||
async def execute(self, **kwargs: Any) -> str:
|
||||
try:
|
||||
sessions = await self._manager.list()
|
||||
sessions = await self._manager.list(
|
||||
owner_session_key=current_request_session_key(),
|
||||
)
|
||||
if not sessions:
|
||||
return "No active exec sessions."
|
||||
lines = []
|
||||
|
||||
@@ -10,6 +10,7 @@ from typing import Any
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.file_state import FileStates, _hash_file, current_file_states
|
||||
from nanobot.agent.tools.path_utils import resolve_workspace_path
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
from nanobot.agent.tools.schema import (
|
||||
BooleanSchema,
|
||||
IntegerSchema,
|
||||
@@ -28,10 +29,18 @@ class _FsTool(Tool):
|
||||
allowed_dir: Path | None = None,
|
||||
extra_allowed_dirs: list[Path] | None = None,
|
||||
file_states: FileStates | None = None,
|
||||
restrict_to_workspace: bool | None = None,
|
||||
sandbox_restricts_workspace: bool = False,
|
||||
):
|
||||
self._workspace = workspace
|
||||
self._allowed_dir = allowed_dir
|
||||
self._extra_allowed_dirs = extra_allowed_dirs
|
||||
self._restrict_to_workspace = (
|
||||
bool(restrict_to_workspace)
|
||||
if restrict_to_workspace is not None
|
||||
else allowed_dir is not None
|
||||
)
|
||||
self._sandbox_restricts_workspace = sandbox_restricts_workspace
|
||||
# Explicit state is used by isolated runners like Dream/subagents.
|
||||
# Main AgentLoop tools leave this unset and resolve state from the
|
||||
# current async task, which keeps shared tool instances session-safe.
|
||||
@@ -46,13 +55,16 @@ class _FsTool(Tool):
|
||||
ctx.config.restrict_to_workspace
|
||||
or ctx.config.exec.sandbox
|
||||
)
|
||||
sandbox_restricts = bool(ctx.config.exec.sandbox)
|
||||
allowed_dir = Path(ctx.workspace) if restrict else None
|
||||
extra_read = [BUILTIN_SKILLS_DIR] if allowed_dir else None
|
||||
extra_read = [BUILTIN_SKILLS_DIR]
|
||||
return cls(
|
||||
workspace=Path(ctx.workspace),
|
||||
allowed_dir=allowed_dir,
|
||||
extra_allowed_dirs=extra_read,
|
||||
file_states=ctx.file_state_store,
|
||||
restrict_to_workspace=ctx.config.restrict_to_workspace,
|
||||
sandbox_restricts_workspace=sandbox_restricts,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -62,13 +74,21 @@ class _FsTool(Tool):
|
||||
return current_file_states(self._fallback_file_states)
|
||||
|
||||
def _resolve(self, path: str) -> Path:
|
||||
access = current_tool_workspace(
|
||||
self._workspace,
|
||||
restrict_to_workspace=self._restrict_to_workspace,
|
||||
sandbox_restricts_workspace=self._sandbox_restricts_workspace,
|
||||
)
|
||||
return resolve_workspace_path(
|
||||
path,
|
||||
self._workspace,
|
||||
self._allowed_dir,
|
||||
access.project_path,
|
||||
access.allowed_root,
|
||||
self._extra_allowed_dirs,
|
||||
)
|
||||
|
||||
def _display_workspace(self) -> Path | None:
|
||||
return current_tool_workspace(self._workspace).project_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# read_file
|
||||
|
||||
@@ -14,6 +14,7 @@ from nanobot.agent.tools.schema import (
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.providers.image_generation import (
|
||||
@@ -21,6 +22,7 @@ from nanobot.providers.image_generation import (
|
||||
ImageGenerationProvider,
|
||||
get_image_gen_provider,
|
||||
)
|
||||
from nanobot.security.workspace_policy import WorkspaceBoundaryError, resolve_allowed_path
|
||||
from nanobot.utils.artifacts import (
|
||||
ArtifactError,
|
||||
generated_image_tool_result,
|
||||
@@ -131,18 +133,22 @@ class ImageGenerationTool(Tool):
|
||||
return cls(**kwargs)
|
||||
|
||||
def _resolve_reference_image(self, value: str) -> str:
|
||||
raw_path = Path(value).expanduser()
|
||||
path = raw_path if raw_path.is_absolute() else self.workspace / raw_path
|
||||
access = current_tool_workspace(self.workspace, restrict_to_workspace=True)
|
||||
workspace = access.project_path or self.workspace
|
||||
try:
|
||||
resolved = path.resolve(strict=True)
|
||||
except OSError as exc:
|
||||
raise ImageGenerationError(f"reference image not found: {value}") from exc
|
||||
|
||||
allowed_roots = [self.workspace.resolve(), get_media_dir().resolve()]
|
||||
if not any(_is_relative_to(resolved, root) for root in allowed_roots):
|
||||
resolved = resolve_allowed_path(
|
||||
value,
|
||||
workspace=workspace,
|
||||
allowed_root=access.allowed_root,
|
||||
extra_allowed_roots=[get_media_dir()] if access.allowed_root is not None else None,
|
||||
strict=True,
|
||||
)
|
||||
except WorkspaceBoundaryError as exc:
|
||||
raise ImageGenerationError(
|
||||
"reference_images must be inside the workspace or nanobot media directory"
|
||||
)
|
||||
) from exc
|
||||
except OSError as exc:
|
||||
raise ImageGenerationError(f"reference image not found: {value}") from exc
|
||||
if not resolved.is_file():
|
||||
raise ImageGenerationError(f"reference image is not a file: {value}")
|
||||
raw = resolved.read_bytes()
|
||||
@@ -201,11 +207,3 @@ class ImageGenerationTool(Tool):
|
||||
return generated_image_tool_result(artifacts)
|
||||
except (ArtifactError, ImageGenerationError, OSError) as exc:
|
||||
return f"Error: {exc}"
|
||||
|
||||
|
||||
def _is_relative_to(path: Path, root: Path) -> bool:
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -8,6 +8,7 @@ from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.path_utils import resolve_workspace_path
|
||||
from nanobot.agent.tools.schema import ArraySchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.security.workspace_access import current_tool_workspace
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.config.paths import get_workspace_path
|
||||
|
||||
@@ -149,15 +150,19 @@ class MessageTool(Tool, ContextAware):
|
||||
def _resolve_media(self, media: list[str]) -> list[str]:
|
||||
"""Resolve local media attachments and enforce workspace restriction when enabled."""
|
||||
resolved: list[str] = []
|
||||
allowed_dir = self._workspace if self._restrict_to_workspace else None
|
||||
access = current_tool_workspace(
|
||||
self._workspace,
|
||||
restrict_to_workspace=self._restrict_to_workspace,
|
||||
)
|
||||
workspace = access.project_path or self._workspace
|
||||
for p in media:
|
||||
if p.startswith(("http://", "https://")):
|
||||
resolved.append(p)
|
||||
elif not self._restrict_to_workspace:
|
||||
elif not access.restrict_to_workspace:
|
||||
path = Path(p).expanduser()
|
||||
resolved.append(p if path.is_absolute() else str(self._workspace / path))
|
||||
resolved.append(p if path.is_absolute() else str(workspace / path))
|
||||
else:
|
||||
resolved.append(str(resolve_workspace_path(p, self._workspace, allowed_dir)))
|
||||
resolved.append(str(resolve_workspace_path(p, workspace, access.allowed_root)))
|
||||
return resolved
|
||||
|
||||
async def execute(
|
||||
|
||||
@@ -3,21 +3,15 @@
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.config.paths import get_media_dir
|
||||
|
||||
WORKSPACE_BOUNDARY_NOTE = (
|
||||
" (this is a hard policy boundary, not a transient failure; "
|
||||
"do not retry with shell tricks or alternative tools, and ask "
|
||||
"the user how to proceed if the resource is genuinely required)"
|
||||
from nanobot.security.workspace_policy import (
|
||||
is_path_within,
|
||||
resolve_allowed_path,
|
||||
)
|
||||
|
||||
|
||||
def is_under(path: Path, directory: Path) -> bool:
|
||||
"""Return True when path resolves under directory."""
|
||||
try:
|
||||
path.relative_to(directory.resolve())
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
return is_path_within(path, directory)
|
||||
|
||||
|
||||
def resolve_workspace_path(
|
||||
@@ -27,16 +21,10 @@ def resolve_workspace_path(
|
||||
extra_allowed_dirs: list[Path] | None = None,
|
||||
) -> Path:
|
||||
"""Resolve path against workspace and enforce allowed directory containment."""
|
||||
p = Path(path).expanduser()
|
||||
if not p.is_absolute() and workspace:
|
||||
p = workspace / p
|
||||
resolved = p.resolve()
|
||||
if allowed_dir:
|
||||
media_path = get_media_dir().resolve()
|
||||
all_dirs = [allowed_dir, media_path, *(extra_allowed_dirs or [])]
|
||||
if not any(is_under(resolved, d) for d in all_dirs):
|
||||
raise PermissionError(
|
||||
f"Path {path} is outside allowed directory {allowed_dir}"
|
||||
+ WORKSPACE_BOUNDARY_NOTE
|
||||
)
|
||||
return resolved
|
||||
extra_roots = [get_media_dir(), *(extra_allowed_dirs or [])] if allowed_dir else None
|
||||
return resolve_allowed_path(
|
||||
path,
|
||||
workspace=workspace,
|
||||
allowed_root=allowed_dir,
|
||||
extra_allowed_roots=extra_roots,
|
||||
)
|
||||
|
||||
@@ -42,6 +42,9 @@ class RuntimeState(Protocol):
|
||||
@property
|
||||
def exec_config(self) -> Any: ...
|
||||
|
||||
@property
|
||||
def workspace_sandbox(self) -> Any: ...
|
||||
|
||||
@property
|
||||
def subagents(self) -> Any: ...
|
||||
|
||||
|
||||
@@ -101,9 +101,10 @@ class _SearchTool(_FsTool):
|
||||
_IGNORE_DIRS = set(ListDirTool._IGNORE_DIRS)
|
||||
|
||||
def _display_path(self, target: Path, root: Path) -> str:
|
||||
if self._workspace:
|
||||
workspace = self._display_workspace()
|
||||
if workspace:
|
||||
with suppress(ValueError):
|
||||
return target.relative_to(self._workspace).as_posix()
|
||||
return target.relative_to(workspace).as_posix()
|
||||
return target.relative_to(root).as_posix()
|
||||
|
||||
def _iter_files(self, root: Path) -> Iterable[Path]:
|
||||
|
||||
@@ -3,16 +3,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.runtime_state import RuntimeState
|
||||
from nanobot.config.schema import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
|
||||
class MyToolConfig(Base):
|
||||
"""Self-inspection tool configuration."""
|
||||
@@ -33,6 +35,12 @@ def _has_real_attr(obj: Any, key: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _is_subagent_status(value: Any) -> bool:
|
||||
from nanobot.agent.subagent import SubagentStatus
|
||||
|
||||
return isinstance(value, SubagentStatus)
|
||||
|
||||
|
||||
class MyTool(Tool, ContextAware):
|
||||
"""Check and set the agent loop's runtime configuration."""
|
||||
|
||||
@@ -68,6 +76,7 @@ class MyTool(Tool, ContextAware):
|
||||
"_current_iteration", # updated by runner only
|
||||
"exec_config", # inspect allowed (e.g. check sandbox), modify blocked
|
||||
"web_config", # inspect allowed (e.g. check enable), modify blocked
|
||||
"workspace_sandbox", # read-only view of workspace enforcement level
|
||||
})
|
||||
|
||||
_DENIED_ATTRS = frozenset({
|
||||
@@ -214,7 +223,7 @@ class MyTool(Tool, ContextAware):
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _format_status(st: SubagentStatus, indent: str = " ") -> str:
|
||||
def _format_status(st: "SubagentStatus", indent: str = " ") -> str:
|
||||
elapsed = time.monotonic() - st.started_at
|
||||
tool_summary = ", ".join(
|
||||
f"{e.get('name', '?')}({e.get('status', '?')})" for e in st.tool_events[-5:]
|
||||
@@ -232,14 +241,14 @@ class MyTool(Tool, ContextAware):
|
||||
|
||||
@staticmethod
|
||||
def _format_value(val: Any, key: str = "") -> str:
|
||||
if isinstance(val, SubagentStatus):
|
||||
if _is_subagent_status(val):
|
||||
header = f"Subagent [{val.task_id}] '{val.label}'"
|
||||
detail = MyTool._format_status(val, " ")
|
||||
return f"{header}\n task: {val.task_description}\n{detail}"
|
||||
# SubagentManager: delegate to its _task_statuses dict
|
||||
if hasattr(val, "_task_statuses") and isinstance(val._task_statuses, dict):
|
||||
return MyTool._format_value(val._task_statuses, key)
|
||||
if isinstance(val, dict) and val and isinstance(next(iter(val.values())), SubagentStatus):
|
||||
if isinstance(val, dict) and val and _is_subagent_status(next(iter(val.values()))):
|
||||
prefix = f"{key}: " if key else ""
|
||||
lines = [f"{prefix}{len(val)} subagent(s):"]
|
||||
for tid, st in val.items():
|
||||
@@ -349,7 +358,7 @@ class MyTool(Tool, ContextAware):
|
||||
parts.append(self._format_value(getattr(state, k, None), k))
|
||||
parts.append(self._format_value(state.model_preset, "model_preset"))
|
||||
# Other useful top-level keys shown in description
|
||||
for k in ("workspace", "provider_retry_mode", "max_tool_result_chars", "_current_iteration", "web_config", "exec_config", "subagents"):
|
||||
for k in ("workspace", "provider_retry_mode", "max_tool_result_chars", "_current_iteration", "web_config", "exec_config", "workspace_sandbox", "subagents"):
|
||||
if _has_real_attr(state, k):
|
||||
parts.append(self._format_value(getattr(state, k, None), k))
|
||||
# Token usage
|
||||
|
||||
@@ -25,10 +25,13 @@ from nanobot.agent.tools.exec_session import (
|
||||
clamp_session_int,
|
||||
format_session_poll,
|
||||
)
|
||||
from nanobot.agent.tools.context import current_request_session_key
|
||||
from nanobot.agent.tools.sandbox import wrap_command
|
||||
from nanobot.agent.tools.schema import BooleanSchema, IntegerSchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.security.workspace_policy import is_path_within
|
||||
|
||||
_IS_WINDOWS = sys.platform == "win32"
|
||||
|
||||
@@ -140,6 +143,7 @@ class ExecTool(Tool):
|
||||
working_dir=ctx.workspace,
|
||||
timeout=cfg.timeout,
|
||||
restrict_to_workspace=ctx.config.restrict_to_workspace,
|
||||
webui_allow_local_service_access=ctx.config.webui_allow_local_service_access,
|
||||
sandbox=cfg.sandbox,
|
||||
path_append=cfg.path_append,
|
||||
allowed_env_keys=cfg.allowed_env_keys,
|
||||
@@ -154,6 +158,8 @@ class ExecTool(Tool):
|
||||
deny_patterns: list[str] | None = None,
|
||||
allow_patterns: list[str] | None = None,
|
||||
restrict_to_workspace: bool = False,
|
||||
webui_allow_local_service_access: bool = True,
|
||||
allow_local_preview_access: bool | None = None,
|
||||
sandbox: str = "",
|
||||
path_append: str = "",
|
||||
allowed_env_keys: list[str] | None = None,
|
||||
@@ -183,6 +189,9 @@ class ExecTool(Tool):
|
||||
]
|
||||
self.allow_patterns = allow_patterns or []
|
||||
self.restrict_to_workspace = restrict_to_workspace
|
||||
if allow_local_preview_access is not None:
|
||||
webui_allow_local_service_access = allow_local_preview_access
|
||||
self.webui_allow_local_service_access = webui_allow_local_service_access
|
||||
self.path_append = path_append
|
||||
self.allowed_env_keys = allowed_env_keys or []
|
||||
self._session_manager = session_manager or DEFAULT_EXEC_SESSION_MANAGER
|
||||
@@ -313,6 +322,7 @@ class ExecTool(Tool):
|
||||
shell_program=prepared.shell_program,
|
||||
login=prepared.login,
|
||||
yield_time_ms=clamp_session_int(yield_time_ms, DEFAULT_YIELD_MS, 0, MAX_YIELD_MS),
|
||||
owner_session_key=current_request_session_key(),
|
||||
max_output_chars=clamp_session_int(
|
||||
max_output_chars,
|
||||
DEFAULT_MAX_OUTPUT_CHARS,
|
||||
@@ -346,29 +356,39 @@ class ExecTool(Tool):
|
||||
shell: str | None = None,
|
||||
login: bool | None = None,
|
||||
) -> _PreparedCommand | str:
|
||||
cwd = working_dir or self.working_dir or os.getcwd()
|
||||
access = current_tool_workspace(
|
||||
self.working_dir,
|
||||
restrict_to_workspace=self.restrict_to_workspace,
|
||||
sandbox_restricts_workspace=bool(self.sandbox),
|
||||
)
|
||||
workspace_root = str(access.project_path) if access.project_path is not None else self.working_dir
|
||||
cwd = working_dir or workspace_root or os.getcwd()
|
||||
|
||||
# Prevent an LLM-supplied working_dir from escaping the configured
|
||||
# workspace when restrict_to_workspace is enabled (#2826). Without
|
||||
# this, a caller can pass working_dir="/etc" and then all absolute
|
||||
# paths under /etc would pass the _guard_command check that anchors
|
||||
# on cwd.
|
||||
if self.restrict_to_workspace and self.working_dir:
|
||||
if access.restrict_to_workspace and workspace_root:
|
||||
try:
|
||||
requested = Path(cwd).expanduser().resolve()
|
||||
workspace_root = Path(self.working_dir).expanduser().resolve()
|
||||
resolved_root = Path(workspace_root).expanduser().resolve()
|
||||
except Exception:
|
||||
return (
|
||||
"Error: working_dir could not be resolved"
|
||||
+ _WORKSPACE_BOUNDARY_NOTE
|
||||
)
|
||||
if requested != workspace_root and workspace_root not in requested.parents:
|
||||
if not is_path_within(requested, resolved_root):
|
||||
return (
|
||||
"Error: working_dir is outside the configured workspace"
|
||||
+ _WORKSPACE_BOUNDARY_NOTE
|
||||
)
|
||||
|
||||
guard_error = self._guard_command(command, cwd)
|
||||
guard_error = self._guard_command(
|
||||
command,
|
||||
cwd,
|
||||
restrict_to_workspace=access.restrict_to_workspace,
|
||||
)
|
||||
if guard_error:
|
||||
return guard_error
|
||||
|
||||
@@ -379,7 +399,7 @@ class ExecTool(Tool):
|
||||
self.sandbox,
|
||||
)
|
||||
else:
|
||||
workspace = self.working_dir or cwd
|
||||
workspace = workspace_root or cwd
|
||||
command = wrap_command(self.sandbox, command, workspace, cwd)
|
||||
cwd = str(Path(workspace).resolve())
|
||||
|
||||
@@ -528,7 +548,13 @@ class ExecTool(Tool):
|
||||
env[key] = val
|
||||
return env
|
||||
|
||||
def _guard_command(self, command: str, cwd: str) -> str | None:
|
||||
def _guard_command(
|
||||
self,
|
||||
command: str,
|
||||
cwd: str,
|
||||
*,
|
||||
restrict_to_workspace: bool | None = None,
|
||||
) -> str | None:
|
||||
"""Best-effort safety guard for potentially destructive commands."""
|
||||
cmd = command.strip()
|
||||
lower = cmd.lower()
|
||||
@@ -548,11 +574,17 @@ class ExecTool(Tool):
|
||||
return "Error: Command blocked by allowlist filter (not in allowlist)"
|
||||
|
||||
from nanobot.security.network import contains_internal_url
|
||||
if contains_internal_url(cmd):
|
||||
if contains_internal_url(
|
||||
cmd,
|
||||
allow_loopback=current_scope_allows_loopback(
|
||||
enabled=self.webui_allow_local_service_access,
|
||||
),
|
||||
):
|
||||
# The runner turns this marker into a non-retryable security hint.
|
||||
return "Error: Command blocked by safety guard (internal/private URL detected)"
|
||||
|
||||
if self.restrict_to_workspace:
|
||||
should_restrict = self.restrict_to_workspace if restrict_to_workspace is None else restrict_to_workspace
|
||||
if should_restrict:
|
||||
if "..\\" in cmd or "../" in cmd:
|
||||
return (
|
||||
"Error: Command blocked by safety guard (path traversal detected)"
|
||||
@@ -577,11 +609,9 @@ class ExecTool(Tool):
|
||||
continue
|
||||
|
||||
media_path = get_media_dir().resolve()
|
||||
if (p.is_absolute()
|
||||
and cwd_path not in p.parents
|
||||
and p != cwd_path
|
||||
and media_path not in p.parents
|
||||
and p != media_path
|
||||
if p.is_absolute() and not (
|
||||
is_path_within(p, cwd_path)
|
||||
or is_path_within(p, media_path)
|
||||
):
|
||||
return (
|
||||
"Error: Command blocked by safety guard (path outside working dir)"
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.schema import NumberSchema, StringSchema, tool_parameters_schema
|
||||
from nanobot.security.workspace_access import current_workspace_scope
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
@@ -91,4 +92,5 @@ class SpawnTool(Tool, ContextAware):
|
||||
session_key=self._session_key.get(),
|
||||
origin_message_id=self._origin_message_id.get(),
|
||||
temperature=temperature,
|
||||
workspace_scope=current_workspace_scope(),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user