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

feat(concurrent_safe_rails): enhance tool binding with workspace and filesystem isolation

NickFuryXXX70982fc0961b
diff --git a/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py b/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
index 7a31eaf2f2..2d9c0fdc46 100644
--- a/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
+++ b/jiuwenswarm/agents/harness/common/rails/concurrent_safe_rails.py
@@ -16,6 +16,8 @@ the agent can use them.
from __future__ import annotations
import logging
+import hashlib
+import json
from copy import copy
from openjiuwen.core.runner import Runner
@@ -128,6 +130,16 @@ class ConcurrentSafeTaskPlanningRail(TaskPlanningRail):
workspace_dir = str(self.workspace.get_node_path(WorkspaceNode.TODO))
agent_id = getattr(getattr(agent, "card", None), "id", None)
language = self.system_prompt_builder.language if self.system_prompt_builder else "cn"
+ fs = self.sys_operation.fs()
+ # Tools retain their filesystem client and workspace. Include both
+ # bindings in the process-local registry ID, not only the agent ID.
+ binding = hashlib.sha256(
+ json.dumps([workspace_dir, id(fs)]).encode("utf-8")
+ ).hexdigest()[:24]
+ scoped_agent_id = f"{agent_id or 'todo'}_{binding}"
+
+ def matches_binding(tool):
+ return tool.workspace == workspace_dir and tool.fs is fs
tool_configs = [
(TodoCreateTool, False),
@@ -142,6 +154,9 @@ class ConcurrentSafeTaskPlanningRail(TaskPlanningRail):
if tool_instance:
for i, (tool_class, found) in enumerate(tool_configs):
if isinstance(tool_instance, tool_class):
+ if not matches_binding(tool_instance):
+ agent.ability_manager.remove(ability.name)
+ break
tool_configs[i] = (tool_class, True)
existing_tools.append(tool_instance)
break
@@ -150,9 +165,11 @@ class ConcurrentSafeTaskPlanningRail(TaskPlanningRail):
try:
for tool_class, found in tool_configs:
if not found:
- new_tool = tool_class(self.sys_operation, workspace_dir, language, agent_id)
+ new_tool = tool_class(self.sys_operation, workspace_dir, language, scoped_agent_id)
registered_tool = Runner.resource_mgr.get_tool(new_tool.card.id)
if registered_tool is not None:
+ if not isinstance(registered_tool, tool_class) or not matches_binding(registered_tool):
+ raise RuntimeError(f"Todo tool binding mismatch: {new_tool.card.id}")
agent.ability_manager.add(registered_tool.card)
tools.append(registered_tool)
continue
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
index cc2cf91f46..6d82bf3571 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -251,9 +251,18 @@ def _resolve_project_dir(override: str | Path | None) -> Path | None:
return None
-def _sandbox_isolation_custom_id(project_dir: str | Path | None) -> str:
+def _sandbox_isolation_custom_id(
+ project_dir: str | Path | None, *, shared_dir: str | Path | None = None,
+) -> str:
"""Stable SysOperation isolation key suffix for per-project sandbox sharing."""
resolved = _resolve_project_dir(project_dir)
+ if is_enterprise():
+ # Match the trusted workspace mounted for this tenant. A default
+ # project must not reuse another tenant's cached sandbox client.
+ root = Path(shared_dir if shared_dir is not None else get_agent_root_dir()).expanduser().resolve()
+ scope = json.dumps([str(root), str(resolved) if resolved is not None else None])
+ digest = hashlib.sha256(scope.encode("utf-8")).hexdigest()[:24]
+ return f"workspace_project_{digest}"
if resolved is None:
return "project_default"
digest = hashlib.sha256(str(resolved).encode("utf-8")).hexdigest()[:16]
@@ -634,7 +643,7 @@ def create_sandbox_sysop_card(
try:
if normalized_type == "yuanrong":
extra_params = _build_yuanrong_extra_params()
- isolation_custom_id = _sandbox_isolation_custom_id(project_dir)
+ isolation_custom_id = _sandbox_isolation_custom_id(project_dir, shared_dir=shared_dir)
gateway_config = SandboxGatewayConfig(
isolation=SandboxIsolationConfig(
container_scope=ContainerScope.CUSTOM,
@@ -692,7 +701,7 @@ 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)
+ isolation_custom_id = _sandbox_isolation_custom_id(project_dir, shared_dir=shared_dir)
gateway_config = SandboxGatewayConfig(
isolation=SandboxIsolationConfig(
container_scope=ContainerScope.CUSTOM,
diff --git a/tests/unit_tests/agentserver/rails/test_concurrent_safe_todo_lifecycle.py b/tests/unit_tests/agentserver/rails/test_concurrent_safe_todo_lifecycle.py
index fffd8d91bf..b3798537a3 100644
--- a/tests/unit_tests/agentserver/rails/test_concurrent_safe_todo_lifecycle.py
+++ b/tests/unit_tests/agentserver/rails/test_concurrent_safe_todo_lifecycle.py
@@ -25,12 +25,13 @@ class LocalFiles:
content=Path(path).read_text(encoding="utf-8")))
-def make_agent(tmp_path):
+def make_agent(tmp_path, fs=None):
+ fs = fs if fs is not None else LocalFiles()
agent = Mock(spec=DeepAgent)
agent.card = SimpleNamespace(id="todo-regression")
agent.system_prompt_builder = SimpleNamespace(language="cn")
agent.deep_config = SimpleNamespace(
- sys_operation=SimpleNamespace(fs=lambda: LocalFiles()),
+ sys_operation=SimpleNamespace(fs=lambda: fs),
workspace=SimpleNamespace(get_node_path=lambda node: tmp_path),
)
agent.ability_manager = Mock()
@@ -46,10 +47,11 @@ async def test_registered_create_instance_is_reset_and_new_round_replaces_list(t
add_tool=lambda tool: registry.setdefault(tool.card.id, tool),
)
monkeypatch.setattr(module, "Runner", SimpleNamespace(resource_mgr=manager))
+ fs = LocalFiles()
first = module.ConcurrentSafeTaskPlanningRail()
- first.init(make_agent(tmp_path))
+ first.init(make_agent(tmp_path, fs))
second = module.ConcurrentSafeTaskPlanningRail()
- second.init(make_agent(tmp_path))
+ second.init(make_agent(tmp_path, fs))
creator = first._find_todo_create_tool()
assert second._find_todo_create_tool() is creator
session = SimpleNamespace(get_session_id=lambda: "session")
@@ -135,3 +137,41 @@ async def test_uninitialized_rail_skips_inner_callback():
ctx = AgentCallbackContext(agent=SimpleNamespace())
await rail.after_tool_call(ctx)
assert not hasattr(ctx.agent, "load_state")
+
+
[email protected]("different_workspace,different_fs", [(True, False), (False, True), (True, True)])
+async def test_registry_keeps_workspace_and_filesystem_bindings_isolated(
+ tmp_path, monkeypatch, different_workspace, different_fs,
+):
+ registry = {}
+ monkeypatch.setattr(module, "Runner", SimpleNamespace(resource_mgr=SimpleNamespace(
+ get_tool=lambda tool_id: registry.get(tool_id),
+ add_tool=lambda tool: registry.setdefault(tool.card.id, tool),
+ )))
+ first_fs = LocalFiles()
+ second_fs = LocalFiles() if different_fs else first_fs
+ first = module.ConcurrentSafeTaskPlanningRail()
+ first.init(make_agent(tmp_path / "a", first_fs))
+ second_root = tmp_path / ("b" if different_workspace else "a")
+ second_agent = make_agent(second_root, second_fs)
+ # An inherited ability card must not keep pointing at the old binding.
+ second_agent.ability_manager.list.return_value = [tool.card for tool in first.tools]
+ second = module.ConcurrentSafeTaskPlanningRail()
+ second.init(second_agent)
+ for old, new in zip(first.tools, second.tools):
+ assert old.card.id != new.card.id
+ assert registry[new.card.id] is new
+ assert new.fs is second_fs
+ assert new.workspace == str(second_root)
+ assert second_agent.ability_manager.remove.call_count == 3
+ if different_workspace:
+ await first._find_todo_create_tool()._create_from_list("same-session", [
+ {"id": "a", "content": "Tenant A"},
+ ])
+ await second._find_todo_create_tool()._create_from_list("same-session", [
+ {"id": "b", "content": "Tenant B"},
+ ])
+ for rail, expected in ((first, "a"), (second, "b")):
+ for tool in rail.tools:
+ assert [todo.id for todo in await tool.load_todos("same-session")] == [expected]
diff --git a/tests/unit_tests/agentserver/test_sandbox_workspace_isolation.py b/tests/unit_tests/agentserver/test_sandbox_workspace_isolation.py
new file mode 100644
index 0000000000..fe1e1eff37
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_sandbox_workspace_isolation.py
@@ -0,0 +1,40 @@
+"""Sandbox reuse must follow the tenant workspace mounted in its policy."""
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter import sysop_builder as builder
+
+
[email protected]("project", [None, "shared-project"])
+def test_enterprise_isolation_includes_workspace(tmp_path, monkeypatch, project):
+ monkeypatch.setattr(builder, "is_enterprise", lambda: True)
+ project_dir = tmp_path / project if project else None
+ if project_dir:
+ project_dir.mkdir()
+ a, b = tmp_path / "a", tmp_path / "b"
+ key = builder._sandbox_isolation_custom_id
+ assert key(project_dir, shared_dir=a) != key(project_dir, shared_dir=b)
+ assert key(project_dir, shared_dir=a) == key(project_dir, shared_dir=a / ".")
+ monkeypatch.setattr(builder, "get_agent_root_dir", lambda: a)
+ assert key(project_dir) == key(project_dir, shared_dir=a)
+
+
+def test_personal_default_project_sharing_unchanged(tmp_path, monkeypatch):
+ monkeypatch.setattr(builder, "is_enterprise", lambda: False)
+ key = builder._sandbox_isolation_custom_id
+ assert key(tmp_path, shared_dir=tmp_path / "a") == key(tmp_path, shared_dir=tmp_path / "b")
+ monkeypatch.setattr(builder, "_resolve_project_dir", lambda project: None)
+ assert key(None, shared_dir=tmp_path / "a") == "project_default"
+
+
+def test_sandbox_cards_use_workspace_isolation(tmp_path, monkeypatch):
+ monkeypatch.setattr(builder, "is_enterprise", lambda: True)
+ monkeypatch.setattr(builder, "build_filesystem_policy", lambda *a, **kw: ({}, []))
+ monkeypatch.setattr(builder, "build_process_policy", lambda: {})
+ cards = [builder.create_sandbox_sysop_card(
+ "http://sandbox.invalid", "jiuwenbox", shared_dir=tmp_path / tenant,
+ ) for tenant in ("a", "b", "a")]
+ assert all(card is not None for card in cards)
+ keys = [card.gateway_config.isolation.custom_id for card in cards]
+ assert keys[0] != keys[1]
+ assert keys[0] == keys[2]