Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: code agent sandbox diretory bugs

zhaozixuanb643a92cc0a0
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 9057872913..df0b359539 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -50,6 +50,7 @@ from jiuwenswarm.server.runtime.session.session_history import (
)
from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (
build_filesystem_policy,
+ effective_files_from_policy,
find_auto_managed_match,
find_nested_files_conflict,
list_effective_sandbox_files,
@@ -4164,8 +4165,8 @@ class AgentWebSocketServer:
return project_dir.strip()
try:
agent = self._agent_manager.get_agent_nowait(channel_id)
- except Exception as exc: # noqa: BLE001
- logger.debug("[command.sandbox] get_agent_nowait failed: %s", exc)
+ except Exception as exc:
+ logger.info("[command.sandbox] get_agent_nowait failed: %s", exc)
return None
adapter = self._resolve_adapter(agent)
if adapter is None:
@@ -4217,6 +4218,22 @@ class AgentWebSocketServer:
return False
return bool(getattr(adapter, "_is_code_agent", False))
+ @staticmethod
+ def _effective_files_from_adapter(adapter: Any) -> dict[str, list[dict[str, str]]] | None:
+ """Read effective sandbox file mounts from the adapter's active sysop card."""
+ card = getattr(adapter, "_sys_operation_card", None)
+ if card is None:
+ return None
+ gateway_config = getattr(card, "gateway_config", None)
+ launcher = getattr(gateway_config, "launcher_config", None) if gateway_config else None
+ extra_params = getattr(launcher, "extra_params", None) if launcher else None
+ if not isinstance(extra_params, dict):
+ return None
+ policy = extra_params.get("policy")
+ if not isinstance(policy, dict):
+ return None
+ return effective_files_from_policy(policy)
+
def _attach_effective_sandbox_files(
self,
payload: dict[str, Any],
@@ -4225,25 +4242,41 @@ class AgentWebSocketServer:
) -> None:
"""Inject ``effective_files`` into the ``/sandbox`` response payload.
- ``effective_files`` summarises what the sandbox will actually grant
- write access to (and what it will always deny) -- the union of
- intrinsic agent files / ``daily_memory`` / current project dir plus
- the user-configured allow list, and jiuwenswarm's own ``config.yaml``
- plus the user-configured deny list. The TUI ``/sandbox status`` and
- ``/sandbox files list`` panels render this directly under
- ``files.allow_write`` / ``files.deny_write`` so the user sees the
- same set the policy builder would compute at sandbox-start time.
-
- The project dir reported in ``allow_write`` is sourced from the live
- adapter (see :meth:`_resolve_active_project_dir`) so the panel
- matches the user's trusted directory rather than the agent-server's
- cwd, which is usually ``~/.jiuwenswarm`` and not what the user means
- by "project".
-
- Best-effort: failures are logged and swallowed so the underlying
- sub-command response still goes back to the client.
+ Prefer the filesystem policy cached on the active adapter's sysop card
+ (same payload jiuwenbox uses at exec time). Fall back to a fresh build
+ when no matching agent/sysop exists yet.
"""
try:
+ project_dir = self._resolve_active_project_dir(channel_id, params)
+ adapter = None
+ try:
+ agent = self._agent_manager.get_agent_nowait(
+ channel_id,
+ project_dir=project_dir,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[command.sandbox] get_agent_nowait failed: %s", exc)
+ agent = None
+ if agent is not None:
+ adapter = self._resolve_adapter(agent)
+ if adapter is not None:
+ adapter_project_dir = getattr(adapter, "_project_dir", None)
+ if (
+ project_dir
+ and adapter_project_dir
+ and str(adapter_project_dir) != str(project_dir)
+ ):
+ logger.warning(
+ "[command.sandbox] project_dir mismatch for effective_files: "
+ "client=%r adapter=%r",
+ project_dir,
+ adapter_project_dir,
+ )
+ cached = self._effective_files_from_adapter(adapter)
+ if cached is not None:
+ payload["effective_files"] = cached
+ return
+
files_runtime: dict[str, Any] | None = None
runtime = payload.get("runtime")
if isinstance(runtime, dict):
@@ -4256,7 +4289,6 @@ class AgentWebSocketServer:
files_runtime = files_in_payload
if files_runtime is None:
files_runtime = get_sandbox_runtime().get("files") or {}
- project_dir = self._resolve_active_project_dir(channel_id, params)
is_code_agent = self._resolve_active_is_code_agent(channel_id)
payload["effective_files"] = list_effective_sandbox_files(
files_runtime,
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
index f71bd5d341..293b7c91cd 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import hashlib
import logging
import os
from pathlib import Path
@@ -232,6 +233,15 @@ def _resolve_project_dir(override: str | Path | None) -> Path | None:
return None
+def _sandbox_isolation_custom_id(project_dir: str | Path | None) -> str:
+ """Stable SysOperation isolation key suffix for per-project sandbox sharing."""
+ resolved = _resolve_project_dir(project_dir)
+ if resolved is None:
+ return "project_default"
+ digest = hashlib.sha256(str(resolved).encode("utf-8")).hexdigest()[:16]
+ return f"project_{digest}"
+
+
def build_filesystem_policy(
files_runtime: dict[str, Any] | None,
*,
@@ -354,6 +364,7 @@ def build_filesystem_policy(
_mount_rw_dir(resolved_workspace)
resolved_project = _resolve_project_dir(project_dir)
+ logger.info(f'zzx: resolved_project: {resolved_project}')
if resolved_project is not None:
_mount_rw_dir(resolved_project)
@@ -446,8 +457,12 @@ def create_sandbox_sysop_card(
if idle_check_interval is not None:
extra_params["idle_check_interval"] = idle_check_interval
+ isolation_custom_id = _sandbox_isolation_custom_id(project_dir)
gateway_config = SandboxGatewayConfig(
- isolation=SandboxIsolationConfig(container_scope=ContainerScope.SYSTEM),
+ isolation=SandboxIsolationConfig(
+ container_scope=ContainerScope.CUSTOM,
+ custom_id=isolation_custom_id,
+ ),
launcher_config=PreDeployLauncherConfig(
base_url=sandbox_url,
sandbox_type=sandbox_type,
@@ -465,6 +480,7 @@ def create_sandbox_sysop_card(
logger.info(
"[sysop_builder] sandbox SysOperationCard created:\n"
" base_url=%s sandbox_type=%s\n"
+ " isolation_custom_id=%s\n"
" idle_ttl=%s idle_check_interval=%s\n"
" preserve_file_sharing_mode=%s\n"
" excluded_commands(%d)=%s\n"
@@ -477,6 +493,7 @@ def create_sandbox_sysop_card(
" policy_mode=%s",
sandbox_url,
sandbox_type,
+ isolation_custom_id,
idle_ttl_seconds,
idle_check_interval,
_PRESERVE_FILE_SHARING_MODE,
@@ -554,6 +571,45 @@ def _resolve_display_path(raw: str | Path | None) -> str | None:
return None
+def _filesystem_policy_to_display_entries(
+ fs_policy: dict[str, Any],
+) -> dict[str, list[dict[str, str]]]:
+ """Convert ``filesystem_policy.bind_mounts`` into ``/sandbox`` display entries."""
+ allow: list[dict[str, str]] = []
+ deny: list[dict[str, str]] = []
+ read_only = {
+ str(path)
+ for path in (fs_policy.get("read_only") or [])
+ if str(path).strip()
+ }
+ for mount in fs_policy.get("bind_mounts") or []:
+ if not isinstance(mount, dict):
+ continue
+ host_path = str(mount.get("host_path") or mount.get("sandbox_path") or "").strip()
+ if not host_path:
+ continue
+ sandbox_path = str(mount.get("sandbox_path") or host_path).strip()
+ mount_mode = str(mount.get("mode") or "rw").lower()
+ access = "ro" if sandbox_path in read_only or mount_mode == "ro" else "rw"
+ kind = _classify_host_kind(host_path)
+ if kind == "directory" and host_path != "/":
+ display_path = host_path.rstrip("/") + "/"
+ else:
+ display_path = host_path
+ entry = {"path": display_path, "access": access, "kind": kind}
+ bucket = deny if access == "ro" else allow
+ _append_unique(bucket, entry)
+ return {"allow_write": allow, "deny_write": deny}
+
+
+def effective_files_from_policy(policy: dict[str, Any]) -> dict[str, list[dict[str, str]]]:
+ """Derive ``/sandbox`` display entries from a cached launcher policy dict."""
+ fs_policy = policy.get("filesystem_policy") if isinstance(policy, dict) else {}
+ if not isinstance(fs_policy, dict):
+ fs_policy = {}
+ return _filesystem_policy_to_display_entries(fs_policy)
+
+
def list_auto_managed_sandbox_paths(
project_dir: str | Path | None = None,
*,
@@ -738,6 +794,7 @@ __all__ = [
"build_filesystem_policy",
"create_sandbox_sysop_card",
"create_local_sysop_card",
+ "effective_files_from_policy",
"find_auto_managed_match",
"find_nested_files_conflict",
"list_auto_managed_sandbox_paths",